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
5EnZO5IkcaY
okay let code number 14 60 make two arrays equal by reversing sub arrays we arrays equal by reversing sub arrays we have to erase we can reverse any sub have to erase we can reverse any sub array of one of them and the question is array of one of them and the question is can we obtain the second one okay well can we obtain the second one okay well if they're not of equal lengths we if they're not of equal lengths we cannot obtain any one of them of course cannot obtain any one of them of course and then there is the second idea so we and then there is the second idea so we can perform that operation as many times can perform that operation as many times as we want and at the same time it's as we want and at the same time it's very important to notice the fact that very important to notice the fact that reversing a sub array of length two is reversing a sub array of length two is swapping the elements and as we all know swapping the elements and as we all know we can actually sort or rather obtain we can actually sort or rather obtain anything we want any every one but only anything we want any every one but only swapping the two adjacent elements so swapping the two adjacent elements so the question is whether they are of the question is whether they are of equal length and can contain the same equal length and can contain the same number of the same elements so for number of the same elements so for checking that out we will do something checking that out we will do something very simple it will sort both of them are that end and we just need to check whether they are the same or not completely the same and the first check would be nice that their sizes are not equal the answer is definitely false okay so if they are equal the question is do they have different elements since they are sorted if they do not match for even at least one positions then we'll never be able to obtain one one from the other so in for a it doesn't equal the target and after this if none of them crashed and after this if none of them crashed and it's definitely true and it's definitely true so now let's see where did the screw-up wisent Avangate where did the screw-up wisent Avangate force like this doesn't make any sense force like this doesn't make any sense whatsoever sort swords move if they're whatsoever sort swords move if they're not equal return false oh my god not equal return false oh my god it's multitasking it's little bit tough it's multitasking it's little bit tough here okay here okay things happen okay good enough
2024-03-21 02:49:52
1,460
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 1460 Make Two Arrays Equal by Reversing Sub arrays
njpHIBDckrU
hello everyone i'm bihan chakravarti and today i'll be discussing problem number today i'll be discussing problem number 454 from late code that is for some two 454 from late code that is for some two so this is february 2022's day three so this is february 2022's day three problem and it's a medium level problem problem and it's a medium level problem as you can see so let's get started as you can see so let's get started so in this problem we have been given so in this problem we have been given four arrays num one two three four and four arrays num one two three four and we have to return all we have to return all like return the number of tuples i j k l like return the number of tuples i j k l such that the sum of i uh like ith such that the sum of i uh like ith number from nums one j th number from number from nums one j th number from nums to like that nums to like that the sum of four numbers equals to zero the sum of four numbers equals to zero okay so this is the question like numbs okay so this is the question like numbs one of i numbers two of j numbers three one of i numbers two of j numbers three of k plus number 4 of of k plus number 4 of l so we have to use each index from each l so we have to use each index from each area like we cannot take two elements area like we cannot take two elements from a single idea we have to take one from a single idea we have to take one element from each array and get element from each array and get the sum as zero so the sum as zero so the approach is very simple now let me the approach is very simple now let me go to my editor here go to my editor here okay so okay so suppose i have suppose i have x plus y x plus y equals to 0 equals to 0 so what are my possible values of x now so what are my possible values of x now this can be infinite but this can be infinite but the way uh like what can be possible the way uh like what can be possible value of x it can be value of x it can be only minus of y because only then i can only minus of y because only then i can write minus y plus y equals to zero so write minus y plus y equals to zero so if i have y that means my x will be if i have y that means my x will be minus y so for any given value of y minus y so for any given value of y x should be its negative x should be its negative okay so okay so suppose i have two arrays nums one and suppose i have two arrays nums one and two initially okay so this is 1 and this two initially okay so this is 1 and this is 2 is 2 so so suppose i take two numbers from here suppose i take two numbers from here let me call the numbers i and j okay let me call the numbers i and j okay i and j i and j once summed it becomes uh like let me once summed it becomes uh like let me denote it as x denote it as x so if i have x so if i have x and suppose i have three and suppose i have three and four here and four here the third and fourth adding the third and fourth adding now now we can check for every index of k and l we can check for every index of k and l using uh two nested loops we can check using uh two nested loops we can check that which element sum is negative of x that which element sum is negative of x like it should be k plus like it should be k plus l should be l should be minus of x now only then i can say that minus of x now only then i can say that x plus x plus like i plus j plus k plus l equals to 0 like i plus j plus k plus l equals to 0 only then i can say that right so what we will do here is that initially calculate all the possible sums from the array one and two okay we will use two nested loops and we will like check for with zero with zero then zero with one zero with two then one with one one with two like that so we will have all sums of all the indices then we will store that in a map and store its frequency as well and i'll get back to the frequency after a bit so once we have that stored then we can again do a nested loop in three and four and check like for every sum k plus l we can check whether there exists a sum in 1 plus 2 like 1 and 2 as well like there exists a sum k plus l which is equals to negative of i plus j we have to check that in the hash map and if we have that we can simply write that our answer variable answer plus equals to map of like hashmap of that key map of negative x now why we are writing this now let me uh like you one can argue that we can use sets here as well right to store only the elements and why you need the frequency that is because uh suppose uh there's a test case just yeah so observe these cases here let me yeah so observe these cases here let me zoom in zoom in yeah so these are the four arrays and yeah so these are the four arrays and let's consider let's consider 0 of num1 0 of num1 0 of num2 with 0 of num2 with 1 of num3 and 0 of num4 so let me write 1 of num3 and 0 of num4 so let me write that that comma comma zero from num1 zero from num1 and num2 and here and num2 and here one comma zero okay one comma zero okay now we have minus ones here so let me now we have minus ones here so let me show another show another possibility now i choose minus one here possibility now i choose minus one here again and minus one this one but this again and minus one this one but this time i choose the second one from nums time i choose the second one from nums one so it will be one one so it will be one comma zero and i'll keep the ones as comma zero and i'll keep the ones as same so one comma zero so as you can see same so one comma zero so as you can see there are two possibilities here but if there are two possibilities here but if i store this in a set then i store this in a set then it will store only unique elements so it will store only unique elements so there will be only one so the count there will be only one so the count would be one but i need the count as two would be one but i need the count as two so i need to keep the frequency of the so i need to keep the frequency of the same thing same thing so that is why we are using a hash map so that is why we are using a hash map so let's take a look in the code we have so let's take a look in the code we have empty hash map initially empty hash map initially okay okay so so so first of all we traverse the first so first of all we traverse the first two two arrays that is nums one and two and arrays that is nums one and two and inside that i just increase the counter inside that i just increase the counter so so it is equivalent in c plus plus is it is equivalent in c plus plus is equivalent to hash of equivalent to hash of norms one plus norms one plus nums nums plus equals to 1 plus equals to 1 in c plus plus it's like this okay so in c plus plus it's like this okay so i'm just incrementing the counter of i'm just incrementing the counter of this key nouns 1 plus num2 now after this key nouns 1 plus num2 now after this is done i initialize a answer this is done i initialize a answer variable it's a counter variable that variable it's a counter variable that will store our answer now we traverse will store our answer now we traverse the ideas three and four numbers three the ideas three and four numbers three and nums four inside that we check and nums four inside that we check first of all we sum nums three of i and first of all we sum nums three of i and nums four of j and then we nums four of j and then we make it like change its sign so if it make it like change its sign so if it spots it positive it becomes negative spots it positive it becomes negative and if it's negative it becomes positive and if it's negative it becomes positive then we check whether the inverse value then we check whether the inverse value exists in the hash map or not if it exists in the hash map or not if it exists then we just get its key and sum exists then we just get its key and sum that value because we sum that frequency that value because we sum that frequency to the answer so suppose to the answer so suppose here here num 1 plus num2 equals to num 1 plus num2 equals to 5 for some instance now 5 for some instance now while i'm here if num 3 plus nums 4 while i'm here if num 3 plus nums 4 becomes minus 5 becomes minus 5 okay suppose i get minus 5 through here okay suppose i get minus 5 through here so my key would be minus 5 into minus 1 so my key would be minus 5 into minus 1 that would be equals to 5 that would be equals to 5 so now we will now since numbers 1 plus so now we will now since numbers 1 plus num2 was 5 it was already in the hashmap num2 was 5 it was already in the hashmap right right so since it's already in the hashmap and so since it's already in the hashmap and now we can check whether this 5 after now we can check whether this 5 after it's inversed we can check if this 5 it's inversed we can check if this 5 exists in the hashmap now if it exists exists in the hashmap now if it exists in the hashmap then in the hashmap then we will increment the counter we will we will increment the counter we will increment the hashmap of 5 we will increment it by the frequency of 5 right so this is the problem if you have any doubts on this problem please comment below i'll be glad to answer all of them i'll try my best to clear your doubts and if you have liked my video and my previous videos please like and subscribe to get further notifications on upcoming videos and i am creating a whole playlist on the february long challenge of lead code so i'll be uploading videos every day so make sure you subscribe to get notifications and yeah as usual see you
2024-03-22 14:40:54
454
https://i.ytimg.com/vi/n…axresdefault.jpg
4Sum II | LeetCode 454 | Hashmap
pLX_Ioz_iMY
So hello what is up guys so happy new year to all of you first of all ok and year to all of you first of all ok and today we will try again new today we will try again new questions new year new what ever you can questions new year new what ever you can call it so let's start without any call it so let's start without any delay ok delay ok delay ok January question, it is easy, it has come ok for us, assign cookie ok, so let's see what is telling us, the question is so amazing, you are an awesome parent, ok brother, you are an amazing father, ok and your Children want some cookie, okay and want to give your children some cookie, you want to give your children some cookie, but you should give each child at most one cookie, so you can give only one cookie to each child, okay, I will Can't eat too much sweet Can't eat too much sweet Can't eat too much sweet son, it's okay, son, it's okay, no one should go, child has a greed factor, GI is no one should go, child has a greed factor, GI is okay, every child is greedy with GI factor, okay, every child is greedy with GI factor, okay, f is the maximum size of a cookie that the child will be okay, f is the maximum size of a cookie that the child will be content with, so GI. content with, so GI. What is the maximum size of the cookie which will make the What is the maximum size of the cookie which will make the child happy yes ok I am happy ok and child happy yes ok I am happy ok and each cookie j has a size i s each cookie j has a size i s j ok so every cookie also has a size s j ok so every cookie also has a size s j ok so if sj is bigger j ok so if sj is bigger Okay, because of the greed of the child, if the child is Okay, because of the greed of the child, if the child is bigger than what I want, then what will that child become content? bigger than what I want, then what will that child become content? Okay, we can assign the we can assign the cookie cookie cookie child eats as much as he wants, then that child will become content. Okay, he should become happy. Your goal is to maximize the number of content children and output the maximum number. So what do we have to do brother, we have more. How many more children can we make happy, we have to tell, okay, and we have to give the number of the same number of children who will become happy, okay, this question is very easy, it seems easy, now see Example one, Example one, Example one, okay, so what is the given size, how much grid do we need, the okay, so what is the given size, how much grid do we need, the first child first child needs one, the second child needs two, and the needs one, the second child needs two, and the third child needs three. Okay, and the second one is third child needs three. Okay, and the second one is given the size. Now we have two cookies given the size. Now we have two cookies whose whose whose two cookies of size one and one okay and one child wants one, I want one, one is saying I want two, one is saying I want brother three, okay so either Look, this is the child, it is okay and if we can give only one cookie, then we will give it to him, this will be our waste because he will not agree, he will not agree, okay, so we will be able to give only one cookie, only one child So the output is one is ok you have So the output is one is ok you have So the output is one is ok you have three children two cookies the greed three children two cookies the greed factor of three children is 1 tooth and even two you factor of three children is 1 tooth and even two you have two cookies since the rate is both one have two cookies since the rate is both one you can only make the child whose greed you can only make the child whose greed factor is one content you need to factor is one content you need to factor is one content you need to ok, I have understood brother, there is no problem here, now let's see this second example, ok grid is one, two more cookies are on our 1 2 3, ok so there is one, ok Pass two is okay and Pass two is okay and Pass two is okay and how much is the grade One is okay two and three how much is the grade One is okay two and three is okay so this brother give it this give it this two is okay so this brother give it this give it this two children's book has calmed down two we have output the children's book has calmed down two we have output the matter is not over okay but but but but matter is not over okay but but but but now here now here now here look, all the cases we have are fine, till now what do you see in both the examples that it is sorted but it is not necessary that it will be sorted, let's assume that our grid is 4th, it is fine, 5, 6, 1, 2, it is fine and 4th, it is fine, 5, 6, 1, 2, it is fine and 4th, it is fine, 5, 6, 1, 2, it is fine and cookies, the size of the cookies is us 6 2 1 8 4 F Okay, let's assume this is okay, then how many children will we be able to make happy? Okay, so see what is coming in my mind here, Well, brother, if we Well, brother, if we Well, brother, if we sort both of them, it's okay, if we sort both of them, it's okay, if we sort this too, it's okay, and if we sort this too, it's okay. sort this too, it's okay, and if we sort this too, it's okay. Now after sorting this, Now after sorting this, what will happen? 2, 3, 4, 5 and 6, okay, after sorting this, the what will happen? 2, 3, 4, 5 and 6, okay, after sorting this, the tooth will come. tooth will come. tooth will come. 5 sx 8 Okay, he will come, he will come, so let's see, we can give the lowest p to the lowest, okay, then it will not be like that we have given brother fifth cookie to brother one, now when he is So we have to give a bigger one. Are you able to So we have to give a bigger one. Are you able to So we have to give a bigger one. Are you able to understand? Okay, if you understand? Okay, if you understand, here six of our understand, here six of our cookies will be divided, here all will be divided. cookies will be divided, here all will be divided. Look, we have given one, it is okay for one, two is okay, Look, we have given one, it is okay for one, two is okay, we have given two, it is okay. we have given two, it is okay. we have given two, it is okay. given what letters, let us assume that we have given four, okay, to four, we have given F, to five, we have given six, and to six, we have given A, everyone will be happy, yes, all the There is no problem, There is no problem, There is no problem, okay, so here we have something in okay, so here we have something in mind about sorting, okay, mind about sorting, okay, if we sort, we can do something, if we sort, we can do something, okay, so okay, so we have to put a check, okay, we have to put a check, okay, one of our checks. one of our checks. one of our checks. S A of A is greater than Eq A. Okay, now you mean the basic idea has come, now after this we will understand the code better. Okay, so first of all, what did we talk about, friend, first of all, what did we talk about, friend, both of them. both of them. Sort both of them. Okay, so Sort both of them. Okay, so look. Cert is G of G. Okay, from the beginning of G to G. End, we have set. Our first one is set. Our first one is sorry or wrong, so with this, our G has become From beginning to end, From beginning to end, look, okay, now see what we look, okay, now see what we can do, now we run the loo, can do, now we run the loo, okay, we take it, and it's okay, we will run it. P and a we will run s p ok aa P and a we will run s p ok aa lesson g dot begin lesson g dot begin ok end end kya b sorry sorry sa and j len add size ok ok brother this one thing we have size ok ok brother this one thing we have made a loop ok now see if if made a loop ok now see if if a off i a off sorry j a off i a off sorry j a off i a off sorry j Greater than equal to G of G of I Okay, so what happened to us friend, the child's grid got filled, okay, so what will we do, so what will we do, we will do it G P I P Ps ok green i plus plus is done and things are going well in the ok f kept watching let's submit and see if it watching let's submit and see if it will work or not a There is There is There is no problem, okay, so I hope you have no problem, okay, so I hope you have understood this thing, it is not so difficult, understood this thing, it is not so difficult, okay, because look what we are doing, the okay, because look what we are doing, the lowest, look at all the lowest grids lowest, look at all the lowest grids here, whenever our grid is being fulfilled. here, whenever our grid is being fulfilled. here, whenever our grid is being fulfilled. one child's grade has been completed, so we kept on increasing it. Okay, so the number of children's grade is getting completed, right, we are increasing it and where are we running our pockets? If it is sorted then it will If it is sorted then it will If it is sorted then it will remain at the lowest position. Okay, now it will remain at the lowest position. What does remain at the lowest position. Okay, now it will remain at the lowest position. What does J's lowest mean? J's lowest mean? Can J complete the lowest grade? If it can, then it is okay. If it cannot, then J is increased, then it will complete it. Understand. it is okay. If it cannot, then J is increased, then it will complete it. Understand. it is okay. If it cannot, then J is increased, then it will complete it. Understand. continue like this, then whatever grid will be completed, we will come and return it at the end, okay, so it is being made like this from here, okay, I will give I will give I will give in the description section, if you in the description section, if you like the video then please like the like the video then please like the video and I will see you in the next one, video and I will see you in the next one, share it with your friends, subscribe the share it with your friends, subscribe the channel and see you tomorrow, okay, this channel and see you tomorrow, okay, this time January batch will take everyone. time January batch will take everyone. time January batch will take everyone. keep doing it friend lead code and I will meet you
2024-03-22 14:44:07
455
https://i.ytimg.com/vi_w…xresdefault.webp
Daily Leetcode Question | 455. Assign Cookies | Day 12 | 1st Jan
lQ6ZUritW70
[Music] hey guys welcome back hey guys welcome back to another video and today we're going to another video and today we're going to be solving the leak code question to be solving the leak code question sort list sort list all right so as the title says we're all right so as the title says we're going to be given a linked list going to be given a linked list and all we need to do is we're going to and all we need to do is we're going to sort it so real quickly given the head sort it so real quickly given the head of the linked list return the list of the linked list return the list after sorting it in ascending order all after sorting it in ascending order all right so follow up so can you sort the right so follow up so can you sort the link list link list in big o and log n time and constant in big o and log n time and constant space space okay so the question itself is pretty okay so the question itself is pretty straightforward we just want to sort straightforward we just want to sort a linked list now there's several a linked list now there's several different ways to that you can use a different ways to that you can use a bubble sort bubble sort insertion sort there's several different insertion sort there's several different sorting algorithms but one thing that we sorting algorithms but one thing that we want to keep in mind is that we want to want to keep in mind is that we want to preferably preferably do it in big o and log n time so do it in big o and log n time so i on the top of my head there's two i on the top of my head there's two algorithms that come to my mind algorithms that come to my mind which can complete it in such a time which can complete it in such a time complexity one of them is quick sort and complexity one of them is quick sort and the other one the other one is merge sort so the thing about quick is merge sort so the thing about quick sort is that even though it's average sort is that even though it's average time complexity is big o of n log n uh time complexity is big o of n log n uh it's uh its worst time complexity is big it's uh its worst time complexity is big o o n squared but on the other hand merge n squared but on the other hand merge sort is consistently sort is consistently big o and log n so that's why we're big o and log n so that's why we're going to be using merge store going to be using merge store and another reason we're going to be and another reason we're going to be using merge sort is because it's a lot using merge sort is because it's a lot easier to do and it's commonly used in easier to do and it's commonly used in linked list questions linked list questions so if you don't know what that is don't so if you don't know what that is don't worry i'll be going through it step by worry i'll be going through it step by step step okay so uh just one example real quickly okay so uh just one example real quickly so we're given four two one three so we're given four two one three we sort it and we get one two three four we sort it and we get one two three four pretty simple pretty simple and this is another example negative one and this is another example negative one five three four zero and it gets sorted five three four zero and it gets sorted so i'll be working with example two here so i'll be working with example two here and i'll be going through it step by and i'll be going through it step by step and show you what it looks like all step and show you what it looks like all right right so this over here is the linked list so this over here is the linked list that we're starting off with negative that we're starting off with negative one one five three four zero and when we want to five three four zero and when we want to perform a merge sort perform a merge sort there's actually two different steps there's actually two different steps that go into performing it that go into performing it now let's just write down the two steps now let's just write down the two steps the first step is going to be a the first step is going to be a splitting step splitting step i'll explain what these actually mean i'll explain what these actually mean and the second step is going to be a and the second step is going to be a merging or sorting step usually it's merging or sorting step usually it's called a merge step called a merge step all right so this is how it's going to all right so this is how it's going to work so basically we're going to be work so basically we're going to be given a linked list given a linked list and what we want to do given a linked and what we want to do given a linked list is that we're going to list is that we're going to break it down the way we break it down break it down the way we break it down is we're going to keep is we're going to keep cutting it down in its halves so we're cutting it down in its halves so we're going to keep going to keep breaking it or splitting it down each breaking it or splitting it down each time by one half time by one half so first let's say this has a length of so first let's say this has a length of n then we would end by two n then we would end by two then end by four and by eight and by 16 then end by four and by eight and by 16 and so on and so forth and we keep and so on and so forth and we keep shortening it now when do we actually shortening it now when do we actually stop shorting it so we're going to stop stop shorting it so we're going to stop shortening shortening our our linked list over here until we our our linked list over here until we get get each of its elements uh by itself right each of its elements uh by itself right so over here we have negative one so over here we have negative one by itself right until we get to such a by itself right until we get to such a point we're going to keep splitting it point we're going to keep splitting it i'll show you what the purpose of doing i'll show you what the purpose of doing this is but in simple words what we're this is but in simple words what we're doing doing is let's say we have a massive problem is let's say we have a massive problem all we're doing all we're doing is we're cutting it down into smaller is we're cutting it down into smaller parts in other words we're dividing all parts in other words we're dividing all of these smaller parts of these smaller parts and it's just a divide and conquer and it's just a divide and conquer strategy we're going to divide it into strategy we're going to divide it into smaller easy to handle parts smaller easy to handle parts then we're going to solve each of these then we're going to solve each of these mini parts by itself mini parts by itself and as we're solving each of these parts and as we're solving each of these parts we're going to converge them and make it we're going to converge them and make it into the final product into the final product that we're trying to get at okay so that we're trying to get at okay so let's just do this first step let's just do this first step which is splitting it okay so in the which is splitting it okay so in the beginning we're going to split it beginning we're going to split it and we're going to divide it by 2. so and we're going to divide it by 2. so this over here is this over here is all one of the halves is going to be uh all one of the halves is going to be uh even and one of them is going to be odd even and one of them is going to be odd so in this case let's say we have so in this case let's say we have negative 1 and 5 so that is going to be negative 1 and 5 so that is going to be one of the splits one of the splits and the other split is going to be three and the other split is going to be three four and zero okay four and zero okay so now the question is did we reach any so now the question is did we reach any of our elements by of our elements by its individual value values the answer its individual value values the answer is no not yet is no not yet so we didn't yet so now in that case so we didn't yet so now in that case what's going to happen what's going to happen is we're going to split it again so over is we're going to split it again so over here let's just focus at this over here here let's just focus at this over here so let's put negative 1 to 5 and when so let's put negative 1 to 5 and when you split this you get you split this you get what two values you get negative 1 by what two values you get negative 1 by itself itself and you also get 5 by itself so in that and you also get 5 by itself so in that case we're going to case we're going to end our split we're not going to be end our split we're not going to be making any more splits so that's going making any more splits so that's going to be it for this half of the linked to be it for this half of the linked list list so now let's go on to the other half so now let's go on to the other half with 3 4 and 0. with 3 4 and 0. so over here we're going to split it and so over here we're going to split it and now when you split it you get 3 by now when you split it you get 3 by itself itself so 3 is also by itself but 4 and 0 are so 3 is also by itself but 4 and 0 are not going to be by itself not going to be by itself so when you split that you get 4 so when you split that you get 4 pointing to 0. so it's still a linked pointing to 0. so it's still a linked list list so now we're going to split this again so now we're going to split this again so only four pointing to zero so only four pointing to zero and that over here gives us four by and that over here gives us four by itself and then zero by itself itself and then zero by itself all right so as you can see we've now all right so as you can see we've now finally reached a point where all these finally reached a point where all these elements are by themselves so negative elements are by themselves so negative one five three four zero one five three four zero and the way that we're actually gonna do and the way that we're actually gonna do this inside of our code is we're gonna this inside of our code is we're gonna be using a be using a we're going to be using a function which we're going to be using a function which is going to be called recursively is going to be called recursively okay and as you can see there's kind of okay and as you can see there's kind of like layers to it and each time we go like layers to it and each time we go lower and lower lower and lower we're getting closer to the individual we're getting closer to the individual values by itself values by itself so this over here is the split part okay so this over here is the split part okay we split everything we split everything into its smallest sections possible and into its smallest sections possible and now what we're going to do now what we're going to do using the split part over here we're using the split part over here we're going to kind of going to kind of build up a new linked list which and build up a new linked list which and this new linked list over here this new linked list over here is going to be our final answer so this is going to be our final answer so this over here over here is going to be sorted so this is our is going to be sorted so this is our sorting or merging step i just drew a sorting or merging step i just drew a line to kind of line to kind of show how the steps are different so we show how the steps are different so we have negative one have negative one five three four zero so how this is five three four zero so how this is going to work is we're going to start going to work is we're going to start off off with the last values that were kind of with the last values that were kind of split apart so what is the last thing split apart so what is the last thing that was split apart over here that was split apart over here so the last thing that was split apart so the last thing that was split apart was 4 and 0. was 4 and 0. so now what we're going to do over here so now what we're going to do over here is we're actually going to sort the very is we're actually going to sort the very last thing that was split apart last thing that was split apart so that is 4 and 0 and we want to sort so that is 4 and 0 and we want to sort it so it so in order to sort that how is it going to in order to sort that how is it going to be so in simple words it's just going to be so in simple words it's just going to be 0 be 0 pointing to 4. that is sorted for a pointing to 4. that is sorted for a version of four pointing the zero but version of four pointing the zero but for the sake of this let's just go for the sake of this let's just go through it a little bit more through it a little bit more methodically so how you would do it methodically so how you would do it is you would have a dummy head and this is you would have a dummy head and this head is just kind of there as a head is just kind of there as a placeholder and we're gonna get rid of placeholder and we're gonna get rid of it later it later so in the beginning it's gonna point to so in the beginning it's gonna point to none and then what we're going to be none and then what we're going to be doing doing is that what is this going to point to is that what is this going to point to so the options we have here so the options we have here are either 4 or 0. so in this case we're are either 4 or 0. so in this case we're going to end up choosing the smallest of going to end up choosing the smallest of them them because we want it in ascending order so because we want it in ascending order so we're gonna end up choosing the value we're gonna end up choosing the value zero and obviously the only other value zero and obviously the only other value left is four left is four so that's how we get our sorted linked so that's how we get our sorted linked list uh and i'll be going through it list uh and i'll be going through it once we have more numbers since once we have more numbers since then it'll make more sense okay so now then it'll make more sense okay so now we're kind of done with this layer over we're kind of done with this layer over here right so now we're gonna go up here right so now we're gonna go up another layer another layer so over here we have three and then we so over here we have three and then we have zero four so have zero four so the aim over here is we have to add the aim over here is we have to add three over here three over here in such a way that it's sorted so how do in such a way that it's sorted so how do we do this so same thing we do this so same thing we're going to have a dummy head and we're going to have a dummy head and what is this what is this and we want to sort this in ascending and we want to sort this in ascending order so if you just look at it it's order so if you just look at it it's obviously going to be 0 3 4. obviously going to be 0 3 4. so let's see how we can do this so you so let's see how we can do this so you can kind of think of these as two can kind of think of these as two different different linked lists so this is one list and linked lists so this is one list and this is list one this is list one so the pointers of each of these are so the pointers of each of these are going to start off at the very first going to start off at the very first value value and what we're going to do is we're and what we're going to do is we're going to choose the smallest between going to choose the smallest between those two pointers those two pointers so in this case we have three at one so in this case we have three at one point here and zero one pointer point here and zero one pointer so what do we choose we choose zero so so what do we choose we choose zero so whatever we choose whatever we choose we're gonna cross out that pointer and we're gonna cross out that pointer and move that pointer move that pointer in that certain linked list to the right in that certain linked list to the right so now our pointer is at four so now our pointer is at four and now we're gonna choose between three and now we're gonna choose between three and four obviously and four obviously three is smaller so then we have three three is smaller so then we have three and then finally and then finally uh we're done with this so obviously the uh we're done with this so obviously the last one we have is four last one we have is four so now we have zero three four so let me so now we have zero three four so let me just erase this and make it so it looks just erase this and make it so it looks better better okay and now by adding three to our okay and now by adding three to our linked list zero comma four in a sorted linked list zero comma four in a sorted manner it's gonna be manner it's gonna be zero three four so basically what's zero three four so basically what's really happening really happening is each time we're going above a level is each time we're going above a level we're sorting that we're sorting that by itself each and every time now by itself each and every time now finally we have finally we have negative one and five you would perform negative one and five you would perform the same steps with the dummy head the same steps with the dummy head but already this is sorted over here so but already this is sorted over here so uh we'll just have it as it is uh we'll just have it as it is so negative one point into five so now so negative one point into five so now let's just go to our final step let's just go to our final step so i'm just going to draw a square so i'm just going to draw a square brackets to kind of identify that these brackets to kind of identify that these are two are two different lists this is linked list one different lists this is linked list one this is length plus two this is length plus two they're both completely different uh for they're both completely different uh for so far so far and we're going to merge them now and by and we're going to merge them now and by merging them we're going to get our merging them we're going to get our final result obviously final result obviously okay so how exactly are we going to okay so how exactly are we going to merge it same steps we have our dummy merge it same steps we have our dummy head head and what is our dummy head going to and what is our dummy head going to point to and in order to go over that point to and in order to go over that we're going to do the same steps we're going to do the same steps since we have two different lists the since we have two different lists the first pointer is going to be at the first pointer is going to be at the first first element of the first list and we're element of the first list and we're going to have one more pointer at the going to have one more pointer at the first element of the second list first element of the second list so we those over there are our two up so we those over there are our two up pointers zero and negative one pointers zero and negative one and which one are we going to choose so and which one are we going to choose so we're going to compare negative one with we're going to compare negative one with zero zero obviously negative one is less than zero obviously negative one is less than zero so the pointer that none is going to so the pointer that none is going to point to point to or in other words the first head value or in other words the first head value is going to be negative one is going to be negative one so since we chose negative one what so since we chose negative one what we're gonna do is we're gonna move this we're gonna do is we're gonna move this pointer pointer to the right by one so in this case now to the right by one so in this case now it's at five it's at five so and we keep doing the same steps so and we keep doing the same steps compare five with zero compare five with zero obviously zero is less than five so in obviously zero is less than five so in that case negative one is going to be that case negative one is going to be pointing to zero pointing to zero and the reason this method actually and the reason this method actually makes sense is because at our lower makes sense is because at our lower levels levels we already sorted each of these linked we already sorted each of these linked lists so as we're building it up lists so as we're building it up it just makes it a lot easier to it just makes it a lot easier to actually merge these two together actually merge these two together all right so now we have zero so in that all right so now we have zero so in that case the pointer moves to the right by case the pointer moves to the right by one one now we're doing five and three three is now we're doing five and three three is still less than the five still less than the five and then we move it to the right again and then we move it to the right again now we have four now we have four and we're completely done with this link and we're completely done with this link post over here so we have no other post over here so we have no other option but to add this over here option but to add this over here and that's exactly what we have and if and that's exactly what we have and if you just look at this linked list that you just look at this linked list that we have over here we have over here that is exactly the same as our answer that is exactly the same as our answer which is negative one which is negative one zero three four five and if you just zero three four five and if you just look at it it's sorted look at it it's sorted in ascending order okay so hopefully you in ascending order okay so hopefully you understood how this work uh works understood how this work uh works and there's two different ways to do and there's two different ways to do this uh you could uh this uh you could uh you could do it recursively or you could you could do it recursively or you could do it iteratively do it iteratively and uh we'll be absolving it recursively and uh we'll be absolving it recursively because that's usually because that's usually a little bit easier at least in terms of a little bit easier at least in terms of code before we actually go into the code code before we actually go into the code part i just want to go over the part of part i just want to go over the part of how exactly do we make the split so in how exactly do we make the split so in order to do this we're going to be order to do this we're going to be having three different pointers having three different pointers or actually variables so one of them is or actually variables so one of them is going to be a slow pointer going to be a slow pointer we're going to have a fast pointer and we're going to have a fast pointer and we're going to have a pointer we're going to have a pointer which is going to keep track of the which is going to keep track of the previous slow position that we were on previous slow position that we were on so i'll just call that p okay so just so i'll just call that p okay so just for the sake of representation just for the sake of representation just think of these as different levels think of these as different levels so anything in this level would refer to so anything in this level would refer to slow anything in this level slow anything in this level level would be referring to fast and level would be referring to fast and then this for the previous pointer then this for the previous pointer all right so now that we have this let's all right so now that we have this let's see how we can actually use these see how we can actually use these pointers pointers to actually divide the list so what's to actually divide the list so what's going to happen is that over here going to happen is that over here our slow pointer and the fast pointer our slow pointer and the fast pointer are all both going to start are all both going to start at a value at the head node at a value at the head node so in this case they both start at so in this case they both start at negative one now the reason the fast negative one now the reason the fast pointer is considered to be fast pointer is considered to be fast is because it's going to move two steps is because it's going to move two steps for every one step that the slow pointer for every one step that the slow pointer moves moves so if you move this little pointer to so if you move this little pointer to the right by one the fast pointer is the right by one the fast pointer is going to move to the right by two going to move to the right by two so now in this case in the very so now in this case in the very beginning this uh the p pointer is not beginning this uh the p pointer is not going to have any value going to have any value so now let's go on to the next iteration so now let's go on to the next iteration so in this case we so in this case we move the slow pointer to the right by move the slow pointer to the right by one perfect one perfect and now after that what's going to and now after that what's going to happen is that we're going to move the happen is that we're going to move the fast pointer fast pointer to the right by two so we move it to to the right by two so we move it to five and then three so this is over here five and then three so this is over here right now right now and what is going to be the previous and what is going to be the previous pointer so the previous pointer is going pointer so the previous pointer is going to be the previous location of the slow to be the previous location of the slow pointer pointer so currently it's going to be right over so currently it's going to be right over here so our previous pointer is going to here so our previous pointer is going to be at negative one be at negative one all right so now let's go on to the next all right so now let's go on to the next iteration so the slow pointer is now iteration so the slow pointer is now going to move to the right by one so going to move to the right by one so we're gonna be over here we're gonna be over here the fast pointer is gonna move to the the fast pointer is gonna move to the right by two so one right by two so one two so now it's over here and now again two so now it's over here and now again the previous pointer what's gonna happen the previous pointer what's gonna happen is gonna go to the previous location is gonna go to the previous location which in this case is five which in this case is five so currently the previous point over so currently the previous point over here is five so here is five so actually what happens over here is we actually what happens over here is we end up stopping so when exactly do we end up stopping so when exactly do we stop so to understand that stop so to understand that we have two different conditions so one we have two different conditions so one condition is when the next values in condition is when the next values in this case technically this case technically this will be pointing to none so the this will be pointing to none so the next value over here is none next value over here is none for the fast pointer so in that case for the fast pointer so in that case that means that we're going to stop so that means that we're going to stop so we can't really do anything we can't really do anything but there might be some instances where but there might be some instances where the fast pointer the fast pointer is the is on the none pointer in that is the is on the none pointer in that case as well case as well we are going to stop so if the next node we are going to stop so if the next node to the fast pointer is none to the fast pointer is none or the current node of the fast pointer or the current node of the fast pointer is none in that case we're going to stop is none in that case we're going to stop iterating through it iterating through it so in this case we're going to currently so in this case we're going to currently stop so let's just see where everything stop so let's just see where everything finally is finally is so our p pointer is over here our so our p pointer is over here our slow pointer is over here and the fast slow pointer is over here and the fast pointer is over here pointer is over here now what really matters over here is now what really matters over here is actually the p actually the p pointer the previous value that we're pointer the previous value that we're looking for so what's gonna happen what looking for so what's gonna happen what we're gonna do we're gonna do is we have one five three four zero nine is we have one five three four zero nine so what we're gonna do over here so what we're gonna do over here is we're gonna take negative one oh is we're gonna take negative one oh sorry i meant to say negative one sorry i meant to say negative one then we have five and we're gonna take then we have five and we're gonna take whatever the p value whatever the p value is and its next element is going to is and its next element is going to become none become none so 5 is not going to point to 3 anymore so 5 is not going to point to 3 anymore instead it's going to be pointing to instead it's going to be pointing to none and what that basically means none and what that basically means is that we have our own linked list over is that we have our own linked list over here similarly over here what's going to here similarly over here what's going to happen happen is the three since nothing's funny to it is the three since nothing's funny to it it's gonna be the head note so three it's gonna be the head note so three points to four points to four points to zero points to none okay which points to zero points to none okay which is uh exactly basically splitting it is uh exactly basically splitting it in half uh if you want to go through it in half uh if you want to go through it one more time real quickly one more time real quickly i'll do it super fast over here so three i'll do it super fast over here so three four zero so we have a slow pointer fast four zero so we have a slow pointer fast pointer pointer flow pointer moves to the right by one flow pointer moves to the right by one fast pointer moves fast pointer moves right by two and obviously the next right by two and obviously the next value to this value to this is none so then we stop iterating is none so then we stop iterating through it and the previous value would through it and the previous value would be at three so in that case be at three so in that case we would have three pointing to none we would have three pointing to none that would be one thing that would be one thing and the other thing that we would have and the other thing that we would have is four pointing to zero point two none is four pointing to zero point two none so hopefully that makes sense and let's so hopefully that makes sense and let's just see that in code right now just see that in code right now all right so let's start with our code all right so let's start with our code and the first thing that we're going to and the first thing that we're going to do is we're going to have our splitting do is we're going to have our splitting function function and i'll just do that over here and for and i'll just do that over here and for the merge function we'll make a separate the merge function we'll make a separate function function okay so over here the first thing that okay so over here the first thing that we're going to do is we're going to we're going to do is we're going to check check if we do not actually have a head value if we do not actually have a head value or or head dot next does not exist or not head head dot next does not exist or not head dot next dot next and why exactly are we doing this and in and why exactly are we doing this and in this case we're just going to end up this case we're just going to end up returning head returning head so the answer to that is pretty simple so the answer to that is pretty simple so let's say we have some sort of linked so let's say we have some sort of linked list list which has nothing inside of it or if it which has nothing inside of it or if it just has one value just has one value so if any of those two conditions are so if any of those two conditions are true what that means is that the linked true what that means is that the linked list itself list itself and its sorted version are exactly going and its sorted version are exactly going to be the same because when you have to be the same because when you have only one value only one value it's going to be exactly the same as the it's going to be exactly the same as the sorted version so this over here sorted version so this over here is what we're going to use and it's also is what we're going to use and it's also going to help us while we're going to help us while we're recursing through our function okay so recursing through our function okay so after this after this we want to define our three variables so we want to define our three variables so we have the p we have the p variable which holds the previous value variable which holds the previous value of the slow head of the slow head slow pointer so i'll just call that p uh slow pointer so i'll just call that p uh then after that we're going to have our then after that we're going to have our slow pointer slow pointer and we're also going to have our fast and we're also going to have our fast pointer so p is going to start off at pointer so p is going to start off at none uh none uh you could also make it start at head i you could also make it start at head i think that should also work but think that should also work but um then slow is going to start off at um then slow is going to start off at the head itself the head itself and fast is also going to start off at and fast is also going to start off at the head sorry the head sorry okay okay so we defined all of our okay okay so we defined all of our variables and now we're going to go variables and now we're going to go inside the while loop inside the while loop so what are the conditions for our while so what are the conditions for our while loop so we keep going loop so we keep going until the fast pointer actually has a until the fast pointer actually has a value value or if fast dot next is not none so or if fast dot next is not none so while fast and fast dot next what that's while fast and fast dot next what that's telling us telling us is that fast uh currently has a value is that fast uh currently has a value and fast dot next and fast dot next is not none right sorry i can't spell is not none right sorry i can't spell okay okay now after we have this we want to now after we have this we want to redefine our functions redefine our functions so what is going to happen to p so p so what is going to happen to p so p over here is now going to be over here is now going to be the value of the slow variable or the value of the slow variable or pointer pointer because p always holds the previous because p always holds the previous value of the slow pointer so we have value of the slow pointer so we have that that now after this we're going to change the now after this we're going to change the slow pointer and obviously the slow slow pointer and obviously the slow pointer all it does it moves to the pointer all it does it moves to the right by one right by one so slow equals to slow dot text pretty so slow equals to slow dot text pretty easy easy now we have to change the value of the now we have to change the value of the fast pointer which in this case we're fast pointer which in this case we're moving the fast pointer by two moving the fast pointer by two so fast dot next dot next perfect so fast dot next dot next perfect so by the ending of this we're going to so by the ending of this we're going to have the finalized versions of the p have the finalized versions of the p value this low value and the fast volume value this low value and the fast volume and what we're going to do over here and what we're going to do over here p dot next is going to end up equal into p dot next is going to end up equal into none none and what that's basically telling us is and what that's basically telling us is that we kind of split up our that we kind of split up our linked list into two different parts linked list into two different parts perfect so we have this over here perfect so we have this over here all right so after we have this over all right so after we have this over here what we want to do is we actually here what we want to do is we actually want to be calling want to be calling our merge function so how exactly we're our merge function so how exactly we're going to call our going to call our merge function so i'll be making the merge function so i'll be making the function later before we do that function later before we do that we're going to call it over here so we're going to call it over here so we're going to return that value we're going to return that value and i'll just call this function over and i'll just call this function over here merge and what are we exactly going here merge and what are we exactly going to be giving inside of our to be giving inside of our merged values so in simple words to our merged values so in simple words to our merged value we're going to be giving it merged value we're going to be giving it the two parts or the divisions that we the two parts or the divisions that we made inside made inside of this sort list function over here so of this sort list function over here so what exactly are the two divisions so what exactly are the two divisions so let's just go back to the sketchbook let's just go back to the sketchbook over here and as you can see let's say over here and as you can see let's say in the first instance we have two in the first instance we have two divisions divisions negative one comma five and three comma negative one comma five and three comma three four zero three four zero right so negative one to five where does right so negative one to five where does it start at it start at so this over here starts at the head so so this over here starts at the head so we have that we have that and where does three start at so this and where does three start at so this three over here three over here starts at the slow pointer so as you can starts at the slow pointer so as you can see the slow pointer ends up over here see the slow pointer ends up over here so the three is also starting at the so the three is also starting at the slow pointer slow pointer so let's just use that knowledge that we so let's just use that knowledge that we have and those are what we're going to have and those are what we're going to be giving our function be giving our function so over here we're going to call this so over here we're going to call this function so self function so self dot sort list and we're going to be dot sort list and we're going to be calling it calling it on the head so that is going to be one on the head so that is going to be one half and the second half that we have half and the second half that we have is going to be starting from the slow is going to be starting from the slow value value so self dot sort list and then we're so self dot sort list and then we're going to be giving it slope going to be giving it slope okay so now you might be confused about okay so now you might be confused about why are we actually calling the sort why are we actually calling the sort list function over here list function over here so in other words all sort list is doing so in other words all sort list is doing uh just to be clear uh just to be clear it's actually splitting down our values it's actually splitting down our values now the reason we're recursively calling now the reason we're recursively calling this is when exactly is this going to this is when exactly is this going to stop stop so this is going to keep going until so this is going to keep going until this this condition over here actually happens so condition over here actually happens so if not head if not head or not head.next what that means is that or not head.next what that means is that if we only have one value if we only have one value or if we have no value at all only then or if we have no value at all only then we're just going to directly return the we're just going to directly return the head that we have head that we have and that is going to stop this function and that is going to stop this function over here over here so what that's basically doing for us is so what that's basically doing for us is we're going all the way we're going all the way down to the bottom so we're going to be down to the bottom so we're going to be going all so we're going to recursively going all so we're going to recursively be calling be calling this function all the way until we reach this function all the way until we reach the very bottom which in this case is the very bottom which in this case is negative 1 negative 1 5 3 4 0 so the numbers by themselves 5 3 4 0 so the numbers by themselves so we're going to keep going until then so we're going to keep going until then and each time that we're doing that and each time that we're doing that we're going to be calling the self.merge we're going to be calling the self.merge function which function which very easily for us is going to be taking very easily for us is going to be taking these two halves these two halves and it's going to merge it into one for and it's going to merge it into one for us so yeah so all we really have left to us so yeah so all we really have left to do right now is to actually make our do right now is to actually make our merge function merge function so let's call it merge and it's going to so let's call it merge and it's going to take self take self and obviously we want to give it two and obviously we want to give it two different linked lists right different linked lists right so in order to do that i'll just call so in order to do that i'll just call one of them l1 and i'll call the second one of them l1 and i'll call the second one l2 one l2 pretty simple so inside of this function pretty simple so inside of this function we're going to be having our dummy node we're going to be having our dummy node that we were talking about that we were talking about and the dummy node just helps us to and the dummy node just helps us to actually form our final linked list actually form our final linked list and just a quick reminder reminder and and just a quick reminder reminder and just a quick reminder just a quick reminder we're taking two linked lists and making we're taking two linked lists and making it into one it into one so what is this dummy node going to be so what is this dummy node going to be so we want to make it an so we want to make it an object of the list node and how exactly object of the list node and how exactly are we making this well it's predefined are we making this well it's predefined for us over here for us over here so we can just use that okay and the so we can just use that okay and the value for this is just going to be none value for this is just going to be none sorry and over here we're also going to sorry and over here we're also going to have have one more node and i'll call this a one more node and i'll call this a current node current node and the purpose of this node over here and the purpose of this node over here is going to be to kind of is going to be to kind of find out what node we're currently on find out what node we're currently on all right all right so now that we have all of this we're so now that we have all of this we're going to go inside actually creating going to go inside actually creating our linked list so we're going to go our linked list so we're going to go inside of a while loop inside of a while loop and this while loop is going to check if and this while loop is going to check if we have a value for l1 we have a value for l1 and if we have a value for l2 the reason and if we have a value for l2 the reason that we're doing this is because we're that we're doing this is because we're going to keep going going to keep going until we reach the ending for either one until we reach the ending for either one of the lists of the lists so let's say we reach the ending of list so let's say we reach the ending of list one and we're going to stop over there one and we're going to stop over there and after that we're going to go to the and after that we're going to go to the value in list 2 value in list 2 and add it to our linked list so over and add it to our linked list so over here we had our pointer so here we had our pointer so what happened over here let's say this what happened over here let's say this is l1 and this is l2 is l1 and this is l2 what happened is that this over here got what happened is that this over here got depleted before depleted before l1 so we used up everything over here so l1 so we used up everything over here so in that case we're going to stop in in that case we're going to stop in going through our while loop going through our while loop and in that case we're going to have one and in that case we're going to have one extra element remaining which in this extra element remaining which in this case is the value case is the value 5 over here and that's what we're going 5 over here and that's what we're going to end up adding to the remaining of our to end up adding to the remaining of our linked list linked list okay so let's just do that real quickly okay so let's just do that real quickly so while l1 and l2 so while l1 and l2 so we have that over there over here so we have that over there over here we're going to compare the values of l1 we're going to compare the values of l1 and l2 so we're going to do l1 dot val and l2 so we're going to do l1 dot val so in the beginning it refers to the so in the beginning it refers to the head node head node so if one dot val is greater than so if one dot val is greater than l two dot val what does that mean so in l two dot val what does that mean so in that case we're always going to choose that case we're always going to choose the smallest value the smallest value and in this case that's gonna be l2 and in this case that's gonna be l2 since l1 is greater than l2 that means since l1 is greater than l2 that means l2 is a smaller value l2 is a smaller value and since we're choosing the l1 value and since we're choosing the l1 value what we're going to do what we're going to do is our current dot next node so is our current dot next node so we have our current node which in this we have our current node which in this case starts off at the very beginning case starts off at the very beginning so current.next is now going to have the so current.next is now going to have the same value same value as l2 and that's obviously because l2 is as l2 and that's obviously because l2 is less than l1 less than l1 and the other thing that it's going to and the other thing that it's going to change is since we're choosing the value change is since we're choosing the value from l2 from l2 we're going to change the pointer that we're going to change the pointer that is in l2 is in l2 so in the beginning let's say we were so in the beginning let's say we were pointing at the head node pointing at the head node we're going to move to the right by one we're going to move to the right by one so and to do that we're just going to do so and to do that we're just going to do l2 dot next l2 dot next now finally over here we're going to now finally over here we're going to have an else condition which refers to have an else condition which refers to the case where l2 the case where l2 is greater than l1 and in order to do is greater than l1 and in order to do that what's going to happen is current that what's going to happen is current dot next is going to equal to l1 over dot next is going to equal to l1 over here here because l1 is smaller and the same thing because l1 is smaller and the same thing is going to happen we're going to move is going to happen we're going to move l1's pointer l1's pointer to the right by one so l1 is now going to the right by one so l1 is now going to be equal to be equal to l1 dot next all right perfect so now to l1 dot next all right perfect so now that we're done with this that we're done with this if else statement over here one more if else statement over here one more thing that's going to happen is that we thing that's going to happen is that we actually have to move actually have to move our current node that we have so we can our current node that we have so we can just let it be in the same place just let it be in the same place so to move it to the right by one so to move it to the right by one current is now going to be equal current is now going to be equal to current dot next so this over here is to current dot next so this over here is going to be or should be the ending for going to be or should be the ending for our while loop our while loop so that over there by the ending of it so that over there by the ending of it we should get a linked list we should get a linked list but what happens is that we actually but what happens is that we actually don't get all of the values don't get all of the values so what we want to do now is we're at so what we want to do now is we're at our current value our current value and what we're going to check is if l1 and what we're going to check is if l1 exists exists so if the by the ending of this l1 does so if the by the ending of this l1 does not have a value of none not have a value of none then in that case what we're going to do then in that case what we're going to do is current dot is current dot next is going to equal to l1 and over next is going to equal to l1 and over here we're going to check here we're going to check if l2 exists so over here we're checking if l2 exists so over here we're checking for l1 for l1 existing and if it does exist well we're existing and if it does exist well we're going to do current.next equals l1 going to do current.next equals l1 and if l2 exists we're going to do and if l2 exists we're going to do current.next equals l2 current.next equals l2 and actually we could do elsif because and actually we could do elsif because only one of these is going to exist only one of these is going to exist and the reason for that is because our and the reason for that is because our while loop over here says while loop over here says while l1 and l2 so what does that mean while l1 and l2 so what does that mean that means that l1 and l2 for it to stop that means that l1 and l2 for it to stop both l1 and l2 must have been negative both l1 and l2 must have been negative or one of them could have been negative or one of them could have been negative so if they were both actually at a value so if they were both actually at a value of none of none then what that means is that we've then what that means is that we've depleted both of the linked lists depleted both of the linked lists but if only one of them had a value of but if only one of them had a value of none what that means is one of the other none what that means is one of the other linked lists linked lists has not been fully added to the final has not been fully added to the final result result so in order to compensate for that we're so in order to compensate for that we're doing this over here and we're adding doing this over here and we're adding that remaining linked list that remaining linked list so we took care of that and finally so we took care of that and finally we're going to be returning our we're going to be returning our value so what do we return over here so value so what do we return over here so are we going to return our dummy are we going to return our dummy uh node and the answer is no so the uh node and the answer is no so the dummy node was just a placeholder dummy node was just a placeholder and the actual ahead of our linked list and the actual ahead of our linked list starts at the next value so over here starts at the next value so over here we're going to do dummy.next and that is we're going to do dummy.next and that is going to be the head going to be the head of the linked list that we're referring of the linked list that we're referring to and this really should be to and this really should be it so let's submit to our solution and it so let's submit to our solution and as you can see our submission was as you can see our submission was accepted accepted so finally thanks a lot for watching so finally thanks a lot for watching guys do let me know if you have any guys do let me know if you have any questions questions and don't forget to like and subscribe and don't forget to like and subscribe thank you
2024-03-21 12:59:14
148
https://i.ytimg.com/vi_w…xresdefault.webp
Sort List | Leet code 148 | Theory explained + Python code
xBpYKQzjjnM
hey so welcome back and this is another daily code problem so today it was daily code problem so today it was called kids with the greatest number of called kids with the greatest number of candies candies and it's just an easy level problem you and it's just an easy level problem you can actually do it in a one-liner so all can actually do it in a one-liner so all that you're given here is a candies that you're given here is a candies array with a given number of candies for array with a given number of candies for every single I think uh child here and every single I think uh child here and then you have three extra candies that then you have three extra candies that you can give these children you can give these children and all that you want to do is say that and all that you want to do is say that okay we want to return true if we can okay we want to return true if we can give this particular can like this give this particular can like this particular kid it's reaction candies to particular kid it's reaction candies to give it greater than or equal to the give it greater than or equal to the maximum number of candies in this array maximum number of candies in this array so all that means is if you give this so all that means is if you give this child two can or three extra candies child two can or three extra candies it'll have five candies it'll have five candies and because the biggest number in this and because the biggest number in this array is five you want to return true array is five you want to return true because well 5 is greater than or equal because well 5 is greater than or equal to five which is the maximum or the to five which is the maximum or the greatest number of candies in this array greatest number of candies in this array at this step here if you give this child at this step here if you give this child three extra candies it'll have six and three extra candies it'll have six and because five is the greatest number of because five is the greatest number of candies currently and six is greater candies currently and six is greater than that amount you also want to return than that amount you also want to return true true same with five because five plus three same with five because five plus three is eight and eight is bigger than five is eight and eight is bigger than five the only one that you want to return the only one that you want to return false on is one here because if you do false on is one here because if you do one plus three that is less than five so one plus three that is less than five so you wanna return false you wanna return false okay and so to do this you can just do okay and so to do this you can just do in one or two lines here in one or two lines here um I'll just do it um I'll just do it split apart here so the first thing you split apart here so the first thing you want to do is figure out what is the want to do is figure out what is the current maximum in the candies array and current maximum in the candies array and you can just do that by like maximum you can just do that by like maximum candies candies is equal to the maximum of this array is equal to the maximum of this array and that will return five and that will return five and then we just want to return an array and then we just want to return an array of Boolean values and we want to return of Boolean values and we want to return true if the current number of candies true if the current number of candies like like current number is greater than or equal current number is greater than or equal to the maximum candies to the maximum candies after we add after we add the extra candies to it the extra candies to it and so that will Define this kind of our and so that will Define this kind of our function for defining is it true or function for defining is it true or false false and we just want to do this for every and we just want to do this for every candy in our candies array awesome so this runs in oven time awesome so this runs in oven time um if you make a one-liner it'll be like um if you make a one-liner it'll be like oh of N squared because you'll make this oh of N squared because you'll make this you'll be performing this Max operation you'll be performing this Max operation for every iteration so it's good to for every iteration so it's good to split these into two separate lines split these into two separate lines um so this runs an O event time because um so this runs an O event time because to determine the maximum that takes o of to determine the maximum that takes o of n because you have to iterate through n because you have to iterate through every number and then for this you have every number and then for this you have to iterate through every number to see to iterate through every number to see okay if we add this extra candies to okay if we add this extra candies to this current number is it greater than this current number is it greater than or equal to so o of n time and O of one or equal to so o of n time and O of one space so yeah I hope that helped and space so yeah I hope that helped and good luck with the rest your algorithms good luck with the rest your algorithms thanks for watching
2024-03-21 01:24:42
1,431
https://i.ytimg.com/vi/x…axresdefault.jpg
LeetCode 1431 - Kids With the Greatest Number of Candies - Python Solution
28mhRudXtDc
hi everyone welcome to this recorder this is raveena and uh today I am going this is raveena and uh today I am going to solve liquid problem number 32. I to solve liquid problem number 32. I actually selected this problem based on actually selected this problem based on the poll that I did last week uh and the the poll that I did last week uh and the based on the words uh the you guys want based on the words uh the you guys want me to solve string problems so I'm gonna me to solve string problems so I'm gonna do that now I'm I will keep referring do that now I'm I will keep referring back to that post if you wanna just you back to that post if you wanna just you know if you haven't seen it you can go know if you haven't seen it you can go in and just vote on what which problems in and just vote on what which problems do you want me to solve or you can do do you want me to solve or you can do that the same in the comments below and that the same in the comments below and tell me uh what kind of problems you tell me uh what kind of problems you would like uh to see on my channel and I would like uh to see on my channel and I will solve them for you okay so let's will solve them for you okay so let's start by reading the question uh the start by reading the question uh the question says that given a string question says that given a string containing just characters of containing just characters of opening parenthesis and closing opening parenthesis and closing parenthesis return the length of the parenthesis return the length of the longest valid well formed parentheses longest valid well formed parentheses substring okay so let's look at example substring okay so let's look at example one here in example one if you look at one here in example one if you look at this uh we want to find out the length this uh we want to find out the length of the longest valid parenthesis of the longest valid parenthesis substring what does that mean is uh we substring what does that mean is uh we all have done math uh in our school time all have done math uh in our school time so we have to find out what is the valid so we have to find out what is the valid parenthesis substring uh so in this parenthesis substring uh so in this input s you see there there's no there's input s you see there there's no there's an opening bracket okay now there's an opening bracket okay now there's another opening bracket and then a another opening bracket and then a closing bracket uh so if you look at closing bracket uh so if you look at this string you can uh you know make out this string you can uh you know make out that this is a valid substring and and that this is a valid substring and and the length of that valid substring is 2 the length of that valid substring is 2 and that is why the output here is 2. and that is why the output here is 2. uh let's try and see how we can solve uh let's try and see how we can solve this problem uh let me go back to my this problem uh let me go back to my notepad Okay notepad Okay so the example here what I'm taking is I so the example here what I'm taking is I want to actually let me move this want to actually let me move this further okay uh I'm gonna take the further okay uh I'm gonna take the example two which is close name closing example two which is close name closing closing okay closing okay yeah so uh the first thing the that I yeah so uh the first thing the that I want to do is I want to have a left and want to do is I want to have a left and right variable so that I can count how right variable so that I can count how many opening brackets and closing many opening brackets and closing brackets I have so let me do that I have brackets I have so let me do that I have a left initialized to zero I have a a left initialized to zero I have a right parenthesis variable initialized right parenthesis variable initialized to zero to zero the next thing I want to have is the the next thing I want to have is the maximum length variable so I have my maximum length variable so I have my max length max length variable also initialized to zero variable also initialized to zero uh I'm gonna start traversing through uh I'm gonna start traversing through the whole string from left to right the whole string from left to right count the number of you know left and count the number of you know left and right parentheses and at the point where right parentheses and at the point where you my left number of left parenthesis you my left number of left parenthesis is equal to my number of right is equal to my number of right parenthesis that's when I see that oh parenthesis that's when I see that oh it's a valid string right it's a valid it's a valid string right it's a valid parenthesis so for example if you look parenthesis so for example if you look at the if you look at let's look at the at the if you look at let's look at the same one yeah if you look at this same one yeah if you look at this example uh if I at some points this is example uh if I at some points this is uh this means that right is one left is uh this means that right is one left is one right is one left is one right is one right is one left is one right is one right is one so uh if you look at one right is one so uh if you look at this substring this substring it says that opening brackets number of it says that opening brackets number of opening brackets which is 2 is equal to opening brackets which is 2 is equal to number of closing brackets which is two number of closing brackets which is two that means that is for a valid substring that means that is for a valid substring and that condition we are going to use and that condition we are going to use in our for Loop when we see number of in our for Loop when we see number of left uh parenthesis equal to number of left uh parenthesis equal to number of right parenthesis we calculate the right parenthesis we calculate the maximum length uh and then we update the maximum length uh and then we update the maximum length if we have not find a maximum length if we have not find a maximum length yet maximum length yet uh we have we will we also need a uh we have we will we also need a breaking condition here the breaking breaking condition here the breaking condition here would be so suppose if I condition here would be so suppose if I have this example right uh I have a have this example right uh I have a closing bracket so it starts with a closing bracket so it starts with a closing Market I have one opening closing Market I have one opening bracket okay bracket okay then I have another closing bracket then I have another closing bracket so when my closing so is there a chance so when my closing so is there a chance that uh this particular thing is a is that uh this particular thing is a is ever going to be a valid substring ever going to be a valid substring because my number of closing packets are because my number of closing packets are greater than my number of opening greater than my number of opening packets which means that I'm never going packets which means that I'm never going to find that opening bracket somewhere to find that opening bracket somewhere right it should come before the closing right it should come before the closing bracket so that means that if my right bracket so that means that if my right is greater than my left number of is greater than my left number of brackets I mean my left opening brackets I mean my left opening parenthesis which means that this is not parenthesis which means that this is not a valid condition that's the time when a valid condition that's the time when we will reset our right and left to zero we will reset our right and left to zero let's see how we can apply I mean let's let's see how we can apply I mean let's see how to work through it uh it will be see how to work through it uh it will be helpful to learn it better with your helpful to learn it better with your example example first my counter is here first my counter is here uh I receive a closing bracket which is uh I receive a closing bracket which is the right which is right for us so I the right which is right for us so I will update that to one will update that to one I then go to uh then I check if my left I then go to uh then I check if my left is equal to right is my left equal to is equal to right is my left equal to right no it is not okay my next right no it is not okay my next condition to check is add my number of condition to check is add my number of write brackets greater than my number of write brackets greater than my number of left brackets left brackets yes my right brackets are greater than yes my right brackets are greater than number of left brackets that's when I number of left brackets that's when I will reset my left and right to zero will reset my left and right to zero since my left was already 0 I'm gonna since my left was already 0 I'm gonna keep it that way and my right will again keep it that way and my right will again be reset to zero okay moving on to the be reset to zero okay moving on to the next element I I go to the next element next element I I go to the next element which is another opening bracket which is another opening bracket when I received that I have opening when I received that I have opening bracket so I am gonna update my left one bracket so I am gonna update my left one is my left equal to right no is my right is my left equal to right no is my right greater than left no okay let's move on greater than left no okay let's move on so I move on to the next so I move on to the next element in the string I receive one element in the string I receive one closing bracket closing bracket I update my right I update my right with plus 1 so 0 plus 1 is 1. now I with plus 1 so 0 plus 1 is 1. now I check if my left is equal to right yes check if my left is equal to right yes my left is equal to right I have left 1 my left is equal to right I have left 1 and right equal to 1. I will calculate and right equal to 1. I will calculate the maximum length now my maximum length the maximum length now my maximum length will would be maximum of the maximum will would be maximum of the maximum length or my uh you can say left press length or my uh you can say left press right or you can just say right into two right or you can just say right into two or left into two so I would say maximum or left into two so I would say maximum of 0 and my left plus right the maximum of 0 and my left plus right the maximum of 0 and 2 is 2 so I'm gonna update my of 0 and 2 is 2 so I'm gonna update my max length here max length here okay moving on I encounter again an okay moving on I encounter again an opening bracket opening bracket I will update my left to 2 with plus one I will update my left to 2 with plus one is my left equal to right uh no is my is my left equal to right uh no is my right greater than left no right greater than left no okay move on okay move on I go to the next string so the next I go to the next string so the next element I receive a closing bracket then element I receive a closing bracket then I'll update my right to 2. I'll update my right to 2. is my left equal to right yes it is then is my left equal to right yes it is then I calculate the maximum length my I calculate the maximum length my maximum length will be Max of the maximum length will be Max of the existing maximum length or and my left existing maximum length or and my left plus right so maximum of 2 and my left plus right so maximum of 2 and my left plus right is 4 maximum of 2 and 4 is 4. plus right is 4 maximum of 2 and 4 is 4. okay sorry about this okay sorry about this okay maximum of 2 and 4 is 4 so I update okay maximum of 2 and 4 is 4 so I update my maximum length to 4. my maximum length to 4. moving on I again encounter a closing moving on I again encounter a closing bracket since I encounter that I am bracket since I encounter that I am going to increment my right to 3. is my going to increment my right to 3. is my left equal to right no is my right a left equal to right no is my right a greater than left yes greater than left yes that's when I will update my left and that's when I will update my left and right to 0. right to 0. this is first iteration now it can also this is first iteration now it can also happen that a sub substring is valid happen that a sub substring is valid when you go from left to right but so it when you go from left to right but so it is not valid when you go left to right is not valid when you go left to right but there can be scenarios when it will but there can be scenarios when it will be valid when you go from right to left be valid when you go from right to left um so some of the some one case that I um so some of the some one case that I can think of is you know this so suppose can think of is you know this so suppose I start with my uh I start from my left I start with my uh I start from my left I see okay I encountered an opening I see okay I encountered an opening bracket I increment my left again bracket I increment my left again opening bracket okay agreement my left opening bracket okay agreement my left and then I receive a closing bracket and then I receive a closing bracket then I increment my right then I increment my right at this point we don't have we don't at this point we don't have we don't actually come across those two actually come across those two conditions is my right equal to left or conditions is my right equal to left or do I have more write records than my do I have more write records than my left brackets in this scenario we might left brackets in this scenario we might miss our valid substring so that is why miss our valid substring so that is why we are doing two passes one from left to we are doing two passes one from left to right and the other pass from right to right and the other pass from right to left left let's see how we can do it from right to let's see how we can do it from right to left for right to left we are going to left for right to left we are going to do the same thing uh oh sorry my max do the same thing uh oh sorry my max length would be 4 I'm gonna retain that length would be 4 I'm gonna retain that the only things I'm going to change is the only things I'm going to change is my left would be initialized to 0 my my left would be initialized to 0 my right would be initialized to zero and right would be initialized to zero and let me delete this pointers as well okay let me delete this pointers as well okay I'll start from my right most element I'll start from my right most element right most element in the string I right most element in the string I receive a closing bracket receive a closing bracket when I receive a closing bracket I when I receive a closing bracket I increment my right to 1. increment my right to 1. I check if my left is equal to right no I check if my left is equal to right no when I go from right to left does it when I go from right to left does it make sense to check if my number of make sense to check if my number of right brackets are greater than my left right brackets are greater than my left practice uh no uh it would make sense to practice uh no uh it would make sense to check if my number of left brackets are check if my number of left brackets are greater than my right bracket when I greater than my right bracket when I receive an opening bracket I will have receive an opening bracket I will have my initially I will have my left and my initially I will have my left and right initialized to zero when I receive right initialized to zero when I receive an opening bracket I am going to update an opening bracket I am going to update my left to 1. now if you look at the my left to 1. now if you look at the scenario when your you're at the end of scenario when your you're at the end of your string and you receive an opening your string and you receive an opening bracket that means that you have your bracket that means that you have your string has already ended and there is string has already ended and there is never going to be a closing bracket never going to be a closing bracket there and that's why that scenario is there and that's why that scenario is invalid that particular substance is invalid that particular substance is going to be invalid no matter how left going to be invalid no matter how left you go so in this scenario when you go you go so in this scenario when you go from right to left you have to make sure from right to left you have to make sure that your left count never that your left count never um is more than your right count and um is more than your right count and that is really important to understand that is really important to understand you know why you are chain chain why you know why you are chain chain why you're checking for a particular you're checking for a particular condition when you are going from left condition when you are going from left to right and why you are checking the to right and why you are checking the other condition when you're going from other condition when you're going from right to left so I hope this is clear uh right to left so I hope this is clear uh let's uh move on with our example here let's uh move on with our example here let's see let's see I already had my right as one uh let me I already had my right as one uh let me move on to my next element where I have move on to my next element where I have my and I get another closing packet so I my and I get another closing packet so I update my right to two update my right to two I check is my left equal to right no is I check is my left equal to right no is my left greater than right no move on my left greater than right no move on I receive an opening bracket I update my I receive an opening bracket I update my left to one check is left created if if left to one check is left created if if uh is left equal to right no is left uh is left equal to right no is left greater than right no move on greater than right no move on get another closing packet update this get another closing packet update this right to plus 1 which is three uh is my right to plus 1 which is three uh is my left equal to right no is my left left equal to right no is my left greater than right no greater than right no move on move on get another opening bracket get another opening bracket we get two we get two is my left equal to right no left is my left equal to right no left greater than right no move on receive an greater than right no move on receive an uh receive one more closing bracket uh receive one more closing bracket update my right to 4. is my left equal update my right to 4. is my left equal to right no is my left greater than to right no is my left greater than right no right no now we have done our iterations from we now we have done our iterations from we have traversed the string from left to have traversed the string from left to right as well as from right to left and right as well as from right to left and check for our conditions that means that check for our conditions that means that the maximum length that we have is this the maximum length that we have is this maximum length is 4 and so we are going maximum length is 4 and so we are going to return this 4. now let's see how we to return this 4. now let's see how we can solve this how we can code this can solve this how we can code this problem okay so the first thing that we problem okay so the first thing that we need is my left need is my left is equal to zero is equal to zero my right equal to 0 and my max length my right equal to 0 and my max length which is also initialized to zero which is also initialized to zero now we want to go from left to right so now we want to go from left to right so for every X in s I am going to check if for every X in s I am going to check if my X my X is is an opening packet an opening packet if it's an opening bracket I would do if it's an opening bracket I would do left is equal to plus equal to 1. else left is equal to plus equal to 1. else it's a closing bracket so it's a closing bracket so oh typo oh typo so I would do write plus equal to 1. so I would do write plus equal to 1. when I increment my left hand right what when I increment my left hand right what do I check I check if my left is equal do I check I check if my left is equal to right so if my left is equal to my to right so if my left is equal to my right right if that's the case then I calculate if that's the case then I calculate maximum length maximum length so my max length so my max length would be Max of would be Max of max length or my left plus right else else if uh my right is greater than left that's when I will reset my left and right to zero so my left and right will be initialized back to zero this is the first Loop when you go from left to right before starting the second Loop we have to make sure that our left and right are initialized to zero so that's why I'm doing this now I go for for every X in my string and I'm going to reverse it right here so colon colon minus one makes It reversed uh so I'm reversing my string I am checking if my X is a opening bracket if it's the opening bracket then the same thing left today plus equal to 1 and my right would be plus equal to 1. here I check if my left is equal to my right if it's true then I am going to update my max length so my max length would be Max of max length max length and or my left plus right my left is greater than right if my left my left is greater than right if my left is greater than right that means I have is greater than right that means I have more opening brackets than my closing more opening brackets than my closing brackets that's the time when you reset brackets that's the time when you reset it it so let's first write equal to zero in so let's first write equal to zero in the end when everything is done when you the end when everything is done when you have Travis it from both sides you have Travis it from both sides you return max length return max length let's try and see if we can run this let's try and see if we can run this code code yeah it's it's uh it's running so let me yeah it's it's uh it's running so let me submit it submit it okay so it's submitted uh let's talk okay so it's submitted uh let's talk about the space and time complexity of about the space and time complexity of this problem so uh this problem so uh if you look at this you are traversing if you look at this you are traversing through the entire string just once through the entire string just once so that makes and so here it's one time so that makes and so here it's one time and then the other time is here so it's and then the other time is here so it's basically you know n plus n which is 2N basically you know n plus n which is 2N and we actually discard constant uh when and we actually discard constant uh when we took time complexity so the time we took time complexity so the time complexity of this uh problem would be o complexity of this uh problem would be o of n when you talk about the space of n when you talk about the space complexity space complexity is going to complexity space complexity is going to be constant because we are using just be constant because we are using just right left and max max length which is right left and max max length which is let me just storing a single integer at let me just storing a single integer at a time it's not scaling so that makes my a time it's not scaling so that makes my space complexity as o of 1. space complexity as o of 1. so I hope this uh explanation was so I hope this uh explanation was helpful and if you like my videos give helpful and if you like my videos give it a thumbs up or comment below uh it it a thumbs up or comment below uh it really helps my channel and if you like really helps my channel and if you like to see more videos like this please to see more videos like this please subscribe to my channel uh there's a subscribe to my channel uh there's a similar uh there's the same explanation similar uh there's the same explanation in Hindi coming up later this week so in Hindi coming up later this week so stay tuned for it as well thank you bye
2024-03-20 08:40:50
32
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode 32. Longest Valid Parentheses (Python)
P1Ag3ItFyUs
Today's problem is to multiply the nested list. In this problem, you have been given a nested list. In this problem, you have been given a nested list. Every element of this list Every element of this list is a sequence or is another list in itself. is a sequence or is another list in itself. You have to multiply this nested list You have to multiply this nested list and after that you have to implement some API. and after that you have to implement some API. and after that you have to implement some API. first API is your naked outer, in this you will be passed the naked list, whatever is your naked list, you can store it or you can perform whatever operation you want on it, after that you will get two APIs. Next and HasNext will be given. First of all, HasNext API call will be made. In this it will be asked whether there is any element left in this list. If there is any element left, then return True. Otherwise, False is returned. If Next is returned as True. So the next API call will be and what you have to return in the next API is whatever will be your next integer in the next list, let us see it with the help of an example, we have a list here, in our list we have tooth element and our first There is a list in itself. There is a list in itself. There is a list in itself. What is the second element? What is your index? The third What is the second element? What is your index? The third element is in itself a list. So element is in itself a list. So when you flip this list, when you flip this list, what will happen to you? You will start traversing from this. Whoever what will happen to you? You will start traversing from this. Whoever comes first is your one. comes first is your one. comes first is your one. comes after this, has not come, then again, then, then, you will get a complete list of fingers like this, then suppose you call on this next, return me next, then in the beginning, you have to return this After that, the next call is made, because now these four elements are left in your list, you have consumed this element, even after that you have four elements left, so what do you have to return? Then if the next call is made, then which is our first This is it, you have to return this, This is it, you have to return this, This is it, you have to return this, then next time it happens, then this has to be then next time it happens, then this has to be returned, next tomorrow this will happen, this will happen returned, next tomorrow this will happen, this will happen next, after returning this, now we have next, after returning this, now we have consumed all the elements, so if consumed all the elements, so if now what will our birth be equal to, then we will now what will our birth be equal to, then we will have have have return false here and here our program will be terminated. If you answer all the API results correctly then your program will pass. If even one API result is called wrong then It will fail like if this one It will fail like if this one It will fail like if this one call 146 what will become of our flat n list call 146 what will become of our flat n list 146 this will become in this if we 146 this will become in this if we call next then our one will come then if we call next then our one will come then if we call next again then four should be returned then if we return next again then six should be called after this six should be called after this six should be called after this array is finished so here if we call has next then we have to return false. Before this if we call anywhere here then anywhere else then we have to return false. Now along with this we have We have to We have to We have to find out whether this current find out whether this current element of the list is an integer or is it element of the list is an integer or is it a list in itself, like here this is our a list in itself, like here this is our list and what is this integer, list and what is this integer, then if we want to find out whether the list is then if we want to find out whether the list is then if we want to find out whether the list is this element is an integer or is it a list in itself, then for that we are given two APIs. We can call this API and from this we Is Is Is it an integer array or a list? it an integer array or a list? If it is an integer array, it will return true. If it is an integer array, it will return true. If it is a list, it will return false. If it is a list, it will return false. Now we know that in that position, Now we know that in that position, suppose there is an integer array, then how can we get that integer array. What is the virtual value on that integer, which integer is it? What is the virtual value on that integer, which integer is it? We have been given API for that. We have been given API for that. If we call get integer, we will get the actual integer. Apart from this, we will get a get list. get the actual integer. Apart from this, we will get a get list. This API is also given, if we This API is also given, if we have a list on our current index, then that have a list on our current index, then that list will be returned to us, like first of all, list will be returned to us, like first of all, what we will check is whether the integer what we will check is whether the integer is there or not, if it is true, our integer is then is there or not, if it is true, our integer is then we get the integer. we get the integer. we get the integer. can gate that entry with the help of key and if its result is false i.e. there was a lit there then we can gate that list with the help of get list, so basically we have to implement this iterator in which we are Integer Get Integer Get List will use these APIs and we will have given three APIs. First of all what will be the API of Inila Ization then second next then has next we have to return the result of these three APIs. If If If we want, we we want, we can store it here or we can fold it and can store it here or we can fold it and store it as a flat list. Here store it as a flat list. Here we can do some operations with this list, we can do some operations with this list, after that our two API calls Next after that our two API calls Next and HasNext are these two API calls. and HasNext are these two API calls. and HasNext are these two API calls. next API call, what we have to do is where our index will be now, we have to return whatever integer is there and what to do in judge next, if we have not set all the elements then Now, Now, Now, how do we implement this? how do we implement this? If we pass the list here, If we pass the list here, multiply it and store it in an array multiply it and store it in an array or a vector, after that or a vector, after that what will be left in Next and A Next? what will be left in Next and A Next? Simple. Simple. Simple. that we can track the current index. Suppose I have taken the current variable which is initially set to zero, then whenever my next one comes, what I can do is simple, return the current of that array, this one Make the current plus plus. I have to Make the current plus plus. I have to Make the current plus plus. I have to return the current of the array as this element return the current of the array as this element and then make the current plus plus. So and then make the current plus plus. So how can I do this? Make the current of the array plus plus how can I do this? Make the current of the array plus plus on y. Either use post comment operator on y on y. Either use post comment operator on y or simple. or simple. or simple. equal to two arrays of current current plus plus and return the drop, basically what I have to do is return the element of whatever my current is doing Let me Let me Let me increment this variable current, take it one step increment this variable current, take it one step forward and what do I have to do in the next, forward and what do I have to do in the next, wherever my index is, all I have to do is wherever my index is, all I have to do is see that it see that it is in my valid range, when will it be in the valid range, when is in my valid range, when will it be in the valid range, when my index is whatever. my index is whatever. my index is whatever. vector will be less than that, if it is equal or more then it means that we have exhausted all the elements and we will return the force, then simply what we will do is we will compare this current with our size, If it is smaller than the size, If it is smaller than the size, If it is smaller than the size, then we will return t, otherwise we will then we will return t, otherwise we will return the result, so if we can return the result, so if we can store this list in an array or vector by store this list in an array or vector by flattening it, then simply we can call Next and flattening it, then simply we can call Next and Judge Next in this API. Judge Next in this API. Judge Next in this API. do this, our code will be very simple. Now how to store this next list? To store it, suppose I take a vector, I will store it in a vector, what type should my inger be of If I want to If I want to If I want to do this, what will all the elements be of inj do this, what will all the elements be of inj type, I will take a vector, type, I will take a vector, now I need to get the next list, this list, now I need to get the next list, this list, what is in this list, here is my list, so what is in this list, here is my list, so first of all, what will I put, I will first of all, what will I put, I will put a loop on it, then my denominator. put a loop on it, then my denominator. put a loop on it, then my denominator. whatever is my nested list, scan each element of it. First of all, I will pass this element. What is this element, is it a list, but I will not know directly, how will I know, I am the From the help you will know that From the help you will know that From the help you will know that I have given some interface whether it I have given some interface whether it is an integer or not, then I will check whether is an integer or not, then I will check whether x is my integer or not, I will x is my integer or not, I will call that API on this x and find out call that API on this x and find out whether it is an integer or not. whether it is an integer or not. whether it is an integer or not. integer, suppose its result is true. If it is an integer, then simply what do I have to do, store it in the vector, what will I do, push it back in the vector, store it in the last part of the vector and If it is an integer, then from If it is an integer, then from If it is an integer, then from where was I getting it? Get integer and get integer, where was I getting it? Get integer and get integer, I will call this API and store it in it. I will call this API and store it in it. If I get the result false or If I get the result false or it is not an integer, then what does it mean it is not an integer, then what does it mean that it is a list and I will get the list. that it is a list and I will get the list. that it is a list and I will get the list. get list, I will get it from this, I will call this API and now I have got this list, if I want to calculate it too, then I will call this function recursively. Whatever we will write this function of ratio, I will I will give you basically I will give you basically I will give you basically how we will flatten this list, we will how we will flatten this list, we will flatten it using ration, we will first flatten it using ration, we will first look at the current element, if it look at the current element, if it is our integer then we will store it in a direct vector, is our integer then we will store it in a direct vector, if it is not our integer if it is not our integer then what can we do? then what can we do? then what can we do? first flatten this list recursively, store it and then proceed further. Once we see its overall code, you will understand better from it. We had to implement three APIs of this nest class I Traitor. Next Hydrator is our basically constructor Next API Our Edge Next API Our Edge Next API Our Edge Next API Next API In our constructor, we have a list In our constructor, we have a list and we are saying that we will and we are saying that we will flatten this list and store it, how flatten this list and store it, how will we store it, which type will we store it, which type of vector in one of our vectors, store it in a vector of type Inger. of vector in one of our vectors, store it in a vector of type Inger. of vector in one of our vectors, store it in a vector of type Inger. we have written this function for that, what will we do in this function, we will recursively flatten our nested list, let us is our list, then we will is our list, then we will loop over this list. loop over this list. How many elements are there in our list? How many elements are there in our list? How many elements are there in our list? first of all we will pass this. This will come in our IT. The complete list will come. Now how will we know whether there is an integer or a list here? For that, we were If this If this If this element is inger or is your list element is inger or is your list then we will call this ae inger. If then we will call this ae inger. If its result is true i.e. there is inger on What will we give inger er and it will return whatever is What will we give inger er and it will return whatever is inger if its result is false, inger if its result is false, what does it mean, there is our what does it mean, there is our list and we have to flatten it, then we will call this function again recursively id getlist. will call this function again recursively id getlist. What will we get from this? Here we will get our list What will we get from this? Here we will get our list and we will send it to Phaltan to and we will send it to Phaltan to flatten this list and flatten this list and then when it returns here, then when it returns here, we will come back in the loop and pass the next element we will come back in the loop and pass the next element to our two. to our two. to our two. flow will run like this, first of all we will come to this loop, when we will pass inside it, then this element of ours will come in the starting, from here we will check whether it is integer or not, if not then we will We will go to it and getlist, basically We will go to it and getlist, basically We will go to it and getlist, basically what will we get from this, we will get this, we will what will we get from this, we will get this, we will pass it to our receive function, pass it to our receive function, then in our receive function, we will then in our receive function, we will have a loop on this, what does it mean to have a loop on this, have a loop on this, what does it mean to have a loop on this, one element is this one element one element is this one element is this i.e. is this i.e. is this i.e. then what will happen, we will check whether it is an integer, yes, this is a single element, so here it is an integer, so we will store it in our answer, so what has come in our vector Then we will Then we will Then we will move ahead, come to its second element, move ahead, come to its second element, check it, if it is also an integer, then check it, if it is also an integer, then we will store it too. Now this loop of ours will end, we will store it too. Now this loop of ours will end, then we will come to its end and will go then we will come to its end and will go back here from where our recurse call was made. back here from where our recurse call was made. What was there in that? Now What was there in that? Now this element of ours has passed, so now the next this element of ours has passed, so now the next element will go to this. Green foreloop was going element will go to this. Green foreloop was going on. Will go to this and will check this. What is this, on. Will go to this and will check this. What is this, this is our index, so we will store it directly. this is our index, so we will store it directly. We will store it on this. We will store it on this. We will come back to this loop, now We will come back to this loop, now our element will come, now our element will come, now what is this, this is a list, so we will come to Y, we will what is this, this is a list, so we will come to Y, we will recursively pass this list to our function recursively pass this list to our function and then we will loop over it again. and then we will loop over it again. What will happen to us while taking it? What will happen to us while taking it? What will happen to us while taking it? come to this, this is an integer, we will store it, then the next will come to this, this is also an integer, we will store this and then our loop will end, then we will come back here from recurse and go to the next. If there is no element left then that If there is no element left then that If there is no element left then that means our original relation will also be means our original relation will also be terminated and terminated and what list will we have stored? 1 1 2 3 3 The list what list will we have stored? 1 1 2 3 3 The list of our next list has been stored in flat N form. of our next list has been stored in flat N form. Now what do we have to do after that? Now what do we have to do after that? We will have next and has these two We will have next and has these two equals. To track where equals. To track where our index is now, we have our index is now, we have taken the current variable which will track where our index taken the current variable which will track where our index is now. Starting, is now. Starting, our index will be on the row, so we have our index will be on the row, so we have stored the row in it. stored the row in it. stored the row in it. next what we will do is what is the size of our list 1 2 3 4 5 is five we will compare row with five is less that means we still have elements left in our list right now we have elements left in our flat n list so From here we will return two. If we From here we will return two. If we From here we will return two. If we return two then our next call will be return two then our next call will be that tell me then which is the element on this current index, that tell me then which is the element on this current index, then what will we do? Answer then what will we do? Answer of current, we will return whatever element is on this index of current, we will return whatever element is on this index and along with it our and along with it our Index current plus plus means now our Index current plus plus means now our index will come to this one. Our index index will come to this one. Our index was earlier at zero. Now what will happen to us? It will become was earlier at zero. Now what will happen to us? It will become one again. Next will come to us because of this one again. Next will come to us because of this we will return T. Why is lane F? we will return T. Why is lane F? We will return T. We will return T. We will return T. we will return no and now what will be our current? Next will we return lane is 5, then next will come we will return two and take our next one forward. Now Will come to three. If th is Will come to three. If th is Will come to three. If th is still smaller than f, then still smaller than f, then what is the output of the next? If it comes to true, what is the output of the next? If it comes to true, what will we do next? We will return three what will we do next? We will return three and take our current to four. If and take our current to four. If four is still smaller than five, then there is four is still smaller than five, then there is four is still smaller than five, then there is output of next will be true. We will return this three in the next API and will take it to our next current. Now what has happened to us is five. I will compare less than five. What happened if this condition fails then what will my next It will return false and as It will return false and as It will return false and as soon as it returns false, our next e- soon as it returns false, our next e- call will not happen, our program will be call will not happen, our program will be terminated, after that only what our terminated, after that only what our program will check is whether the program will check is whether the value given to us was correct or not. value given to us was correct or not. If it was correct then If it was correct then If it was correct then otherwise if our output is not correct, then your entire program will work in this way. What will we do in this? Initially, we will store our next list in this form, after that we will return the result of both Next and HasNext. What will our overall tongue collection take? If you look here, we were traversing the list, we were traversing each element once, like what was our list, vv 2 3 3, this was our list, We were doing this element, We were doing this element, We were doing this element, then we were doing each element inside it then we were doing each element inside it one by one and then we were moving ahead, then one by one and then we were moving ahead, then our total number of integers will be our total number of integers will be 1 1 2 3 3 five integers, that is the number of 1 1 2 3 3 five integers, that is the number of times our traversal will run recursively. times our traversal will run recursively. But each element is being But each element is being traversed only once, so what will be our tangent of this function? traversed only once, so what will be our tangent of this function? Whatever will be the Whatever will be the total elements in our next list, total elements in our next list, then comes our next A. This is then comes our next A. This is our off one and J is the next one. our off one and J is the next one. our off one and J is the next one. are of one, then both of them are the same. If our A calls are there, then the total time will be the same. This one is also of A. This one is also of ours. If our A calls are of ours, then both of them What is of A type, What is of A type, What is of A type, then overall, what will be our time then overall, what will be our time and what will be our space? We have and what will be our space? We have taken a vector to store this list. How many taken a vector to store this list. How many elements will be stored inside this vector, elements will be stored inside this vector, as many integers will be inside our original nested list. as many integers will be inside our original nested list. If we consider it as n, then If we consider it as n, then our total space will be of this size, our total space will be of this size, then what will be our time and space then what will be our time and space complexity? complexity? Thank you guys.
2024-03-24 10:57:29
341
https://i.ytimg.com/vi/P…axresdefault.jpg
Flatten Nested List Iterator | Leetcode 341 | Recursion | C++ | Daily Challenge
IKQSexsR7eE
Hello Everyone I am Jaysh Today in today's video I will be sharing with you how I sharing with you how I studied Digit DP. How I asked myself this studied Digit DP. How I asked myself this question, what was my thought process and question, what was my thought process and while solving and practicing DP, while solving and practicing DP, what were the patterns which mostly helped me. what were the patterns which mostly helped me. what were the patterns which mostly helped me. important and on which a lot of questions have come, which is actually correct, I will be discussing in this video, I will also provide the pseudo code and the C plus plus code to the two one of the questions which I find It is basically easy for a It is basically easy for a It is basically easy for a beginner who is doing Digit DP question for the beginner who is doing Digit DP question for the first time or seeing this pattern for the first first time or seeing this pattern for the first time. Ok let me show you the question. time. Ok let me show you the question. Numbers with Repeated Digits is hard Numbers with Repeated Digits is hard as you can see it is a very basic as you can see it is a very basic question. question. question. if you know Digit DP then you can do it very easily. And this is not the most optimized code but as a beginner you will understand it very well. Okay, so let's start. Let's It is very important to understand the pattern It is very important to understand the pattern It is very important to understand the pattern because without understanding the pattern, you will face a lot of problems. The because without understanding the pattern, you will face a lot of problems. The first step is to assume that you have been given a number whose range is anything greater than zero. Do not assume the power of 10. Whatever is the range of two integers, it What to do? What to do? What to do? You will be asked in the question to tell the count You will be asked in the question to tell the count of the numbers which are following some pattern from one to of the numbers which are following some pattern from one to A. Do you understand? Like A. Do you understand? Like suppose one to A. Tell the count of those numbers suppose one to A. Tell the count of those numbers which have unique digits. If we take the example of this question then it is which have unique digits. If we take the example of this question then it is ok. ok. Have unique digits. Now the second pattern is Have unique digits. Now the second pattern is A and B. Two numbers have been given, you have to calculate from A to B A and B. Two numbers have been given, you have to calculate from A to B basically and this will be the range from basically and this will be the range from zero to 10, it is okay to zero to 10, it is okay to calculate the same count separately but this pattern is calculate the same count separately but this pattern is not covered in this video. not covered in this video. not covered in this video. tell me in the comments, if you want this also, it is quite simple, if you know this, then it means you will do it yourself, you will not even need me, but still if you feel like it then In In In this video this video ok moving on now ok moving on now watch if I tell you one to a I suppose a watch if I tell you one to a I suppose a is 10 is 10 tooth 4 5 6 7 8 na 10 let's take this a little bigger let's tooth 4 5 6 7 8 na 10 let's take this a little bigger let's take this 1 let's take take this 1 let's take 12 1 ok 12 1 ok tell me the count of those numbers tell me the count of those numbers tell me the count of those numbers unique digits, that means you cannot count, neither has it come twice, nor has it been done twice, there is nothing, so it is clearly visible in this, apart from all of them, they will be counted, but Understand, if I Understand, if I Understand, if I take it to this range, then how will you take it to this range, then how will you do it? Any brute force or any L will do it? Any brute force or any L will work. This question will be asked from DP only. What is the right thing to work. This question will be asked from DP only. What is the right thing to do? Basically, what needs to be done in this question is do? Basically, what needs to be done in this question is that n is your number and you have to that n is your number and you have to convert it into a string. convert it into a string. convert it into a string. after converting it into a string, it is a string of only nine lengths. Now you are feeling that it is a string of only nine lengths, which means that we do very basic basic. When we come to questions with such small constraints, then it is okay. What is the suggested number? T is a string of length 4 5 Now what Now what can happen is that every position is can happen is that every position is filled, I can put any of these numbers, filled, I can put any of these numbers, plus the number will sit at the last and it will plus the number will sit at the last and it will be smaller than this number. be smaller than this number. be smaller than this number. mind, so how do we do it? Basically, we propose a memorization function like this. Basically, an e is equal to the index. If you don't know, let me tell you. Basically, You You You take a vector, it is divided, okay, take 10 digits, take a vector, it is divided, okay, take 10 digits, divide it with zero, divide it with zero, so now what are you storing in it, suppose so now what are you storing in it, suppose you took a number, in the first position, you took a number, in the first position, what did you do, you divided it with zero, what did you do, you divided it with zero, everything else is zero. everything else is zero. everything else is zero. not been used till now, the number which remained or is not yet mine, understand that basically it means not yet mine, understand that basically it means storing which numbers have been used, it is not connected with Kanan, storing which numbers have been used, it is not connected with Kanan, we have to create a number of one digit, okay, we have to create a number of one digit, okay, so this mask is basically so this mask is basically so this mask is basically can only go up to nine digits, then what can Apna do? Because there are only two digits from zero to no, then what can Apna do? Instead of taking this vector Apna, we can give one integer to the In which we will In which we will In which we will check from the bit representation that the number is present at check from the bit representation that the number is present at one zero position, if the th bit is present then it means zero one zero position, if the th bit is present then it means zero number has come in the number and if zero has number has come in the number and if zero has not come in the same position, if it is one then not come in the same position, if it is one then n is in the second position in the number. n is in the second position in the number. n is in the second position in the number. the Mask G et Okay, so you understood, basically this function is something like this: basically this function is something like this: Index, Index, equal, mask, base, there are three things, three things will be useful for equal, mask, base, there are three things, three things will be useful for you, you, now see, let's assume, now see, let's assume, I told you what is equal, otherwise I told you. I told you what is equal, otherwise I told you. I told you what is equal, otherwise I told you. that we will go to the same length as the string and I have also seen that we have to connect through the mask, one number will come only once, but as I told you, What should I keep in my DP, where should I keep it, What should I keep in my DP, where should I keep it, What should I keep in my DP, where should I keep it, my month will not be my month will not be crossed, my code will not be crossed, crossed, my code will not be crossed, both are correct but this number is both are correct but this number is obviously bigger than this, so it obviously bigger than this, so it should not be counted, neither do we use it for that. should not be counted, neither do we use it for that. Basically now what does equals Basically now what does equals do? Like suppose initially do? Like suppose initially its value is one when its value is one when something comes equal to zero. Basically when you are starting the something comes equal to zero. Basically when you are starting the dimension question then you check whether dimension question then you check whether whatever number you are entering in this position is whatever number you are entering in this position is whatever number you are entering in this position is it equal to this or is it greater than this? Basically if it is smaller than this means I propose here one for instance two, it will be easier to explain. Okay 3 56 Suppose this If I If I If I keep it, it won't make any difference, if it gets smaller from here, it will keep it, it won't make any difference, if it gets smaller from here, it will be smaller in the future, but if I be smaller in the future, but if I keep this th then I will have to keep this th then I will have to check for the next index also, so the work of this one check for the next index also, so the work of this one is that as long as it is equal to one here, I is that as long as it is equal to one here, I is that as long as it is equal to one here, I my number only till the number of that digit, that is, if I is equal to one and I am in this position, then I can place 3 then F, some of it can be placed in this position, 6 to 8, yes, I cannot place all of it, Yes but if it is zero then I Yes but if it is zero then I Yes but if it is zero then I can put anything from zero to zero. This can put anything from zero to zero. This happens. Okay, so you happens. Okay, so you understand the significance of 'e equal'. I have written it 'i' understand the significance of 'e equal'. I have written it 'i' because it is short for 'e equal' so because it is short for 'e equal' so when I used to code, when I used to code, when I used to code, so that when you are doing the work, if there is any mistake in the code in the last section then it is easy. If you keep good names then it is ok. Now let's see the basic pseudo code. Let's see in this particular question what is it. It says that given It says that given It says that given number of positive digits you have to make count number of positive digits you have to make count in range and to have at least one repeated in range and to have at least one repeated digit so that at least one digit must digit so that at least one digit must be repeated, the question is the same, there is just a little be repeated, the question is the same, there is just a little twist. Now let's go back twist. Now let's go back Now understand whether the 13 that was your example from your father is this one Now understand whether the 13 that was your example from your father is this one Now understand whether the 13 that was your example from your father is this one or now or now he is saying give me that number in which the he is saying give me that number in which the atlist is one repeat, so now we have only atlist is one repeat, so now we have only 11 from here in which the atlist is 11 from here in which the atlist is one repeat and the rest is one repeat and the rest is one repeat and the rest is your first answer was everything except 11. Now the answer is only 11, so basically from the exclusion-inclusion principle you can say that n pw minus whatever is your answer, do not count how many variations there will be, this is your final We will We will We will extract this from our DP, then it is extract this from our DP, then it is simple maths, so this was the foundation of this problem, it is simple maths, so this was the foundation of this problem, it is completely fine, let's come to the pseudo code, completely fine, let's come to the pseudo code, how this happened, basically, the pseudo code how this happened, basically, the pseudo code closed. closed. closed. told you that whatever is the max, if it is equal, then you should choose the number only till this digit, not smaller than that, not bigger than that, but the max remains which I am saying if it is If If If not, then we will convert it to max, whatever that not, then we will convert it to max, whatever that string is, its integer value, otherwise we will put our nan or whatever we get. Now we will go from zero to max in the for loop and place each number in the right position and see but it is Also look at yourself, we will check with the mask Also look at yourself, we will check with the mask Also look at yourself, we will check with the mask that if that that if that person is already there in the mask, basically yes, consider it as digit D. person is already there in the mask, basically yes, consider it as digit D. IG, if it is already there, then you IG, if it is already there, then you continue, continue, if not, then consider it as digit Y at this place. if not, then consider it as digit Y at this place. Now you update the mass Now you update the mass and pass it equal to one, and pass it equal to one, if your digit is equal to max, if the if your digit is equal to max, if the digit is equal to max then don't send it, send zero, simple and no updated mask in mask. By doing this, all the possibilities will be accessed. Do you need a count of answers? Make one answer, make it zero, do whatever you want with the function, return it in the end, and this way your count will come. Okay, understood. Let's This is the code of PS, This is the code of PS, see the same thing, if it is DP, first I have calculated the max function here, if it is there, then the over number is equal to it, then no no, the answer is zero here, this for loop is from zero to This max and one day This max and one day This max and one day shift, if means it is within the same month, shift, if means it is within the same month, I am checking through binary I am checking through binary if it is there, then it is not a content, no, by doing this, right if it is there, then it is not a content, no, by doing this, right here, as you can see, I have made a FDI D, it has here, as you can see, I have made a FDI D, it has come from the fourth factor. come from the fourth factor. sending some forest in the beginning, is this a small sending some forest in the beginning, is this a small catch, if you have got it, then catch, if you have got it, then pause the video and write in the comment. If you haven't got it, then pause the video and write in the comment. If you haven't got it, then let's let's explain explain then then see what is suggested. see what is suggested. Why will this code fail? Think, now this code Why will this code fail? Think, now this code will fail because you have will fail because you have not seen this case. You are saying that not seen this case. You are saying that put any number from zero to max, any one is fine, 00 0 and none are the same, all three are fine but if 00 0 and none are the same, all three are fine but if 00 0 and none are the same, all three are fine but if put zero here, then in your code, are you setting it in your mask that now zero has been used, it is written, so now you should not put it back, then if it You You You can always propose that if can always propose that if you are number you are number two then you will never be able to make it like this. You have kept it zero for the first time. two then you will never be able to make it like this. You have kept it zero for the first time. Now you cannot keep zero on this. You will have to keep Now you cannot keep zero on this. You will have to keep something, then you will become number one, otherwise you will something, then you will become number one, otherwise you will not be able to reach number one, otherwise you will have to handle that case. not be able to reach number one, otherwise you will have to handle that case. A is kept that as long as there are A is kept that as long as there are only zeros behind it, you keep keeping zeros, but only zeros behind it, you keep keeping zeros, but as soon as another number comes, then I update the A as soon as another number comes, then I update the A root root basically that now I basically that now I will not use my zero basically because the will not use my zero basically because the zeros before it are just zeros before it are just Yes, it may be no, but no, these two Yes, it may be no, but no, these two zeros have no meaning. Actually, it is only 10. zeros have no meaning. Actually, it is only 10. These two zeros are their own because they These two zeros are their own because they are working in their own string, that is why we have to are working in their own string, that is why we have to see this case. see this case. see this case. Okay, submit all three test cases and Okay, submit all three test cases and see, it shows 'Accepted'.
2024-03-25 14:46:00
1,012
https://i.ytimg.com/vi_w…xresdefault.webp
Digit Dp | 1012. Numbers With Repeated Digits | Patterns | C++ Code | Dynamic Programming
pLzb27cOpuM
so today we're gonna discuss this question from bi-weekly contest 18 question from bi-weekly contest 18 problem number one three to eight break problem number one three to eight break a palindrome so in this you are given a a palindrome so in this you are given a parent drumming string as an input and parent drumming string as an input and you have to replace exactly one you have to replace exactly one character by an lower degree settle a character by an lower degree settle a little bit so that the string which is little bit so that the string which is sawn should be less so graphically small sawn should be less so graphically small is possible and that shouldn't be a is possible and that shouldn't be a palindrome itself as you can see from palindrome itself as you can see from this example this is a and we can put if this example this is a and we can put if I convert this B to a then this is the I convert this B to a then this is the least like so graphically possible least like so graphically possible string and did not also a palindrome and string and did not also a palindrome and if it is not possible to convert then we if it is not possible to convert then we have to turn an empty string as you can have to turn an empty string as you can see in this because it'll be converted see in this because it'll be converted in any other like if we have to at least in any other like if we have to at least and put exactly converts one character and put exactly converts one character this is one that if I can apply to any this is one that if I can apply to any other you like BC it also again remains other you like BC it also again remains a Pinto and it doesn't satisfy this a Pinto and it doesn't satisfy this condition so we have to return an empty condition so we have to return an empty string so what we can do is as you can string so what we can do is as you can see in any palindrome which is of even see in any palindrome which is of even size if we change any tag term it will size if we change any tag term it will become non palindromic as you know become non palindromic as you know because it is a mirror image of itself because it is a mirror image of itself and in odd number of the linndrum and in odd number of the linndrum odd number window if we have to change odd number window if we have to change if we can't change an alphabet before if we can't change an alphabet before the index of its middle then it also the index of its middle then it also will not become a below after the things will not become a below after the things let me tell you in this example so as let me tell you in this example so as you can see this is a palindrome if I you can see this is a palindrome if I change a to be so it will not be a Pinto change a to be so it will not be a Pinto but it will not be the least like so but it will not be the least like so graphically smallest alright so what we graphically smallest alright so what we do is to be least extra graphically do is to be least extra graphically smallest less example just seems like we smallest less example just seems like we have to be we have we have we should have to be we have we have we should have is max - max possible from here have is max - max possible from here from the starting because as you can from the starting because as you can imagine it the numbers take example with imagine it the numbers take example with numbers numbers if you have one four five and if you if you have one four five and if you make if one cannot go beyond because it make if one cannot go beyond because it will become zero but if you want to make will become zero but if you want to make it a three-digit number it a three-digit number but smallest what we can do it we make but smallest what we can do it we make we should make it one also well and if we should make it one also well and if zero is not allowed in this case so we zero is not allowed in this case so we should also make it one so what we do is should also make it one so what we do is we Traverse from left to right and if we we Traverse from left to right and if we see any of the element which is greater see any of the element which is greater than P we should convert it back to it than P we should convert it back to it so it is very much so if you can write so it is very much so if you can write back to it it will will not be a back to it it will will not be a palindrome anymore and it will be like palindrome anymore and it will be like so graphically smallest so in this case so graphically smallest so in this case we just converted back to it and it will we just converted back to it and it will it will be the case for this case if the it will be the case for this case if the string length is less than 2 then it is string length is less than 2 then it is not possible at all in this case because not possible at all in this case because this is this this is this if we move it this is this this is this if we move it here from here to here then as we can here from here to here then as we can see we draw a middle line so we check see we draw a middle line so we check with this and this it is a Potomac with this and this it is a Potomac string but we cannot change both of this string but we cannot change both of this as of it to anything most for the small as of it to anything most for the small so in this case what we'll do is we'll so in this case what we'll do is we'll move from now from back from right to move from now from back from right to left and if any alpha between counter is left and if any alpha between counter is smaller than Z will make it Z so take smaller than Z will make it Z so take this example only if we have this number so if you cannot change this then we have to change this now at the last number so we can change this to 1 but if we change it it will also become palindromic so we can change it to anything like 9 we just put it 9 because it will be a simple logical so let's get it moved here with the code if the size is like less than or equal to 1 then x will be a null string empty string sorry then we first move from 0 to 2 less than n by 2 and if we encountered anything greater than a then we make that position of s equal to a and then return the string if anything is not satisfied in this loop then we move from back to the front and anything we encounter like smaller than said we increment it increment that number because that will be the lexicographically nesting legs smallest one so then we turn that and after that we just return the empty string if none of these conditions are so I hope you understand the logic thank so I hope you understand the logic thank you for watching and I'll see you next you for watching and I'll see you next week
2024-03-20 12:10:50
1,328
https://i.ytimg.com/vi/p…axresdefault.jpg
1328. Break a Palindrome || biweekly-contest-18 || leetcode || medium question|| c++
wdcyuxmYAWI
hello everyone welcome to the channel today we are going to solve lead code today we are going to solve lead code 412 fbus so we'll be given an integer 412 fbus so we'll be given an integer array n as an input we need to return a array n as an input we need to return a string array of size n so they have string array of size n so they have given as a condition four conditions so given as a condition four conditions so for each element that we are going to for each element that we are going to visit in the range n if the visited visit in the range n if the visited number is divisible by both three and number is divisible by both three and five we need to open fist bus to the five we need to open fist bus to the result if it's just divisible by only result if it's just divisible by only three we just need to open F if it's three we just need to open F if it's divisible by only five we need to open divisible by only five we need to open bus if none of the cases match what we bus if none of the cases match what we are going to do is we just need to open are going to do is we just need to open the number to the result but in a string the number to the result but in a string format let's go to an example so given format let's go to an example so given an input number three so we will be an input number three so we will be visiting three elements here which is 1 visiting three elements here which is 1 2 2 3 so for each number one 3 so for each number one we are going to check all these three we are going to check all these three conditions if one is divisible by three conditions if one is divisible by three and five no it's not divisible by three and five no it's not divisible by three and five so the next condition is if one and five so the next condition is if one is divisible by three no that's not and is divisible by three no that's not and the third condition is if one is the third condition is if one is divisible by five no so what we're going divisible by five no so what we're going to do is we need to upend one to the to do is we need to upend one to the result but in a string result but in a string format and then we going to go to the format and then we going to go to the next element likewise two two is also next element likewise two two is also not divisible by three and five so we not divisible by three and five so we just need to open two as a just need to open two as a string and the last element is three we string and the last element is three we know three is divisible by three so what know three is divisible by three so what we need to do is we just need to open F we need to do is we just need to open F here and this is our result so likewise we have two more examples here so this is the let's let's approach instantiate resultant two store result second step is we need to iterate through all the numbers in the range n trate through trate through each each number from one to y number from one to y while we are iterating we need to check while we are iterating we need to check if if the number is divisible by three open Fus to the if that's not the case and if the if that's not the case and if the number number is divisible by just is divisible by just three then we need to append if the number is divisible by append append thiss to the thiss to the result if not of the case result if not of the case match just up string number to the result after this we need to do return result so yeah this is the approach now let's look into the code go so we have in initialized the array and now we have to iterate from 1 array and now we have to iterate from 1 to n so we have we have setting I equal to n so we have we have setting I equal to 1 here and so I will iate from 1 to n to 1 here and so I will iate from 1 to n and if you look at the end the I will be and if you look at the end the I will be incremented by one at each run so first incremented by one at each run so first run it will be one and the next run it run it will be one and the next run it will be two and so on and so for until will be two and so on and so for until it reaches it reaches n so the first condition we are checking n so the first condition we are checking is if I is divisible by 3 and 5 if is if I is divisible by 3 and 5 if that's the case then we are opening F that's the case then we are opening F bus if that's not the case then we are bus if that's not the case then we are going to if condition so in a if we are going to if condition so in a if we are just checking if I is divisible by three just checking if I is divisible by three if that's the case we'll be appending if that's the case we'll be appending this if uh I is just divisible I we'll this if uh I is just divisible I we'll be appending just bu if none of the CES be appending just bu if none of the CES case match es we'll be just opening case match es we'll be just opening string of integer to the result and at string of integer to the result and at the end of Y Loop we'll be just the end of Y Loop we'll be just returning the returning the result so yeah that's it thank you
2024-03-22 10:48:53
412
https://i.ytimg.com/vi_w….webp?v=65505ae3
Fizz Buzz | Leetcode 412 Solution
NbsMEJNPG7I
welcome back daily lead coders daily leak code lead code daily Elite code day leak code lead code daily Elite code day 52 we're back once again 52 we're back once again uh yeah we're back once again we just uh yeah we're back once again we just got off uh we just finished talks with got off uh we just finished talks with uh uh uh Elon and Joe Byron we're making sure uh Elon and Joe Byron we're making sure that we're allocating uh I think the that we're allocating uh I think the about 33 percent of the US's available about 33 percent of the US's available networking resources and we're networking resources and we're rediverting it to the HCC which is the rediverting it to the HCC which is the hyperbolic coding chamber so we found a hyperbolic coding chamber so we found a way to get about 100 million more spots way to get about 100 million more spots so so feel free to join it's very important feel free to join it's very important also I missed a comment in the last also I missed a comment in the last video by the legendary Thomas Wong it's video by the legendary Thomas Wong it's part of the game Brother Gotta a see part of the game Brother Gotta a see those mediums like slicing Butters those mediums like slicing Butters actually facts brother and so he actually facts brother and so he mentioned 1763 longest nice substring mentioned 1763 longest nice substring don't cheat with Brute Force so I think don't cheat with Brute Force so I think I think we could try this problem but I think we could try this problem but I'm pretty sure we're gonna get cooked I'm pretty sure we're gonna get cooked we're gonna get baked give me one second we're gonna get baked give me one second so I just pulled it up oh okay it's an so I just pulled it up oh okay it's an easy okay so I thought it might be easy okay so I thought it might be something crazy I thought it might be something crazy I thought it might be like a medium but honestly sometimes the like a medium but honestly sometimes the easiest are harder than the hards so we easiest are harder than the hards so we might get baked by this might get baked by this [Music] [Music] might be okay it's one of those problems might be okay it's one of those problems those easies where those easies where the start right it's easy to get a the start right it's easy to get a simple solution rather than getting to simple solution rather than getting to linear times where the hard kicks in so I will try my best so I don't think we're going to do this so I don't think we're going to do this problem today actually yeah I don't problem today actually yeah I don't think we're gonna do this problem today think we're gonna do this problem today since we have to we're they're still o1 since we have to we're they're still o1 Matrix right actually my brain is kind Matrix right actually my brain is kind of fried I don't know if we're going to of fried I don't know if we're going to try a one Matrix again try a one Matrix again the optimal solution the optimal solution I think the optimal solution is dynamic I think the optimal solution is dynamic programming and if that's the case then programming and if that's the case then oof right definitely so maybe we'll just oof right definitely so maybe we'll just actually do longest nice substring today actually do longest nice substring today like Thomas mentions and then see how like Thomas mentions and then see how we're feeling but make sure to join the we're feeling but make sure to join the hyperbolic coating chamber this is a hyperbolic coating chamber this is a hyperbolic Time Chamber to hyperbolic Time Chamber to 10x 500x your current skill levels so 10x 500x your current skill levels so you're going to want to make sure you you're going to want to make sure you join if there are hundreds of hundreds join if there are hundreds of hundreds uh um hundreds thousands of people uh um hundreds thousands of people joining and since we just got about 33 joining and since we just got about 33 of the US is a networking resource of the US is a networking resource allocated for the HCC you know it's allocated for the HCC you know it's going to fill up pretty fast again so going to fill up pretty fast again so just make sure you join and yeah we're just make sure you join and yeah we're just going to jump in we're gonna do a just going to jump in we're gonna do a shorter session today since my brain is shorter session today since my brain is a little fried so you have a string s is nice if for every letter of the alphabet that s contains this thing is nice if for every letter of the alphabet that s contains it appears both in uppercase and lowercase for example a b capital A B B is nice because a and a appear B and B appear however a b a is not because B appear it's not because B appears but capital B does not appear so we have yazay and I think this should so we have yazay and I think this should be false right be false right wait oh wait no wait oh wait no for every letter of the outfit that s for every letter of the outfit that s contains it appears both in uppercase contains it appears both in uppercase and lowercase and lowercase given a string s return the longest sub given a string s return the longest sub ah interesting ah interesting the longest substring of s the longest substring of s that is nice if there are multiple that is nice if there are multiple returns returns ah the string Assumption of the earliest ah the string Assumption of the earliest occurrence if there are none return an occurrence if there are none return an empty string empty string interesting the longest interesting the longest occurrence or the substring occurrence or the substring for the longest substring of s that is for the longest substring of s that is nice you can return the longest nice you can return the longest substring of s that is nice if bb bb bb substring of s that is nice if bb bb bb is nice string becomes both B B and B is nice string becomes both B B and B appear appear right the longest substring we actually right the longest substring we actually have to return the actual string from have to return the actual string from the a lowercase large a lowercase a there are no nice substrings this is so I'm thinking there is no follow-up to so I'm thinking there is no follow-up to this our ABA is not because B appears the B is not so just to generate some solutions it seems like I think our best conceivable run time for this we know from Thomas's linear time so linear time is possible but finding the longest substring the longest substring the longest substring the wait is nice because a slash a is the wait is nice because a slash a is the only letter of the alphabet the only letter of the alphabet and S wait a and a appear and B and B and P B and B appear however a b a is not because B appears but B does not so I'm not actually understanding that is a slash a is the only letter of the alphabet in s well z and y are also in the alphabet and both a and they appear a a is the longest and substrate so I think maybe we could do a sliding sliding window pattern solution here imagine we have a window right we have y right we know that this is not a nice substring right and then we have a we know this is still a not a nice substring right maybe we have a map of our window right we'll know that it's not a nice string or add Z right but we still won't be a or add Z right but we still won't be a nice substring nice substring then we'll add a a into a hmm how is then we'll add a a into a hmm how is this an easy this an easy longest nice substring maybe I'm over longest nice substring maybe I'm over complicating it with my potential ideas complicating it with my potential ideas appears both an uppercase and lower appears both an uppercase and lower maybe I should have tried this with a maybe I should have tried this with a fresh brain fresh brain did like six hours did like six hours seven hours seven hours for example a b a BB is nice because a for example a b a BB is nice because a and a appear and B and B appear however and a appear and B and B appear however ABA is not because B appears ABA is not because B appears but B does not sliding window definitely doesn't make particularly because it's hard to know particularly because it's hard to know when our window should grow and should when our window should grow and should shrink maybe we could create the sliding shrink maybe we could create the sliding window anyway the time complexity would window anyway the time complexity would be pretty crazy be pretty crazy but even then if we have a window I think what we could do is we could I think what we could do is we could start right we'll start with a string start right we'll start with a string we'll say okay we have a nice such thing we'll say okay we have a nice such thing right and we have another string it's right and we have another string it's not a nice string anymore so then we'll not a nice string anymore so then we'll restart we'll have a we have a string we restart we'll have a we have a string we had another one it's not a nice string had another one it's not a nice string we only have Z you add Z we only have Z you add Z it's not it's it's not a nice string we it's not it's it's not a nice string we had a it's still not a nice string had a it's still not a nice string then we add a it's not a nice string at then we add a it's not a nice string at a it's a nice string you get another a a it's a nice string you get another a it's still a nice string it's still a nice string we have y it's not a nice string so we have y it's not a nice string so we'll restart hmm a is a nice string because a slice a is the only literally oh yeah my brain is absolutely fried I shouldn't have tried and BB is a nice string it's both B and and BB is a nice string it's both B and B appear the whole string is a substring well if we go with our original answer well if we go with our original answer of the next string having to make it a of the next string having to make it a nice string before we start nice string before we start that we miss versions or we could have a that we miss versions or we could have a lowercase a and then capital a or even the string s return the longest substring of s that is nice if there are multiple turn the substring of the since they say you want to return the since they say you want to return the subjecting of the earliest occurrence subjecting of the earliest occurrence and we're likely going to be moving and we're likely going to be moving sequentially through the array sequentially through the array that means we could do what we said that means we could do what we said earlier s that is nice there are multiple return s that is nice there are multiple return the suction of the earliest occurrence the suction of the earliest occurrence that yes that yes a a a a lowercase y however a lowercase B capital A is not however a lowercase B capital A is not because because B appears the capital B B appears the capital B does not I think there's probably also a divide um um if y a z a capital a lowercase a let's see if we can get a hint Brute Force well we could have done so maybe let's see if we maybe we'll so maybe let's see if we maybe we'll find some intuition by fluence in Brute find some intuition by fluence in Brute Force Brute Force right Force Brute Force right foreign double for Loop we'll have y and a so we start at y right we start at Y and then we'll pretty much iterate Until the End right and build a string we're going to see the longest substion that exists at this index and then we go to the next one and so I think what we could you could do that right in that sense we would be generating uh all nice strings set this equal to an array to start semicolon we have all nice strings we semicolon we have all nice strings we want to do a double for Loop right we'll want to do a double for Loop right we'll start at Y and then for y we'll see how start at Y and then for y we'll see how far we can go far we can go uh to see if a string is blue approach where we could act if we wanted approach where we could act if we wanted to return the longest possible to return the longest possible nice string longest possible nice string nice string longest possible nice string without actually returning the actual without actually returning the actual string I think we could do that but it would just be like subsequences so that wouldn't actually make sense The Brute Force approach we start at y a z and how does this generate I guess we could like they said check each because we basically have to have an is because we basically have to have an is nice function if you have a function that is is nice right we're going to do four lit I is equal to zero I is less than s dot length by plus plus and we're failing Thomas here because he wanted a non-linear solution but we'll get there uh I could change the J right J plus plus and then we'll create a string we'll say con string will be equal to uh an empty string to start and then we'll add a character now we'll check if it's nice first so now we'll check if it's nice first so say is nice say is nice string and if it is then we want to do string and if it is then we want to do all nice strings all nice strings dot push string right and then afterwards we'll do a string plus equal S Sub and then for is nice give them given a and then for is nice give them given a string or you want to be able to tell string or you want to be able to tell that it's nice and I think if we're that it's nice and I think if we're given a string like given a string like yeah yeah yeah yeah then for a particular a capital a lowercase you want to know if it's nice and we could load the yeah I think the good point to start yeah I think the good point to start with this problem is how do you tell if with this problem is how do you tell if the string is nice you know the string the string is nice you know the string is nice if for every letter of the is nice if for every letter of the alphabet as contained it appears both an alphabet as contained it appears both an uppercase uppercase and lowercase so I think we could do that in linear time with linear space with the set and so we'll return a Boolean value it'll be two linear iterations to the string one to set up the set will have a set of strings basically these are just going to be one character we could iterate through fur const car of s if there's a new set dot add car so now we'll have every character in s in a map right and then we know that for every layer of the alphabet the S contains it appears both in the uppercase and lowercase so to do that right we'll return false in the case we can't find this actually we'll return right and then we'll iterate through the right and then we'll iterate through the string once again and we'll say if set dot has car dot two lowercase or ifset foreign ER case or set car.2 upper car.2 upper case case right then we will return false so if right then we will return false so if the set doesn't have an uppercase right the set doesn't have an uppercase right or maybe it has lower case so it doesn't or maybe it has lower case so it doesn't have uppercase or it has up cases have have uppercase or it has up cases have lowercase you want to return false lowercase you want to return false otherwise we'll return true right then otherwise we'll return true right then afterwards we'll have a list of strings afterwards we'll have a list of strings which we'll want to sort right and we'll which we'll want to sort right and we'll say strings dot sort a comma B right a say strings dot sort a comma B right a DOT length which would be an array is DOT length which would be an array is less than b dot length less than b dot length then we could return all nice strings there's always at least one character in there's always at least one character in s right and if there's another thing we uh if uh if right we'll say all nice right we'll say all nice strings that length is not if it equals strings that length is not if it equals zero then we'll return zero then we'll return empty string otherwise we'll return the empty string otherwise we'll return the first element forgot to use the function forgot to use the function to lowercase let's have a power type to lowercase let's have a power type string topic does not exist on type string topic does not exist on type strings you mean strings you mean oh it's a yeah uppercase C and our string is a constant let's okay okay interesting so we're getting nothing so we have a string right called yes a right we start at index zero which is y and start at index J which is zero and then at y we'll say is this string nice right it's not right so we don't push it and then we'll add y to our string then we add a is it nice no then we add Z nice no then we add a nice but it should eventually have some but it should eventually have some output right when we get to output right when we get to this version right here I wonder is nice might not be returning the proper or we can also test right so just for or we can also test right so just for this case we'll test that the string AAA this case we'll test that the string AAA is nice and we'll print that to start is nice and we'll print that to start this is to make sure that is nice works foreign oh I see what's happening we're starting oh I see what's happening we're starting at right so we want to say J is equal to at right so we want to say J is equal to I I to start right so we should be getting some of that we're actually getting AAA as a value so we check if a is my string if value so we check if a is my string if it is we push it then we add a character it is we push it then we add a character then we print it yeah I'm not understanding let me print is nice up here and I think we might now we should have a year um we're adding the string yeah I'm oh is there no there's not an extra space with printing console.log string we're saying is a a a nice screen I think we can tell actually if we print I think if we print all nice strings I think if we print all nice strings we'll see that empty string I think is we'll see that empty string I think is in there in there right so there's actually a couple of right so there's actually a couple of empty strings in there empty strings in there that's actually interesting I wonder oh that's actually interesting I wonder oh I guess because we're starting I guess because we're starting yeah we check if the first string I see yeah we check if the first string I see so I think we want to do is you can so I think we want to do is you can delete this line delete this line and we'll basically say right if F dot and we'll basically say right if F dot length length equals zero we'll return to false right equals zero we'll return to false right it's not a nice string that way our data it's not a nice string that way our data won't be skewed towards empty values oh and then we wanted the longest substring so if we wanted the longest substring I'm also yeah this after we want the longest substring right so if that's the case we can do B minus a DOT length and return the first element which should be the smallest I mean the largest some reason we're returning some reason we're returning empty string here it's just strange you shouldn't have any so for I is equal to zero right we're so for I is equal to zero right we're going to start with the string we're going to start with the string we're going to set start with b right we check going to set start with b right we check if the empty string is nice it's not so if the empty string is nice it's not so we add a capital B which I have capital we add a capital B which I have capital B is nice right we'll say J equal to I so d0 right we check if the string is nice empty string it's not so we add a character I think you now actually want this up I think you now actually want this up here this very slow solution and there's actually no solution given up so I think this would be uh this would actually be we have a double for Loop so we have N squared time but our solution to check if something is nice is at worst case we're iterating over the entire string so I would actually say this is n cubed time in the worst case so this maybe there's a linear times linear times solution what if we remove the pair so if we had what if we remove the pair so if we had this string here this string here a a y we removed these two y's that we A a a y we removed these two y's that we A and A and A right there would be three strings left right there would be three strings left this would be what we have remaining this would be what we have remaining doesn't seem like a viable option what doesn't seem like a viable option what if we only remove pairs that have a uppercase and a matching pair have y here y hearing with a and a that's the case then longest string used to so it's actually not the string so if we had a b b b b we have capital B lowercase I mean this we have capital B lowercase I mean this one makes sense right s I think I know what we could do I think I know what we could do so what if we have a we have a sliding so what if we have a we have a sliding window we have y a z right window we have y a z right and then as we iterate through what and then as we iterate through what we'll do is we'll make certain right on we'll do is we'll make certain right on each iteration we should be able to tell each iteration we should be able to tell in constant time whether or not our in constant time whether or not our string is well it wouldn't be constant time this would be I think in worst case it'd be N squared times would be an improvement we'd have y right we check if it is a nice string right and it's not a nice string no that right and it's not a nice string no that wouldn't work either because we want a wouldn't work either because we want a greedy version [Music] want a linear time solution linear time what if we did this add addition and what if we did this add addition and subtraction right okay well if we know that the nicest okay well if we know that the nicest string has string has let's read the problem for every letter let's read the problem for every letter of the Opera that has contains it of the Opera that has contains it appears both in uppercase and lowercase given a string s return the longest substring of s that is nice longest solution is at statistics if there are multiple return the substring hmm hmm none return an empty string that that none return an empty string that that one is yeah the linear time here is very one is yeah the linear time here is very very difficult to be like our current version is n cubed related topics hash table dividing I knew there was a divide and conquer a solution to this I knew there was a divided in conquer it's also a bit manipulation I knew there's something there with that so I know you can add foreign one way we can check if a substring is one way we can check if a substring is nice we could also use this version uses nice we could also use this version uses two for Loops over s another version two for Loops over s another version right you could iterate through the right you could iterate through the string or I would have y right and we'll string or I would have y right and we'll check we could have a map right of check we could have a map right of character to we'd want pretty much yeah this one yeah this one I'm gonna have to we're gonna we're definitely gonna have to get back into the lab on how to make sense of linear time solution here but he's been we I did like six or six five six hours today it's been 30 minutes uh on on recording
2024-03-22 12:41:47
1,763
https://i.ytimg.com/vi/N…axresdefault.jpg
LeetCode everyday: Day 52 - LC 1763 IS IMPOSSIBLE
CnhxX00MMTI
good day to you my dear friends well it's time to solve some lead God well it's time to solve some lead God problems today I increased the quality a little let's see I'm a little bit tired because I participated in in the lead Club contest yesterday and then I participated in the lead code contest today so also I have new neighbors also I have new neighbors and they are loud and they are loud you know they get drunk and they scream you know they get drunk and they scream at each other at each other well not constantly but from time to well not constantly but from time to time oh and it's a rare thing you know when an and the funniest thing there is a very and the funniest thing there is a very loud woman there and once she came to me loud woman there and once she came to me it was like the first or the second day it was like the first or the second day of the living here of the living here and he said to me you know I hear a woman screaming from from time to time do you know what what's it all about and I answered no I do not know and then said okay and then I will go some I'll go ask some other neighbors and she disappeared and after that I understood that the woman that always screams is that woman she asked about herself I don't know what was that about it's like she created a small diversion because she raised this issue first so no one would suspect her ah what a plan let's go back to more let's go back to more mundane things like liquid problems mundane things like liquid problems yesterday yesterday I encountered I encountered terrible terrible problem problem well it wasn't that hard but well it wasn't that hard but of of it was hard for me it was my SQL oh this was my this is a nice version it's the same it's just structured better so what was the problem so what was the problem we got a table employee ID Department ID we got a table employee ID Department ID primary flag and some employees they are primary flag and some employees they are presented presented one time in a table and some employees one time in a table and some employees presented more than one time presented more than one time and for those for Unique employees there is only one for Unique employees there is only one option for primary flag it's a letter option for primary flag it's a letter but if they have many different but if they have many different departments departments one of them one of them should have a wide primary flag should have a wide primary flag and our goal and our goal is to list all employees and their is to list all employees and their departments departments you know you know often there was often there was so many attempts by me and even some so many attempts by me and even some suggestions in the chat from no condom suggestions in the chat from no condom crease arrived to this solution with inner join max value Max primary flag you know for max value Max primary flag you know for each employee and then we connect this each employee and then we connect this thin thin to our original table to our original table no not original to our table with no not original to our table with employee and Department and now each employee is going to have only his maximum primary flag this is a solution with inner join but solution from no condom crease is also good to use Union do this do this select flags for years Flex it's kinda easy flags for years Flex it's kinda easy check check we are going to have employee 2 and then we are going to have employee 2 and then play E4 and I have a runtime error apartment [Music] okay two and four and the Departments are one or three great and we are going to Union to another query and let's for now comment it out and let's write a second query and it's gonna be what it's gonna be okay of course employee ID and Department ID now let's group now let's group bye Kevin what do we want to count by the way it's one one it's one one three three three three good good and yesterday I had this idea you know and yesterday I had this idea you know that I somehow must count employee IDs but I forgot about this having keyword and I wasn't able to to Google it or something and okay okay Houston we have a problem what what foreign let's see what's the difference let's try this I'll do it here no of course it doesn't matter no of course it doesn't matter where is the error where is the error Union Union select everything seems nice Department ID Department ID it's fun foreign employee employee employee ID comma Let's Lose the brackets and see what will happen no we have a problem oh of course I'm a no we have a problem oh of course I'm a bloody yeah yeah let's forget about this let's forget about this incident and of course there is another way there and this will will be and this will will be to use a more elaborate so we are going to have so we are going to have to wear with to wear with select select in another select and I also tried this in another select and I also tried this approach and also failed I don't know I don't think it's even now it's our favorite one where uh now it's our favorite one where uh primary key is it working you see it's so it's a very important thing to come back to solve the issues and it's even more important than solving an it's even more important than solving an issue in the first place issue in the first place where oh no oh no it's not like this okay something it's the strangest output in the world it should be where nope that's goodbye let's Group by and again we are going to use our new and again we are going to use our new favorite having favorite having count you can do this this way we get we got all right right now and not and probably or not and probably or or primary flag or primary flag equals equals why great so this is another another great so this is another another solution solution without joins without unions and I'm quite happy that I was able to reproduce it now let's go to a solution section let's see what we have here well I already told you what we have here um one of the most upvoted it's the version of this solution and the strange thing is that it's very about and there are no comments but actually you do not need this tip here and you do not need order by here maybe I should leave a comment comment or maybe that's a no so this is this is this was an issue so this is this is this was an issue number 1789 primary department for for number 1789 primary department for for each employee now each employee now for something completely different let's take some issue that I solved some problem that I solved previously before I started streaming in depth easy difficulty easy difficulty for now we already covered these two and these two and concatenation and build array the one function call and our next victim is this one eleven oh eight defending an IP address so we have an IP address in this form and we want to replace all dots with very easy very easy with the G sub and in most damages it's with the G sub and in most damages it's done in the same manner done in the same manner my additional solution was like this my additional solution was like this now I now I decided to add a bang decided to add a bang you know you know so that we do not return a new so that we do not return a new stream but modify our original stream stream but modify our original stream and return this modified original stream and return this modified original stream maybe it's better in terms of space maybe it's better in terms of space well because you see when we do it like well because you see when we do it like this and our address still and our address still has all the dots but if we do this with has all the dots but if we do this with the bank address stream is also modified not also address stream is also modified not also it is modified it is modified so maybe it is better so maybe it is better maybe there's no difference at all I'm maybe there's no difference at all I'm not sure I'd love to see some comments on that but until that day until these comments I will proceed with adding bang to everything so yeah it's a small problem and most so yeah it's a small problem and most solutions are exactly like this solutions are exactly like this there is a variant to go through every symbol in address this character to a string this character to a string if it's a DOT well we add not dot but if it's a DOT well we add not dot but doesn't brackets to a string doesn't brackets to a string but it's not very effective because we but it's not very effective because we go through every character another go through every character another approach is to split approach is to split address split by the dot like let's do address split by the dot like let's do this by the way this by the way just to have an exercise split by Dot yes and after that yes and after that join it back together join it back together with dotting brackets as always as always would be interesting to see what a dress would be interesting to see what a dress looks like in this situation the rest doesn't change so should we use a lot of bands oh my God scared the out of me what just happened there method 91 so I I've seen that you tried some kind of a Marathon today for me it's hard to stream even for an for me it's hard to stream even for an hour let's go back to this problem I added let's go back to this problem I added Banks everywhere it's like Banks everywhere it's like the song from Kill Bill like Bang Bang the song from Kill Bill like Bang Bang you shut me down bam bam I hit the you shut me down bam bam I hit the ground oh you can't do that Bang Bang so so our G sub variant is the best but our G sub variant is the best but under the hood it probably does the same under the hood it probably does the same thing so do not let it shortness you know confuse you and make you make you think that you are some kind of and now and now let's solve some money your problem by the way let's check this out let's check my rank nah it's still it holds maybe just one more problem relax take it easy I don't remember this song I got it's an SQL problem well come back I got it's an SQL problem well come back in an hour and I will still be sitting in an hour and I will still be sitting here trying to solve this problem here trying to solve this problem so we have a table activity so we have a table activity player ID into the device ID integer player ID into the device ID integer event date date in games played integer event date date in games played integer here is it here is it find the first login date find the first login date for each player for each player aha aha return the result table in any order return the result table in any order by the way in the previous problem by the way in the previous problem there was also this there was also this line that we can return results in any line that we can return results in any order but order but if it wasn't the case our Union solution or we just or we just we would just add all the buy and we would just add all the buy and everything will be good so so we have this activity table output why do we need games played why do we need games played just a distraction huh but if I said it doesn't matter you just it's like the earliest oh there is a trap somewhere let's see an example like player id1 device ID 212 and the earliest date is this one yes the second man well this one and third okay let's try select okay let's try select player player ID and min event date because it's not gonna work from the get-go but we'll get it there forum forum what uh what was it activity activity in group by and let's see let's see so long so long it's green please first try have you seen first try have you seen that it was beautiful it was marvelous that it was beautiful it was marvelous ah ah okay correct that nut well of course it okay correct that nut well of course it was easy oh as I always say as I always say such a nice feeling but that's it for today miraculously yay I'm so happy because I'm so tired after all these contests and at each of these contests I was only able to solve oh I have this feeling that I wanted to say something but I don't remember like at all so I see I'll see you tomorrow good people of I don't know Elite code solving by the way probably I am the only person by the way probably I am the only person who actually had smart coder tag to my who actually had smart coder tag to my text text yeah so yeah so I read I read a file with instructions a file with instructions but that's it I'll see you tomorrow but that's it I'll see you tomorrow thank you very much be cool where is this button ah
2024-03-22 14:43:01
1,789
https://i.ytimg.com/vi/C…axresdefault.jpg
LeetCode problems #1789 (MySQL), #1108 (Ruby), #511 (MySQL)
KPLGOEK1mhs
hello everyone.welcome the hacker key in this video we will look into solving the problem validates IP address it is a medium problem but it's very straightforward problem before we start please do like and subscribe to the channel hacker d let's look into this given a string we need to determine if it's an ipv4 or an ipv6 so let's look into the characteristics of ipv4 or ipv6 so for ipv4 if you look into this there will be four segments for ipv4 so the total segments will be four and these are separated by dot and for ipv6 these are separated by colons and there are eight segments 1 2 3 4 5 6 7 8 so 8 segments we need to check those and the maximum IP is 255 255 dot 255 255 the segment should in be greater than 255 255 and the values for the segment should be between the each character should be between 0 and 9 that is 1 check we need to do and we also need to check that are not trailing or prefix dots similarly in ipv6 what we will check is the length of each segment should be between 0 to 4 and the character in each segment should be between 0 to 9 or a too small F or capital a to capital F the third we need to check if all this checks are past we would return either ipv6 or ipv4 if none of them passed you just return neither let's go ahead and quit this out so the first thing we need to check is if the given IP is equal to null or IP dot length is equal to 0 we'll just return later now we need to check if IP dot check IP of IP and IP dot contents : we will just return check IP v6 of IP all right none of them we will just return neither now we need to define these functions mix check ipv4 IP let me copy this and say few seconds get six so we talked about it we need to check for ipv4 there are no trailing dots if IP dot third of 0 is equal to dot of IP dot butin I'll go ahead and define a string so that I and now that is done we will divide this and now that is done we will divide this IP into segments now we will check the IP into segments now we will check the number of segments should be four if not number of segments should be four if not we will just return neither and that's we will just return neither and that's it now for each segment what we need to check is we need to check segment length should be between zero and three and if there is a start in character starts with zero the length of the segment should be one you can check that condition all Sigma dot carat of zero segment dot length rather than one just return and now we check that for each character in the segment we 1009 just written and now we will check 1009 just written and now we will check the integer value of the string should the integer value of the string should it be greater than 255 future dot value it be greater than 255 future dot value of segments greater than 55 return and of segments greater than 55 return and if everything looks good we'll just if everything looks good we'll just return for now coming to the attributes return for now coming to the attributes we will I'd be dot make the copies in a few seconds it will be looking for Poland not a dot go gesture jump and maybe we will split into segments with all four color and check a sec mins dot length not equal to eight for ipv6 it should be eight segment we need to check a segment then put a zero dot greater than 4 in ipv6 each segment is of length four just written on that is good for we need to check that each character is then say now we need to check if it's between 0 now we need to check if it's between 0 to 9 it is tablet capital f no see and I can cover this and you chose and I can cover this and you chose between 1/2 capital a to capital F just between 1/2 capital a to capital F just written and everything is good 210 ip6 written and everything is good 210 ip6 all right let's go ahead and submit hmm all right let's go ahead and submit hmm care cannot be converted into cash care cannot be converted into cash sequence oh this is string dot always sequence oh this is string dot always something right bunch of typos sorry something right bunch of typos sorry about that about that all right here we go I hope it's clear all right here we go I hope it's clear all we are checking for if it contains all we are checking for if it contains dot will check for ipv4 if you don't dot will check for ipv4 if you don't condense a call and we will check for condense a call and we will check for ipv6 in ipv4 we will check there are ipv6 in ipv4 we will check there are four segments and each segment length is four segments and each segment length is between 0 to 3 and the characters are between 0 to 3 and the characters are between 0 to 9 for ipv6 we will check between 0 to 9 for ipv6 we will check there are eight segments if the length there are eight segments if the length of the character segment is between 0 to of the character segment is between 0 to 4 and for each character is between 0 to 4 and for each character is between 0 to 1 9 a 2 small small it is smaller and 1 9 a 2 small small it is smaller and calculated capital F that's all we are calculated capital F that's all we are doing so I hope it's clear please do doing so I hope it's clear please do like and subscribe to this channel like and subscribe to this channel hacker thank you for
2024-03-18 10:52:38
468
https://i.ytimg.com/vi/K…axresdefault.jpg
Leetcode 468 Validate IP Address Java Solution
jhCGILLv5-w
welcome ladies and gentlemen so today we are going to solve google most asked are going to solve google most asked question which is longest consecutive question which is longest consecutive sequence this is a google frequency sequence this is a google frequency frequently asked question so frequently asked question so without any further ado let's start without any further ado let's start solving this problem okay so to solve solving this problem okay so to solve this problem what the question is first this problem what the question is first of all we are over here we say like we of all we are over here we say like we given an unsorted area of integers and given an unsorted area of integers and we have to written the length of longest we have to written the length of longest consecutive sequence element element consecutive sequence element element sequence okay you must write an sequence okay you must write an algorithm in one times okay so it says algorithm in one times okay so it says like when you write it one time so like like when you write it one time so like you know it's thing like you can't use you know it's thing like you can't use sorting like you know if you use sorting sorting like you know if you use sorting then uh it will be of any log so then uh it will be of any log so basically initially like in the first basically initially like in the first step i think like okay why don't we go step i think like okay why don't we go for the sodium then i just check it over for the sodium then i just check it over this thing like oh this thing like oh constant of oil in times okay so for the constant of oil in times okay so for the own times we can use hash map to solve own times we can use hash map to solve this problem okay so hashtag is quite this problem okay so hashtag is quite good to use it okay good to use it okay now let us see like what the input is now let us see like what the input is saying and how we're going to use saying and how we're going to use schrodinger has been to schrodinger has been to okay so first of all what i will do i okay so first of all what i will do i will gonna use a sorting method okay and will gonna use a sorting method okay and i will tell you the i will tell you the approach and everything over here okay approach and everything over here okay so first of all what i will do i will so first of all what i will do i will create it and add it i will use edit create it and add it i will use edit sort function and i will swap my array sort function and i will swap my array so we will use this example so um it so we will use this example so um it will become it become one two three four will become it become one two three four hundred and two hundred like this okay hundred and two hundred like this okay guys okay after getting this what i will guys okay after getting this what i will do do i will simply gonna say okay now create i will simply gonna say okay now create one current pointer and run my max one current pointer and run my max pointer my current pointer and my max pointer my current pointer and my max point my current pointer will initially point my current pointer will initially point over here okay so and i will get point over here okay so and i will get uh uh initialize with one let's say like if we initialize with one let's say like if we have something any any value in our uh have something any any value in our uh in our like array that length is one in our like array that length is one because that value because that value length count is one okay so uh let's see length count is one okay so uh let's see over here so my current is one and what over here so my current is one and what i'll do i have five is next sequence i'll do i have five is next sequence which is two so it is two over here it which is two so it is two over here it is true so i will update my current and is true so i will update my current and i will update my max as well okay now my i will update my max as well okay now my another sequence is three so two plus another sequence is three so two plus one is three yeah we have three so i one is three yeah we have three so i will update my max as well again okay will update my max as well again okay now i will go and check for four does it now i will go and check for four does it has four yes it has four even as well so has four yes it has four even as well so i will update my current and i will i will update my current and i will update my max as well now it will check update my max as well now it will check does it has five because four plus one does it has five because four plus one is five next liquid is five it will say is five next liquid is five it will say no no it doesn't have five so what i no no it doesn't have five so what i will do i will simply uh reset my will do i will simply uh reset my current to back one and my max initially current to back one and my max initially i have four i have four okay now what we have another one is 100 okay now what we have another one is 100 so it will say that's 100 plus one it so it will say that's 100 plus one it has 101 it doesn't know it doesn't has has 101 it doesn't know it doesn't has 101 okay so that like i i will not 101 okay so that like i i will not upgrade my max because my max has the uh upgrade my max because my max has the uh highest sequence longest sequence value highest sequence longest sequence value okay why should i update it okay then okay why should i update it okay then now i will check for another one which now i will check for another one which is 200 does it has 201 then i will again is 200 does it has 201 then i will again check like yeah it doesn't have any 201 check like yeah it doesn't have any 201 so i will simply gonna break it and i so i will simply gonna break it and i will come back from the loop and i will will come back from the loop and i will return the maximum of my uh return the maximum of my uh value from the max okay so i have i hope value from the max okay so i have i hope this thing is clear if you still know this thing is clear if you still know then don't worry while i'm gonna then don't worry while i'm gonna write the code you'll be definitely write the code you'll be definitely gonna understand okay gonna understand okay so by looking at this what things are so by looking at this what things are coming in my mind okay what i will do i coming in my mind okay what i will do i will simply first of all uh will simply first of all uh so we are using sorting okay so we are using sorting okay we are using something so first of all i we are using something so first of all i will create a base condition but will create a base condition but basically you will say my number line is basically you will say my number line is initially 0 so like my current point has a one one you can even go for the zero as well but you can even go for the zero as well but i will say like you know like at least i will say like you know like at least like your point is pointing to someone like your point is pointing to someone so it that that so it that that even that only simple digit even that only simple digit lag will become okay now in this one i will first of all okay now in this one i will first of all check i will check if if they are more check i will check if if they are more equal then only i'm going to if they are equal then only i'm going to if they are equal then i will know where to go so i equal then i will know where to go so i will check if my number of i will check if my number of i is not equal to my terms of i minus 1 so is not equal to my terms of i minus 1 so if my current value is not similar to if my current value is not similar to the previous value then only i will come the previous value then only i will come into this loop okay into this loop okay if that's the condition then what i will if that's the condition then what i will do i will check if my current value has do i will check if my current value has the difference of 1 to my previous value the difference of 1 to my previous value so i will say match dot so i will say match dot absolute off absolute off of i of i minus numbers of minus numbers of i minus 1 if it has the difference of 1 i minus 1 if it has the difference of 1 then i will simply increment my current then i will simply increment my current okay if either if if okay if either if if it has a difference then oh it has a difference then oh that that's good like it will like we we that that's good like it will like we we find the another sequence as well okay find the another sequence as well okay and what i do i have to upgrade my max and what i do i have to upgrade my max as well as well so i have to upgrade my max so for that so i have to upgrade my max so for that what i will do i will simply say max what i will do i will simply say max equals and i have to reset my current to one and i have to reset my current to one back again let's just say like if it's back again let's just say like if it's break break and like after four it doesn't have five and like after four it doesn't have five so now it does hundreds so i will uh so now it does hundreds so i will uh reset my current back to the one okay reset my current back to the one okay guys and finally like once it iterate guys and finally like once it iterate through all over the array and it to through all over the array and it to find like the maximum value so that i find like the maximum value so that i will again check like does my current will again check like does my current has the maximum value of my max and the has the maximum value of my max and the maximum value then i will check over maximum value then i will check over here as well by measured max of max for here as well by measured max of max for my current my current okay so i have no now the code is clear okay so i have no now the code is clear like what i'm doing over here like what i'm doing over here okay let me just run it and see like is okay let me just run it and see like is it going very well or not passing all it going very well or not passing all the test cases so it's just taking a the test cases so it's just taking a little bit time because my intent is little bit time because my intent is little slow down let me want to submit little slow down let me want to submit it it and see and see it's passing all the test cases or not it's passing all the test cases or not and everybody so it's accepting value so and everybody so it's accepting value so i hope the code is still like what we i hope the code is still like what we are doing over here so first of all i are doing over here so first of all i just sort it over here and then i get just sort it over here and then i get one pointer current which initially has one pointer current which initially has one and my similar max has one length as one and my similar max has one length as well then i uh well then i uh run it and then i'm checking like if my current pointer is not similar to my previous one if they are similar then i will i will just say i will never gonna enter in this one because it could that never be the sequence enough that never be a sequence okay and if if they are unequal then i will check is there is there difference is one of one if there is difference then it'll be like let's say like we have three minus um or three minus two is one so then different is one so it okay then i will update my current and okay then i will update my current and finally over here i have to upgrade my finally over here i have to upgrade my max as well upon into my current and if max as well upon into my current and if you let us say like um you let us say like um i found a different one then i will just i found a different one then i will just simply and reset my current to one and simply and reset my current to one and then that is the only one and five over then that is the only one and five over here i'm just getting my max function here i'm just getting my max function okay so i have to i hope so these things okay so i have to i hope so these things feel like how we are feel like how we are doing this okay so let us talk about doing this okay so let us talk about this time complexity the time complexity this time complexity the time complexity in this one we are dealing with end in this one we are dealing with end globe n globe n and our space complexity is one go for and our space complexity is one go for okay guys so i hope this i hope so this okay guys so i hope this i hope so this thing is clear okay but uh but our thing is clear okay but uh but our question is like we have to use sold question is like we have to use sold this in using uh owen types so for that this in using uh owen types so for that one i will gonna use hash map okay so one i will gonna use hash map okay so now let's just focus like how we're now let's just focus like how we're gonna uh solve this problem using hash gonna uh solve this problem using hash map okay so now let's show like how map okay so now let's show like how we're gonna install using hash one so we're gonna install using hash one so using hash now what i will do i will using hash now what i will do i will create uh create uh one integer one integer and one boolean and one boolean so one key and one value okay so my so one key and one value okay so my integer will be my key integer will be my key and my boolean will be my value okay and my boolean will be my value okay let's just see like like i'm just saying let's just see like like i'm just saying like what we're doing so we are using like what we're doing so we are using hashbrown so in my hash map i will get hashbrown so in my hash map i will get one integer one boolean okay now now one integer one boolean okay now now you'll ask why i will tell you you'll ask why i will tell you just wait i will tell you okay so now just wait i will tell you okay so now what we i have i have 100 i will write what we i have i have 100 i will write by all the entries over here of my by all the entries over here of my integer one three two and initially what integer one three two and initially what i will do i will mark all of them as i will do i will mark all of them as true true all of them initially are true all of them initially are true okay okay so i i just filled my hash map and i so i i just filled my hash map and i will fill all the entries let me just will fill all the entries let me just change the color okay guys so here we go change the color okay guys so here we go okay guys now what i will do i will okay guys now what i will do i will check done is my 100 is the starting of check done is my 100 is the starting of my consecutive sequence if it is my consecutive sequence if it is starting like let's select it does not starting like let's select it does not has if it isn't 99 any previous value as has if it isn't 99 any previous value as well then it never be the starting why well then it never be the starting why should i start from over 100 if it has should i start from over 100 if it has 99 so i'm going to check does my 100 has 99 so i'm going to check does my 100 has 99 over here no it doesn't have 99 over 99 over here no it doesn't have 99 over here so i'm just gonna uh leave it and i here so i'm just gonna uh leave it and i will come to the next one okay now all will come to the next one okay now all right by four i will check that's my right by four i will check that's my four s three four minus one is three so four s three four minus one is three so it will gonna look up and see yeah it it will gonna look up and see yeah it has three then what i will do i will has three then what i will do i will simply gonna mark this as fourth okay simply gonna mark this as fourth okay because my phone never be level will be because my phone never be level will be the starting of my observatory sequence the starting of my observatory sequence okay it it is a part of the sequence but okay it it is a part of the sequence but it is not the starting okay so now i it is not the starting okay so now i come over here over 200 come over here over 200 now i will check does my 200 has 199 it now i will check does my 200 has 199 it will gonna check again in in my uh will gonna check again in in my uh loop in my array it says like no no no loop in my array it says like no no no we don't have then what i will do i will we don't have then what i will do i will it leave it as true now i come out to it leave it as true now i come out to one does one minus one has zero it will one does one minus one has zero it will check so it's say like no it doesn't check so it's say like no it doesn't have zero so that whatever i will come have zero so that whatever i will come over here by three now it will check over here by three now it will check does three has two three minus one is does three has two three minus one is two it will gonna check here it has two two it will gonna check here it has two over here then what i will do i will over here then what i will do i will mark it as four because my three can not mark it as four because my three can not be a starting of my contributing be a starting of my contributing sequence it will do the part but it's sequence it will do the part but it's not the starting okay guys not the starting okay guys okay i hope so this thing is like what okay i hope so this thing is like what i'm doing so okay i'm doing so okay it is now i come over here on my two it is now i come over here on my two okay so over here what i will do i will okay so over here what i will do i will simply gonna check does my two has minus simply gonna check does my two has minus one the two minus one is one it has one one the two minus one is one it has one it was a yeah it has one it has one so it was a yeah it has one it has one so what i will do i will say don't mark what i will do i will say don't mark don't mark it don't mark it so don't take it at the starting because so don't take it at the starting because the starting is will be work okay so i the starting is will be work okay so i also like these things like how we are also like these things like how we are doing it okay doing it okay so let me just erase it so let me just erase it okay guys so now what uh we gonna how we okay guys so now what uh we gonna how we gonna check it okay so what i will gonna check it okay so what i will again run a loop so now i mark the again run a loop so now i mark the starting now i have the true one so the starting now i have the true one so the true one are the starting the older true one are the starting the older through one are the starting and the through one are the starting and the fourth one are the parts they are not fourth one are the parts they are not the starting so what i did i learned two the starting so what i did i learned two my first loop mark or mark all them has my first loop mark or mark all them has two my second loop mark the startings as two my second loop mark the startings as two only and we are remaining as phones two only and we are remaining as phones now my third loop now my third loop in my third loop guys what i will do i in my third loop guys what i will do i will take again two pointers my current will take again two pointers my current and my max so my current will and my max so my current will check check everyone lands from initially let's say everyone lands from initially let's say month i'm over here my current will be month i'm over here my current will be initially as one and my max will be as initially as one and my max will be as well because it doesn't so i will check well because it doesn't so i will check that's hundred plus one has that's hundred plus one has it will want to check or complete all it will want to check or complete all this one it will say no it does not have this one it will say no it does not have 101 so what i will do i will just simply 101 so what i will do i will just simply gonna uh remove it from over here and i gonna uh remove it from over here and i will come over here to this one will come over here to this one okay now i am on my phone it will check okay now i am on my phone it will check that's okay guys okay so now it will come over here it will check this 200 has to [Music] computer no 201 does not help so again my current will be one and max will be one so like like there is no need to upgrade because one is one okay okay guys now again what what what what will okay so my mistake okay so my mistake okay guys now again what will happen it okay guys now again what will happen it will come on the another two which is will come on the another two which is one now it will check this one has two one now it will check this one has two one plus one is two yes it has two over one plus one is two yes it has two over here it has two over here so what i will here it has two over here so what i will do i will update my one two by two okay do i will update my one two by two okay and my max will upgrade as well to two and my max will upgrade as well to two now it will check this just two plus one now it will check this just two plus one has three yes it has three i will has three yes it has three i will upgrade my current to three and my max upgrade my current to three and my max will be upgrade to three as well okay will be upgrade to three as well okay now it will check because three plus one now it will check because three plus one has four yes it has four so what i will has four yes it has four so what i will do i will update my current to 4 and my do i will update my current to 4 and my max for 4. now it will again want to max for 4. now it will again want to check this 4 plus 1 is 5. no it doesn't check this 4 plus 1 is 5. no it doesn't have to i just completely it take all my have to i just completely it take all my loop it does not have 5 and then maximum loop it does not have 5 and then maximum value which i found is 4 and i'm going value which i found is 4 and i'm going to remove my maximum value so that's how to remove my maximum value so that's how we gonna return our maximum value i hope we gonna return our maximum value i hope so the approach is here if you still so the approach is here if you still don't i will suggest you to just try to don't i will suggest you to just try to rewatch this video back again uh you rewatch this video back again uh you definitely want to understand okay guys definitely want to understand okay guys so here we go so here we go so now what i will so now what i will do is first of all i will create my hash do is first of all i will create my hash map and i hope so like you will map and i hope so like you will definitely want to understand i will not definitely want to understand i will not agree with this thing i'm just using agree with this thing i'm just using this part this part okay so let me just say completely and okay so let me just say completely and here we go ladies and gentlemen here we go ladies and gentlemen so it's completely okay so now what i so it's completely okay so now what i will do i will facilitate my hashmap will do i will facilitate my hashmap okay so my hashmap will be of my okay so my hashmap will be of my integer integer and not my boolean and not my boolean okay guys okay guys i like to put it so i'm just filling it so i've said map i i comma comma uh true uh true i will mark initially as true i fill the i will mark initially as true i fill the hashtag and i might mark all of them as hashtag and i might mark all of them as two okay now my second follower what i two okay now my second follower what i will do in my second formula is i will will do in my second formula is i will simply say do one thing simply say do one thing to start it from zero and i have to to start it from zero and i have to check if if my let's say my hundred and check if if my let's say my hundred and something of back as well like 99 something of back as well like 99 because 100 cannot be a starting effect because 100 cannot be a starting effect if it has 99 okay so i will want to if it has 99 okay so i will want to check over here and i will mark check over here and i will mark those one as opposed and i will leave those one as opposed and i will leave less of them as true okay less of them as true okay so whatever okay guys okay in this one what i will do i will check if my map contains key of numbers of i minus one i minus one similarly let's say four i think is the starting but it has three so four cannot be the starting so what i will do i will just simply upgrade it i will say map output that number i that that pointer has four mark it as phones okay now over here now over here what i have to do i have to get another for loop that for loop will gonna count and it will be the maximum value okay so first of all i will create my max initially zero okay so if you say like don't put a zero put at one so for you i'll put that one okay now what i will do i will just continue i will get my key and check if my map reset i will check whether my if my value is true i will check if my map dot contains key is true key is true if it if it is true if it if it is true then what i will do i will say then what i will do i will say get the maximum value like the get the maximum value like the max of max of [Music] [Music] max formula correct so for the current max formula correct so for the current one i will just use a cater function to one i will just use a cater function to find that that my function find that find that that my function find that will help me to get the current value will help me to get the current value okay so man okay so man okay guys okay guys and don't forget to release over here and don't forget to release over here now i will make a call to that now i will make a call to that function which we have created public function which we have created public and file name which you want to create and file name which you want to create so so okay guys now okay guys now i have to create my hashtag of integer till my map dot contains till my map dot contains p p of of t okay guys t okay guys if if till then it contains key till then it contains key okay then till then what i will do i okay then till then what i will do i will simply say increment by k will simply say increment by k and update my current as well and update my current as well so that's what i'm doing so that's what so that's what i'm doing so that's what it's doing like if it is four plus one it's doing like if it is four plus one five then i will say equilibrium current five then i will say equilibrium current as well okay and finally return my as well okay and finally return my current over here so that's the polar current over here so that's the polar body there in general so after the body there in general so after the scaling let me just scaling let me just view it clearly i hope the code is clear view it clearly i hope the code is clear that means gonna do all of this thing that means gonna do all of this thing from over here okay from over here okay so what i'm doing initially is i just so what i'm doing initially is i just get my hash map and i'm right i'm get my hash map and i'm right i'm filling my hash first of all then what filling my hash first of all then what i'm doing i'm marking i'm doing i'm marking the previous one if it is the previous the previous one if it is the previous uh positivity sequence then i will mark uh positivity sequence then i will mark it as fourth and over here i'm just it as fourth and over here i'm just saying like saying like don't become true don't become true just check their length and give the just check their length and give the length of the maximum maximum to give length of the maximum maximum to give the maximum length possibility sequence the maximum length possibility sequence let me just run it to see any let me just run it to see any compilation error will be faced compilation error will be faced so it seems like we're facing a so it seems like we're facing a compilation error over here okay so it's compilation error over here okay so it's not t is k not t is k by mistake by mistake okay guys so here we go is judging and okay guys so here we go is judging and we just get a five let me see what is we just get a five let me see what is that i think i think we have to give max that i think i think we have to give max zero zero might be might be might be because like might be might be might be because like you know in this one you have to give my you know in this one you have to give my my back is accepting very well so you know like you have to give max zero because you know like we are using hashtag so it's counting uh is counting the value so uh in the sorting one you have to give one or zero is for up to everybody in the hash mode you have to give zero so remember this thing okay so let me just want to submit it and i'm going to tell you space capacity and time complexity if this or the test case is accepted very well it's just taking a little little time because mine i told you my internet is working right a little bit slower is this good timing in this case okay guys so by mistake i just put content speed so it will become map.cat because we have to get that key by mistake i use content so let me just gonna uh can i copy this one no i can't copy this one so let me just gonna again submit it to see like mistakes happen i just put consecutive over here so it will come back look at it and here we go so it's something very well okay so now let's just talk about what the time [Music] type compression source problem so okay gentlemen i hope this program is clear and this is a google most frequently asked questions in the interview so thank you very much ladies and gentlemen for watching this video if you still have any doubts just do let me know in the comment section i will definitely release you and till then take care bye bye love you guys believe me i love you take care bye
2024-03-21 11:36:23
128
https://i.ytimg.com/vi/j…axresdefault.jpg
GOOGLE CODING INTERVIEW QUESTION - Longest Consecutive Sequence || Leetcode -128
eTZuMX9F8s4
hello everyone i hope all of you are having a great time i know it's it's a having a great time i know it's it's a monday and everyone's having monday monday and everyone's having monday blues but still we have to solve the blues but still we have to solve the lead code daily question and the lead code daily question and the question that we have in today is word question that we have in today is word search lead code 290. it's an easy level search lead code 290. it's an easy level question on lead code and i totally feel question on lead code and i totally feel the same to our surprise we have already the same to our surprise we have already solved this question in the month of solved this question in the month of september 2020 this was a time when we september 2020 this was a time when we started a channel and for those who have started a channel and for those who have been associated with the channel since been associated with the channel since long must be aware of it long must be aware of it i just went through the video i have i just went through the video i have clearly explained the entire concept clearly explained the entire concept behind solving the question and i would behind solving the question and i would urge you guys to have a look at it also urge you guys to have a look at it also please increase the speed to 1.2 x for please increase the speed to 1.2 x for better better understanding and apologies there is understanding and apologies there is slight noise in the video in the slight noise in the video in the starting so kindly please ignore it and starting so kindly please ignore it and do watch it till the end where i have do watch it till the end where i have coded it live for you guys coded it live for you guys over to you i hope you really enjoy over to you i hope you really enjoy watching the other video this brings me watching the other video this brings me to the end of today's session i hope you to the end of today's session i hope you enjoyed it if you did please don't enjoyed it if you did please don't forget to like share and subscribe to forget to like share and subscribe to the channel thanks for viewing it have a the channel thanks for viewing it have a great day ahead and stay tuned for more great day ahead and stay tuned for more updates from coding decoded i'll see you updates from coding decoded i'll see you tomorrow with another fresh question but tomorrow with another fresh question but till then good bye
2024-03-22 14:22:38
290
https://i.ytimg.com/vi/e…axresdefault.jpg
Word Pattern | Leetcode 290 | Live coding session 🔥🔥🔥🔥| Map Problem
mHsj83NoZDA
hey so welcome back and there's another daily code problem so today it's called daily code problem so today it's called non-overlapping intervals now I actually non-overlapping intervals now I actually did this one yesterday but I thought did this one yesterday but I thought we'd do it today and so essentially uh we'd do it today and so essentially uh what you're given here is just a what you're given here is just a two-dimensional array or I kind of like two-dimensional array or I kind of like thinking of it as really just a list of thinking of it as really just a list of tuples that's how I think of it tuples that's how I think of it um and essentially all that you want to um and essentially all that you want to do is you want to picture these kind of do is you want to picture these kind of like in a Time series so this will like in a Time series so this will indicate the time and it's basically a indicate the time and it's basically a timeline starting at zero and you can timeline starting at zero and you can imagine one two and then three and like imagine one two and then three and like so on so this could be like four and so so on so this could be like four and so what this kind of looks like in this what this kind of looks like in this graph here is the interval one to two graph here is the interval one to two without start here and go all the way up without start here and go all the way up to two then two to three would look to two then two to three would look something like from two to three three something like from two to three three to four well that's like this and then to four well that's like this and then one to three well that's essentially one to three well that's essentially from here all the way to here and so from here all the way to here and so what you want to do is essentially what you want to do is essentially remove the minimum number of intervals remove the minimum number of intervals so that there's no overlaps and so if so that there's no overlaps and so if we're looking for that essentially what we're looking for that essentially what you can see here you can see here is that the only one that really causes is that the only one that really causes overlaps is this one here these ones are overlaps is this one here these ones are fine because well although they touch fine because well although they touch They Don't Really overlap so that's okay They Don't Really overlap so that's okay so these two cases are fine the only so these two cases are fine the only thing that you really care about here is thing that you really care about here is that this one actually hovers over these that this one actually hovers over these other two and so naturally if we just other two and so naturally if we just kind of broke this one or removed it kind of broke this one or removed it that's incrementing our account from that's incrementing our account from zero to one it only took one removal so zero to one it only took one removal so that none of these intervals are that none of these intervals are overlapping and that's actually your overlapping and that's actually your answer here one answer here one all right and so essentially all right and so essentially um the first thing that I thought of um the first thing that I thought of when I was trying to solve this was okay when I was trying to solve this was okay it's kind of confusing hopping around it's kind of confusing hopping around here to find of these interval ranges so here to find of these interval ranges so just by sorting them it just made it a just by sorting them it just made it a lot more intuitive for me and so that in lot more intuitive for me and so that in this case is just moving one comma three this case is just moving one comma three to basically this location here so it to basically this location here so it looks like one three looks like one three all right so it goes one two one three all right so it goes one two one three two three three four I can't toss in my two three three four I can't toss in my head of okay what if we want to sort it head of okay what if we want to sort it by the second number and then the first by the second number and then the first number like maybe changing the Sorting number like maybe changing the Sorting algorithm a little bit but you don't algorithm a little bit but you don't actually have to do that you just have actually have to do that you just have to think about sorting it to think about sorting it um from the first value then the second um from the first value then the second value if that makes sense value if that makes sense um and so from here the only things that um and so from here the only things that you have to keep track of is essentially you have to keep track of is essentially the count because naturally you're going the count because naturally you're going to be incrementing the count but other to be incrementing the count but other than that the only thing that you really than that the only thing that you really need to be thinking about need to be thinking about is the previous interval or end interval is the previous interval or end interval number okay and that's that's the key to number okay and that's that's the key to everything here and so initially the everything here and so initially the previous n interval number will be two previous n interval number will be two like when did the previous interval end like when did the previous interval end okay and so essentially you're just okay and so essentially you're just going to be looking at from the first going to be looking at from the first interval like index one not index zero interval like index one not index zero onwards so you set the previous to two onwards so you set the previous to two and then you look at basically this and then you look at basically this interval and these ones onwards from interval and these ones onwards from that and so you're just comparing okay that and so you're just comparing okay did this interval end before this one did this interval end before this one start if not then naturally there's an start if not then naturally there's an overlap otherwise you just take the new overlap otherwise you just take the new ending as the current interval okay if ending as the current interval okay if that doesn't make much sense I think me that doesn't make much sense I think me showing it you the code and just showing it you the code and just relating it back to this diagram here it relating it back to this diagram here it might make more sense so I'll try to might make more sense so I'll try to stay with me stay with me and so once again the first thing that and so once again the first thing that we want to keep track of is naturally we want to keep track of is naturally the count because that's what we're the count because that's what we're going to want to return here going to want to return here and we're also going to want to sort and we're also going to want to sort this for Simplicity this does cost this for Simplicity this does cost analog again time complexity so it's analog again time complexity so it's going to be the bottleneck up for this going to be the bottleneck up for this um algorithm but it uh it's a great um algorithm but it uh it's a great benefit otherwise you're going to be benefit otherwise you're going to be reiterating and pointing back and forth reiterating and pointing back and forth and it'll be more of an N squared and it'll be more of an N squared algorithm so it's worth the cost and so algorithm so it's worth the cost and so from here uh what you want to keep track from here uh what you want to keep track of is what is the previous like end time of is what is the previous like end time so I'll call it like previous end as a so I'll call it like previous end as a variable and so this is going to be variable and so this is going to be essentially the first interval in our essentially the first interval in our list and basically the end of that list and basically the end of that interval interval and so once again we're just going to and so once again we're just going to iterate through all these intervals iterate through all these intervals um from the first index onwards because um from the first index onwards because we don't want to consider the first we don't want to consider the first index here because that's our previous index here because that's our previous end end so that just looks like in Python like so that just looks like in Python like that because you can just use a python that because you can just use a python slicing to simplify it slicing to simplify it and so once again there's only two and so once again there's only two different cases that we have to consider different cases that we have to consider so we can just use the NFL it's for this so we can just use the NFL it's for this and the first case is what if there is and the first case is what if there is no overlap so the previous no overlap so the previous um um the previous interval ends before the the previous interval ends before the current one starts that's the key for current one starts that's the key for this first one this first one so if the previous interval ended before so if the previous interval ended before the current one even started that's fine the current one even started that's fine let's just update the new previous end let's just update the new previous end date and so what that looks like in if date and so what that looks like in if statement is just okay is the previous statement is just okay is the previous and less than or equal to because it's and less than or equal to because it's fine if they touch they just can't fine if they touch they just can't overlap the current interval overlap the current interval I will call this interval I will call this interval um it's start time so we check if the um it's start time so we check if the current one started current one started um after this one has ended um after this one has ended and so then naturally we just want to and so then naturally we just want to update our new previous end to this new update our new previous end to this new end end to do the starting one we want to do to do the starting one we want to do index at zero sorry about the confusion index at zero sorry about the confusion and so from here this case is there is and so from here this case is there is an overlap an overlap and so we want to handle that overlap and so we want to handle that overlap and basically once again increment our and basically once again increment our account but we also want to update this account but we also want to update this new previous endpointer new previous endpointer and so the reason is for that is because and so the reason is for that is because while this the previous intervals end while this the previous intervals end time time um um has ended between this interval range has ended between this interval range that we're currently looking at and so that we're currently looking at and so the key to solving this problem is we the key to solving this problem is we want to take whichever one want to take whichever one ends earliest because if you take the ends earliest because if you take the previous end time of a date or a time previous end time of a date or a time that ends like kind of later on there's that ends like kind of later on there's a higher probability that it's going to a higher probability that it's going to overlap with an upcoming interval so overlap with an upcoming interval so let's just take the one that ends the let's just take the one that ends the earliest so you don't have that problem earliest so you don't have that problem and that's how you basically get the and that's how you basically get the minimum number of intervals minimum number of intervals okay and so in code what that looks like okay and so in code what that looks like is let's just compare the current is let's just compare the current previous end time with the current previous end time with the current previous end time previous end time all right so let's try running that all right so let's try running that looks good and success so for time and space complexity well our time complexity is going to be analog again because this sorting is the bottleneck and for space complexity well the only storage that we're really using here is a constant space variables so you don't have any um uh space complexity such as old one or constant space but yeah I hope this helped a little bit and rest your albums
2024-03-22 12:11:19
435
https://i.ytimg.com/vi/m…axresdefault.jpg
435. Non overlapping Intervals - LeetCode Python Solution
RfMroCV17-4
hey guys Greg here let's solve minack which is leak code problem 155 it is a which is leak code problem 155 it is a very interesting problem where I think very interesting problem where I think it's super clever once you know the it's super clever once you know the answer and it feels like you can get to answer and it feels like you can get to that answer but sometimes you just don't that answer but sometimes you just don't quite get it and here you are so let's quite get it and here you are so let's check it out so this is one of those check it out so this is one of those questions where you design a class and questions where you design a class and that's actually very common for Fang that's actually very common for Fang style interviews they get you to design style interviews they get you to design basically a very clever class so we want basically a very clever class so we want to design a stack that supports push so to design a stack that supports push so putting an element on the stack popping putting an element on the stack popping to taking the most recent one off top to taking the most recent one off top simply asking what is on the top without simply asking what is on the top without popping it off and retrieving the popping it off and retrieving the minimum element in constant time so minimum element in constant time so that's the new interesting one that that's the new interesting one that makes this all difficult so we want to makes this all difficult so we want to implement the minst class where minack implement the minst class where minack the Constructor simply initializes the the Constructor simply initializes the stack object you can really do whatever stack object you can really do whatever you want there a void push so void just you want there a void push so void just means it doesn't return anything so it's means it doesn't return anything so it's going to push a value onto the stack so going to push a value onto the stack so it just pushes the element Val onto the it just pushes the element Val onto the stack void pop so that's actually stack void pop so that's actually strange that it's void because generally strange that it's void because generally it would return the thing that's on the it would return the thing that's on the stack but here it's just going to remove stack but here it's just going to remove the element on top of the stack and not the element on top of the stack and not return anything we have int top so return anything we have int top so that's just going to ask what the top that's just going to ask what the top element on the stack is it gets the top element on the stack is it gets the top element without removing anything and in element without removing anything and in get min is going to just get the minimum get min is going to just get the minimum element on the stack and don't worry we element on the stack and don't worry we don't have to pop that off that would don't have to pop that off that would actually be a lot more difficult and actually be a lot more difficult and again we must Implement a solution with again we must Implement a solution with o of one time complexity for each o of one time complexity for each function so anytime we run any of these function so anytime we run any of these functions once we expect that to be functions once we expect that to be constant time now let's say that in constant time now let's say that in order you're going to put on these four order you're going to put on these four values into the stack now what's very values into the stack now what's very clever here is we're actually going to clever here is we're actually going to make two stacks and that's totally fine make two stacks and that's totally fine because you're really just using because you're really just using precisely double the space and so we're precisely double the space and so we're going to start out with two empty Stacks going to start out with two empty Stacks where this one I'm just going to call it where this one I'm just going to call it s it's basically our normal stack and s it's basically our normal stack and here I'm going to call this m because here I'm going to call this m because this is the one that keeps track of this is the one that keeps track of specifically the minimum now it's put on specifically the minimum now it's put on our first value which is five and so our first value which is five and so that's just going to be an append where that's just going to be an append where we put five onto this stack and this one we put five onto this stack and this one is always going to keep track of the is always going to keep track of the minimum in the same place of here and minimum in the same place of here and that'll make sense shortly but here for that'll make sense shortly but here for this element of five well the minimum is this element of five well the minimum is also five so we're just going to append also five so we're just going to append that as well let's put on our second that as well let's put on our second element of four so if we do that on our element of four so if we do that on our stack well we just want to do an append stack well we just want to do an append and so we put four at the end and then and so we put four at the end and then our minimum what is the minimum well it our minimum what is the minimum well it could add be five or it could be four we could add be five or it could be four we know that four is the smaller value so know that four is the smaller value so we will append the minimum and that is we will append the minimum and that is going to be four now let's say for a going to be four now let's say for a second you asked what the minimum was second you asked what the minimum was well we could just return the top of our well we could just return the top of our minimum stack which is going to be four minimum stack which is going to be four now suppose again that we actually now suppose again that we actually popped this element off here so if you popped this element off here so if you called pop that's going to remove this called pop that's going to remove this for our minimum stack when we pop we're for our minimum stack when we pop we're actually going to pop that as well and actually going to pop that as well and notice again here if you were to ask the notice again here if you were to ask the minimum well it's still five at this minimum well it's still five at this point but we're actually going to undo point but we're actually going to undo that and just carry on now let's put on that and just carry on now let's put on our new value which is -1 here onto this our new value which is -1 here onto this deack we're simply just going to add a deack we're simply just going to add a -1 now for the minimum we want to put on -1 now for the minimum we want to put on the smallest value but notice we don't the smallest value but notice we don't actually have to ask about this because actually have to ask about this because we know that this value is going to be we know that this value is going to be smaller than this one in fact it's smaller than this one in fact it's always going to be organized like this always going to be organized like this where we have the minimum on the top where we have the minimum on the top here so four is the minimum on the top here so four is the minimum on the top we want the minimum which is again going we want the minimum which is again going to be 1 and so if you asked at this to be 1 and so if you asked at this point what is the minimum well you would point what is the minimum well you would return the top which is -1 get minimum return the top which is -1 get minimum is always just going to return the top is always just going to return the top of our minimum because that's always of our minimum because that's always where it's going to be stored as we add where it's going to be stored as we add our element of 10 well we're going to our element of 10 well we're going to add 10 over here as expected but then add 10 over here as expected but then here we want to add the minimum well the here we want to add the minimum well the minimum is either my newest value or it minimum is either my newest value or it is the thing that's at the top we don't is the thing that's at the top we don't care about all this stuff because it's care about all this stuff because it's still always organized like like this still always organized like like this where it's going to get smaller as it where it's going to get smaller as it goes further why is that the case well goes further why is that the case well we always want the minimum to be stored we always want the minimum to be stored on the top so in this case well -1 is on the top so in this case well -1 is actually smaller than 10 so our new actually smaller than 10 so our new minimum is the same as our old minimum minimum is the same as our old minimum and if you asked at this point what is and if you asked at this point what is the minimum well it's -1 we just return the minimum well it's -1 we just return the Top If we popped anything off here the Top If we popped anything off here if you popped off our 10 well then we if you popped off our 10 well then we need to simply just pop off this value need to simply just pop off this value yet again we ask the minimum in here yet again we ask the minimum in here well it's still the top right here if well it's still the top right here if you were adding a new value like -20 you were adding a new value like -20 well that could be the new minimum or well that could be the new minimum or maybe it wouldn't be we'd add -20 onto maybe it wouldn't be we'd add -20 onto our normal stack is that the new minimum our normal stack is that the new minimum well is it smaller than this value the well is it smaller than this value the top of our Min stack yes it is and so top of our Min stack yes it is and so our new minimum is going to be stored at our new minimum is going to be stored at the top right here we will always keep the top right here we will always keep track of the minimum at the top of the track of the minimum at the top of the stack so let's just pop everything off stack so let's just pop everything off here if we take off the -20 we are going here if we take off the -20 we are going to take off the -20 over here you ask to take off the -20 over here you ask the minimum it's at the top right here the minimum it's at the top right here say we took off the -1 well we take off say we took off the -1 well we take off the ne- 1 here if you ask the minimum it the ne- 1 here if you ask the minimum it is going to be four same thing if you is going to be four same thing if you popped it off we pop it off both get the popped it off we pop it off both get the minimum it's five same thing repeats if minimum it's five same thing repeats if you added another value maybe you added you added another value maybe you added a value of 10 Well we'd add it 10 over a value of 10 Well we'd add it 10 over here but you wouldn't add the 10 over here but you wouldn't add the 10 over here because that's bigger than the here because that's bigger than the value on our top which is the minimum value on our top which is the minimum and so we would add the same value as it and so we would add the same value as it was before so let's write our code we was before so let's write our code we need two Stacks so in the Constructor or need two Stacks so in the Constructor or the init function we'll make a self. the init function we'll make a self. stack to be an empty list and we want stack to be an empty list and we want self. Min stack that's our M to be self. Min stack that's our M to be another empty list they're both just another empty list they're both just going to act as Stacks but the Min stack going to act as Stacks but the Min stack will always be in control of the minimum will always be in control of the minimum value now when we push that's the most value now when we push that's the most interesting function here so we always interesting function here so we always want self. stack. append the value our want self. stack. append the value our new stack is just going to accept that new stack is just going to accept that value however for our Min stack we need value however for our Min stack we need to say well firstly if we don't have a to say well firstly if we don't have a self. min Min stack meaning our Min self. min Min stack meaning our Min stack is empty well we know we just want stack is empty well we know we just want the value so we'll self. Min stack. the value so we'll self. Min stack. append the value however if it's true append the value however if it's true that the self. Min stack at -1 so that that the self. Min stack at -1 so that means the top of our minimum stack means the top of our minimum stack meaning our minimum our current minimum meaning our minimum our current minimum so if our current minimum is less than so if our current minimum is less than the value well that means that our the value well that means that our minimum value is still the minimum value minimum value is still the minimum value okay our value is bigger so we're not okay our value is bigger so we're not interested in keeping that we want the interested in keeping that we want the old one that means we do a self. minst old one that means we do a self. minst stack. append with our previous minimum stack. append with our previous minimum which is just the same value right here which is just the same value right here so we want this one our previous minimum so we want this one our previous minimum stays the same otherwise if that wasn't stays the same otherwise if that wasn't true we want self. Min stack. append the true we want self. Min stack. append the value need that new minimum and so we value need that new minimum and so we will append that and the other functions will append that and the other functions from here are really not too interesting from here are really not too interesting you want to do a self. stack.pop you want to do a self. stack.pop whenever we pop and you also want the whenever we pop and you also want the minimum to match we also do a self. Min minimum to match we also do a self. Min stack.pop when we add ask what's on the stack.pop when we add ask what's on the top well that means just our normal top well that means just our normal stack so we want return self. stack at stack so we want return self. stack at -1 our minimum is not involved there but -1 our minimum is not involved there but when we want the minimum well we've when we want the minimum well we've actually already used that this is our actually already used that this is our current minimum we want the self. Min current minimum we want the self. Min stack at -1 that is just the top of our stack at -1 that is just the top of our minimum stack or our minimum value as minimum stack or our minimum value as you can see all of these functions just you can see all of these functions just use aent or pop that means they're on use aent or pop that means they're on average constant time so that checks average constant time so that checks these boxes and we just have to return these boxes and we just have to return that value and that's really it if I that value and that's really it if I zoom out here you'll see all of the code zoom out here you'll see all of the code if we were to run that then we'll get if we were to run that then we'll get accepted now you probably wouldn't get accepted now you probably wouldn't get asked more about the complexity here but asked more about the complexity here but if you were to we' say that the time if you were to we' say that the time complexity is 0 of one for each complexity is 0 of one for each operation and the space complexity well operation and the space complexity well that is kind of O of n because in that is kind of O of n because in general you're storing this extra Min general you're storing this extra Min stack here that really has nothing to do stack here that really has nothing to do with the question it just happens to be with the question it just happens to be useful to solving the problem so I'd say useful to solving the problem so I'd say we're pretty much using an extra o of n we're pretty much using an extra o of n here I hope this was helpful drop a like here I hope this was helpful drop a like if it was guys and I'll see you later
2024-03-21 13:25:56
155
https://i.ytimg.com/vi_w…xresdefault.webp
Min Stack - Leetcode 155 - Explanation + Python Solution
hb_pWBPYMXM
Hello Hi Guys Welcome to Code West Today's Question is Gold and Tons in This Will Play a Game with Her Friend to Write the Number and Ask and Guess What the Number Subscribe Video Subscribe Jaitly in Both Its Position and Humid Number Locator Different Positions on a View To Return How Many How Many Times Hit And And Hit The Bell And Sometimes Hit The Cow So Let's Understand This With Example Lake Near Ones Cigarette Stringers 5207 Distance Between 10 And Friends Not Know About Distic But I Do n't Know About Different Is The Present In Distic 9 and to get the order order order status that is gas given to 781 299 plus extinct is 70 cigarette spring not s president but this position of gas in gas to consume subscribe to that in g string this platform position Secret Also Its Secret Also Its Secret Also Its elements for this also indicate that both elements for this also indicate that both characters of various positions match Buddhist characters of various positions match Buddhist Babool Babool a Noble Similarly 111 is President Hindi a Noble Similarly 111 is President Hindi Secret Secret Jai Hind Cigarette String All All Shoulder Jai Hind Cigarette String All All Shoulder Disposition of one in the same string and Disposition of one in the same string and position of one Hindi Sequencing Different position of one Hindi Sequencing Different Shoaib Malik Ko Daku Shoaib Malik Ko Daku Shoaib Malik Ko Daku President for the thing but different position Twitter Jahan Gaon Indian Visa to return how many bones and gorgeous hit solved valued by capital one and three cops for a capital also better return this that now let's you create a look at the approach To traverse through the To traverse through the To traverse through the string and intense pain on the characters and string and intense pain on the characters and does not matching matching liquid form does not matching matching liquid form 2018 that which will force 2018 that which will force vacancy are built to the vacancy are built to the frequency of frequency of phone number office secret string and second phone number office secret string and second frequency of service to the characters of frequency of service to the characters of the gas string number of times the gas string number of times the gas string number of times traversing the character of research in the middle and when both the tractors are different then will update the vs notes only to -do list subscribe intentionally not exhaustive width third front will update one to per seventh index North Point Will Move Forward 9 We North Point Will Move Forward 9 We North Point Will Move Forward 9 We Have Wanted Injection And In This Index Have Wanted Injection And In This Index Tractors And Very Beautiful Same Will Tractors And Very Beautiful Same Will Update Kar Bol Variable Update Kar Bol Variable 122 Close 122 Close That No These Values ​​Will Not Be Any That No These Values ​​Will Not Be Any Discrepancy Are They Will Only Be Amazed Discrepancy Are They Will Only Be Amazed Mehndi Very Sharp Tractor Adaptive Laker Mehndi Very Sharp Tractor Adaptive Laker Different Different Different a mouth and not the greatest sin boti the spring of difference they will update or frequency are o the cutter and secret is dros will update jatin tax and character add gas is vansh will update the first day of no value for a main If and different so will If and different so will If and different so will update se one drops of secret update se one drops of secret tomorrow swimming and growth index of first tomorrow swimming and growth index of first time and hear or tempered glass over phone number butar given brother number drop and given by that bill bramble id number off that person to wear blender valve number off Do that date is shine frequency reddy pregnancy are but testing lab technician minimum number removed particular updated 212 yesterday updated 212 yesterday morning morning addressed to formalized frequency proof the address but addressed to formalized frequency proof the address but packing minimum set up particular index packing minimum set up particular index live from one one day minimum is vansh scars live from one one day minimum is vansh scars begum one no begum one no begum one no With This Number Subscribe Now To Receive New Updates Reviews Nov 10 2013 12312 A 98 Point Is It Vivo Index Bodh Tractors Different Sunil Update This Corresponding Value Day t-20 Are A Gift This Point Activated Here With These Be Updated No Where Can Be Updated No Where Can Be Updated No Where Can Move Appointed to Held Nau Liters and Move Appointed to Held Nau Liters and Buddhi Strings Have Also Been Updated on That Novel The Move Ahead Buddhi Strings Have Also Been Updated on That Novel The Move Ahead Solitaire Bodhi Strings of Difference They Will Update The Second Index of the Secret Frequency Are with One Hand in Sikhon Cigarette Fast Index of S there was no will hurt oo S there was no will hurt oo S there was no will hurt oo kuch dar di category and different super will kuch dar di category and different super will update the third index of the update the third index of the secret here with one and the fort index secret here with one and the fort index of frequency are of gas of frequency are of gas that no know when they are atravarso dheere that no know when they are atravarso dheere ki bihar police answer indestructible in ki bihar police answer indestructible in Trending Person Calculator Sir Nikhar Jahan Trending Person Calculator Sir Nikhar Jahan Committed During This Too Frequency Committed During This Too Frequency Is Nobody Would See My Travels Him Is Nobody Would See My Travels Him Zinc Minimum Value From ODI And T20 Zinc Minimum Value From ODI And T20 India Will Look Like India Will Look Like A View Of Bihar In Dec09 Act Value A View Of Bihar In Dec09 Act Value In Bodhi Answer Is In Bodhi Answer Is 90 Sunil 802 Varsham No 90 Sunil 802 Varsham No 90 Sunil 802 Varsham No move to This Festival Test Case This Festival Test Case Number 2018 Number 2019 They Are Straight First Always Number 2018 Number 2019 They Are Straight First Always Giving False Evidence And The Bulls Giving False Evidence And The Bulls And Guest House Number Of The And Guest House Number Of The Question And Will Declare That To Question And Will Declare That To Frequency Vectors New Delhi This Hand Idli Hour Having Elements By Karne Limit Bigg Boss This This is the element of the following 4 This is the element of the following 4 This is the element of the following 4 users liked this 1807 maximum number that users liked this 1807 maximum number that David Villa David Villa a great way to lotus eyes and you will release a great way to lotus eyes and you will release element 102 will create another factor which element 102 will create another factor which aims to the country of aims to the country of a sequence of getting a string in will be named a sequence of getting a string in will be named das das das and zero know its worst drinks for i will check first name the character of i will check first name the character of buddhist ring get secret one to one this secret off side ww2 gas of i means cattle and also they will be available on that in this chapter note school will update were Frequency vector with this acigarette was hidden - 0 a plus b plus b plus c katai is the correct and were converted into in in tears for watching the best and similarly e paul will update chief guest Books Books Books free hindi novels to calculate the free hindi novels to calculate the a knock setting dikhao us bhi have to dead over a knock setting dikhao us bhi have to dead over and frequency address that and frequency address that 1005 plus hello 1005 plus hello viewers add the minimum of minimum viewers add the minimum of minimum balance a particular index indore possible balance a particular index indore possible minimum of minimum of and ashok bhai comedy jio 500 and ashok bhai comedy jio 500 ab aadhe bhi hai that mistake ab aadhe bhi hai that mistake ab aadhe bhi hai that mistake were return of string will declare string answer were return of string will declare string answer equal to two with empty string a answer plus equal to will convert per equal to two with empty string a answer plus equal to will convert per yes bol yes sir plus two equal to he yes bol yes sir plus two equal to he that no will convert r ka ujjwal that no will convert r ka ujjwal that no will convert r ka ujjwal Like share and subscribe
2024-03-22 14:36:24
299
https://i.ytimg.com/vi/h…axresdefault.jpg
Bulls And Cows Leetcode | Leetcode 299 | Leetcode September Challenge
yUE4xl45jJ8
all right guys now we are going to do the next problem with lead code problem the next problem with lead code problem 51st and queens the N Queens puzzle is a 51st and queens the N Queens puzzle is a problem of placing and queens on an any problem of placing and queens on an any length s Porter says no to Queens attack length s Porter says no to Queens attack each other ok when an integer and each other ok when an integer and returns return all the solution to the N returns return all the solution to the N Queens prappas it Queens prappas it each solution contains a distinct whole each solution contains a distinct whole configuration of N Queens placement best configuration of N Queens placement best cook you and dot both and if I indicate cook you and dot both and if I indicate a queen and an empty space respectively a queen and an empty space respectively so this is how we're going to do this so this is how we're going to do this but we are going to have create a but we are going to have create a variable a result variable which we are variable a result variable which we are going to return at and off the algorithm okay so let's define this as the analyst so once we're done with this we're going to have character la T you have n we are going to use arrays dot fill to fill see with pot once this is done we will create a thing Eddie it s new string array I don't after hi I have another area size M I will call the fill function again and I'm going to have a restart copy of C n times then string dot value value function convert stuff into Train yep can you character in a string once we're done with this we have a good for us a prototype grid now I'm going to create slacks shell boolean column sag equal to Nu equal to do them array of size because I haven't homes I'm going to the flag but diagonals 45-degree diagonals and I lost 135 degree line because I have how much two and minus one diagonals 45-degree angles and 2 into n minus 1 1 45-degree diagonals and as we know that you know Queen it it it goes diagonally and it goes by column and rows so then I'm going to have a helper function to it I'm going to pass my sister my thing my bags I have three of and and I zero this was row so quickly and and I zero this was row so quickly you know I mean kick I'm gonna increment you know I mean kick I'm gonna increment my row and iterate through columns and my row and iterate through columns and it's like that then wide helper function it's like that then wide helper function which going to switch is going to take my return they give my string s boolean flag oh my god I didn't and I forgot the [Music] okay I have these please then I'm going to have an increase row and integer and the F Rho equal to equal to M by n minus 1 rows from 0 of course so this would mean that you have covered all the rows so I will just add new array list then I'm going to have arrays dot as see list function as my SLA I'm going to turn it into this and store it in my laser something needs yes district column equal to 0 column smaller than M column plus size nothing out of the ordinary R then an if condition that F column flag for the column is equal to equal to let's speaking about it not I want this to be not diagnose flag or column Plus really not diagnose flag or column Plus really just think about it you know just think about it you know collect through is the is the 45-degree collect through is the is the 45-degree angle yeah number and similarly not I'm angle yeah number and similarly not I'm sorry sorry so not fat n minus 1 minus Rho plus so not fat n minus 1 minus Rho plus column because you know great you can column because you know great you can you can visualize this black inner of you can visualize this black inner of one forty five degree at is mirror image one forty five degree at is mirror image of what a forty five-degree crossed you of what a forty five-degree crossed you know a certain column so basically know a certain column so basically column doesn't changes row if I subtract column doesn't changes row if I subtract true from n minus 1 that will give me true from n minus 1 that will give me the opposite Tina and after that will the opposite Tina and after that will create a mirror image of the 45 degree create a mirror image of the 45 degree air diagonals so let's go ahead if all air diagonals so let's go ahead if all of these are false you can what I'm of these are false you can what I'm going to do is I'm going through a sign going to do is I'm going through a sign true to the DS going to get a clue no no I now I'm going to have a character array C is equal to new cache of size n are rather let's be a bit clever about it let's take as column two character Eric the CEC we have to yeah okay once I have this let's go to as row and I'll give a queen to it Queen to pit I'm sorry C so C zeros then I'm going to you string okay wonderful then let's copy the help function from above and let me close this one then just copy the code from over and say word that the flag one it's my recursion my function called eight returns because I have to check for the other things as well I just cannot really use you know the whatever changes out then I have to reward back and check for other organizations so this looks good let's try this 14th I have a bracket problem at 14th yeah was okay let's look now see let's try now oh I'm sorry guys okay let's try now oh I'm sorry guys okay it's working let's submit it okay thanks it's working let's submit it okay thanks for your time
2024-03-20 10:02:26
51
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode 51 N Queens
am6xH8Wlwk0
today's problem is very simple we are given two strings one is a we are given two strings one is a smaller string smaller string or it can be larger and another string or it can be larger and another string is the bigger string and is the bigger string and we have to check whether s is a we have to check whether s is a subsequence of t subsequence of t or not so subsequence is uh or not so subsequence is uh means that you pick some characters from means that you pick some characters from a sentence a sentence from a string or maintaining their order from a string or maintaining their order for example i pick for example i pick h then i pick h then i pick g and then i pick let's say c g and then i pick let's say c so you will see that h occurs first then so you will see that h occurs first then g then c g then c and in this string from where we have and in this string from where we have picked it there also they occur in the picked it there also they occur in the same order same order that is h occurs first then g then that is h occurs first then g then c then h g c will be a subsequence of c then h g c will be a subsequence of this string but on the other hand if we this string but on the other hand if we write write it like ghc although the characters are it like ghc although the characters are same same we see that very g g is here we see that very g g is here then after this we look for h then after this we look for h and we do not find it although it's and we do not find it although it's before before so it's occurring in different order in so it's occurring in different order in the this string the this string but here it's in different order so this but here it's in different order so this is not a substring is not a substring subsequence of this and this is a subsequence of this and this is a subsequence of subsequence of this string so here also you have to this string so here also you have to check whether the given check whether the given string s is a subsequence of t or not string s is a subsequence of t or not so for this example if we see that is a so for this example if we see that is a present or not first of all these present or not first of all these characters should be present if the characters should be present if the character itself is not present character itself is not present there is no notion of ordering we there is no notion of ordering we straight away turn false straight away turn false so we check if a is present or not we so we check if a is present or not we see that yes see that yes a is present here there can be multiple a is present here there can be multiple instances of a as well instances of a as well so we see that one character i have so we see that one character i have found next we look for b found next we look for b so we pick characters in order in s so we pick characters in order in s and we look in t so wherever we found and we look in t so wherever we found the first character we look for the next the first character we look for the next character character there onwards so we found a in the there onwards so we found a in the beginning itself beginning itself so we look from second character for so we look from second character for b and we found a b here b and we found a b here so we move to the next character which so we move to the next character which is d and try to find it and we found it is d and try to find it and we found it here here and now there are no characters left and now there are no characters left here so we say that here so we say that yes return true yes return true but if this is not a substring let's say but if this is not a substring let's say we have some other character here let's we have some other character here let's say a b say a b x then we see that a we found here x then we see that a we found here this is s this is t then we look for this is s this is t then we look for next character b next character b we found here then we look here onwards we found here then we look here onwards for x for x we go here we don't find don't find we go here we don't find don't find don't find we reach the end of t don't find we reach the end of t and this we did not find so we return and this we did not find so we return false a c b a c b so we see if a is present yes it's here so we see if a is present yes it's here then we look for c we continue continue then we look for c we continue continue we found c here and then we look for b but we see that there is no character left so we return so the algorithm is very simple if first so the algorithm is very simple if first characters match characters match each sub let's say this is the function each sub let's say this is the function and we are and we are calling it on smt so if calling it on smt so if s0 is same as s0 is same as t0 that is first character match t0 that is first character match then our job is reduced just look for then our job is reduced just look for this substring this substring in this substring whether this in this substring whether this subsequence is present in this or not subsequence is present in this or not so return each sub s one onwards so this will denote this slice will denote first to last character and else that is first characters are else that is first characters are different so we will not different so we will not advance in s since we have to find all advance in s since we have to find all the characters of the characters of this s so we did not find a here this s so we did not find a here so what we are left with we will find so what we are left with we will find this entire s this entire s in this part from first to last in this part from first to last character character so in this case we will return each sub so in this case we will return each sub s complete s and t s complete s and t one till end and one till end and uh if so here we are using recursion uh if so here we are using recursion this is the main function and we are this is the main function and we are recursively calling this function recursively calling this function on a smaller substring of s and t on a smaller substring of s and t and finally when should we return if s and finally when should we return if s is non-empty and t is non-empty and t is empty so if s is empty that means we is empty so if s is empty that means we have searched for all the characters of have searched for all the characters of s and we move to next character only s and we move to next character only when when we found the previous character in the we found the previous character in the same order same order that we followed so if we found b here that we followed so if we found b here next character we look from here onwards next character we look from here onwards so we never do so we never do second scan of this array so if second scan of this array so if at any point of time if in this at any point of time if in this recursive call if recursive call if s dot length is 0 that is all characters s dot length is 0 that is all characters are found are found or maybe that the input was itself zero or maybe that the input was itself zero then we have nothing to find then we have nothing to find then return true and if s dot length is not zero then we will check if t dot length is zero that is some characters are still not formed but we have reached the end of t so we return false in this case and after these cases just check if the first character of the substring of of the substrings match then our job is reduced one character less in each of these if they are different then just look for this s in the substring from one to last of t so that is very simple so let us see the time complexity here we are doing one scan of s and t so time complexity would be order of n whichever is larger or n plus m and we are not storing anything in some extra space so space is order one time is order n linear n plus m and space is order one so let's write this simple code in c so if this is subsequence a smaller so if this is subsequence a smaller string is empty that means all string is empty that means all characters are found characters are found then we return true if that is not the then we return true if that is not the case we will go to next line case we will go to next line if it's 0 this function will not execute if it's 0 this function will not execute further but if it goes beyond this that further but if it goes beyond this that means means s is not empty then if t is empty t dot length is zero then return false and if return if first characters are not same then return and this will be the substring of t and this will be the substring of t from one to last and let's see from one to last and let's see it works so let's submit it works so let's submit [Music] and the solution is accepted [Music] and we are here around 63 so you can try some iterative approach maybe that should give some better timing here maybe recursion is causing some slowness but still it's not that bad time complexity is often only and now let's write the same and this solution is also accepted and here also we are around fifty percent mark so this p could be mainly due to some iterative approaches where you can have two pointers one will be pointing to the current character we are trying to search in the character that we are trying to find so that will be in s so if we are trying to find a that will be pointing to a and the second will be the current position in t so if we found here then we will advance it and if it both then we will look for b so this pointer will remain stationary here the first one and the second will keep advancing and here it will find b then we will advance this by one this by 1 and then we will find c in the end and then we will check that if s has reached the end or not then we will return true so you can try this this logic would be very similar to this and that should give a better result and the python solution is also accepted and the python solution is also accepted now let's try that two pointer approach now let's try that two pointer approach if we can do it better return true and then or let's call it a s for indexing s or let's call it a s for indexing s and idxt so we will look for all the characters d d if t i if t i is equal to uh is equal to uh this s idx is pointing to the character this s idx is pointing to the character which we are searching which we are searching so s s i d x so s s i d x then what we will do we have to advance then what we will do we have to advance this pointer in this pointer in s so s i d s so s i d x plus plus and this i x plus plus and this i will anyway advance and will anyway advance and if s i dx if s i dx is equal to s dot length is equal to s dot length so the last index will be s dot length so the last index will be s dot length minus 1 so if it's minus 1 so if it's s dot length that means we have searched s dot length that means we have searched all the all the characters of s so we return characters of s so we return true so that we don't continue our true so that we don't continue our search even if we have reached the end search even if we have reached the end of s of s and we don't get an out of bound and we don't get an out of bound exception here exception here since this would be less than s of since this would be less than s of length length so we return true but if that is not the so we return true but if that is not the case and we have reached the end of case and we have reached the end of this loop then we will see this loop then we will see we have reached the end of this bigger we have reached the end of this bigger string but have we reached the end of string but have we reached the end of this smaller string or not so this smaller string or not so return s i dx return s i dx should be equal to s naught length if should be equal to s naught length if it's less than that that means we did it's less than that that means we did not get a chance to not get a chance to search all the characters of s and we search all the characters of s and we reach the end reach the end so let's see if this works uh okay this works let's submit if it passes all the test cases or not and this solution is accepted and you see that our solution is right here it was earlier here around 63 percent now it's 85.4 percent and it's just a matter of time that you try a few times it can reach this peak also that is 99 so you see that we get a much faster running time in the case of this iterative solution i think we did not use this one so we can get rid of this and this would work so we needed just one pointer other pointer is this i itself let's and we are still here these are the top and we are still here these are the top two bars two bars but i believe that we can jump to this but i believe that we can jump to this without too much of effort without too much of effort so now let's try our code the same logic so now let's try our code the same logic in java and python also and see in java and python also and see if there is any improvement there also if there is any improvement there also or not i think this loop this check may also not be required since we are already taking care of this and everything else is fine d dot and this solution is also accepted and and this solution is also accepted and now we have now we have reached our almost there we are almost reached our almost there we are almost there we are there we are better than 93 of the submissions better than 93 of the submissions so this iterative approach is working so this iterative approach is working better in not just c plus list but java better in not just c plus list but java as well as well finally let's for the sake of finally let's for the sake of completeness completeness do this in python 3 as well and this is also accepted and here also and this is also accepted and here also we are right we are right in the towards the top of the region in the towards the top of the region that is around 93 that is around 93 so i hope you understood both of the so i hope you understood both of the approaches recursive as well as approaches recursive as well as iterative iterative the logic is same in both the cases we the logic is same in both the cases we make make one scan of both of these and if we one scan of both of these and if we reach reach t at the end but we have not reached the t at the end but we have not reached the end of s end of s that means we have not found all the that means we have not found all the characters of s characters of s in the order they are in s so we return in the order they are in s so we return false in that case false in that case now let me try one more thing this check now let me try one more thing this check was redundant was redundant let's see if it improves anything and here we are we are at the top hundred percent so we have reached our destination finally with uh uh improving our solutions slowly and slowly so that check was not required and removing that helped us jump from here to here so i hope you liked both the approaches feel free to share your valuable
2024-03-24 12:07:31
392
https://i.ytimg.com/vi/a…axresdefault.jpg
Is Subsequence | LeetCode 392 | C++, Java, Python | Recursive and Iterative | 100% | Watch complete
tznrea_Skqg
Hello everyone, my name is Adarsh ​​Mishra, you are watching this Dress to the Nation, today you are watching this Dress to the Nation, today we are going to talk about the problem named Get Perfect Number. The we are going to talk about the problem named Get Perfect Number. The problem problem statement is here divided into three lines, statement is here divided into three lines, so before reading it, I so before reading it, I so before reading it, I tell you why this development is made in the video because this problem has to be created, it parses the list and if it is not submitted then there comes the time limit exceeded hair, it means that the To To To find the solution to calculate 11 buttons, find the solution to calculate 11 buttons, it is taking more time for input, then it is taking more time for input, then how to reduce that time. Time how to reduce that time. Time complexity has come here. So, we have complexity has come here. So, we have divided this problem by 30. I will divided this problem by 30. I will tell you three solutions. tell you three solutions. tell you three solutions. one another in terms of time complexity, so it is important to understand it well. Click here to see the perfect number, what is our pack number, this is the Subscribe to this link. Subscribe to this link. Teacher's Day and Teacher's Day and effectively now here quantum effectively now here quantum means that my number is and the number can be means that my number is and the number can be divided into 6, 2030, here it means that when you subscribe to someone, if that number is getting divided, let's see whether it can be divided by any one person. And subscribe subscribe be equal, at this time quits positive be equal, at this time quits positive individuals, it means all the individuals, it means all the reverses of that which you are seeing in front of you, reverses of that which you are seeing in front of you, when we do all this, you will get angry, when we do all this, you will get angry, if who is our ex's then if who is our ex's then what will be our ex's perfect. what will be our ex's perfect. what will be our ex's perfect. will be one more point given here that excluding number 80 we should not take that number if we have exclusives then we will not consider six so this is how many number children we have one plus two plus three layer three division quickly so do, if not subscribe, I have given the input number, name, use it, 28th gram number is 28, so if you solve first, then who divides the to-do, then tell me how 128th is Superhit someone validates Vansh is Superhit someone validates Vansh is not able to divide 21 or three, this channel is subscribed, okay then this problem is subscribed. That salt is coming to the fans of accidents, how many meters are you, how many numbers does it divide in between, on whatever number we have is a number, Before doing this, we are in the Before doing this, we are in the list of Hello Compiler and we have given power tunes of time to solve a test case of the tank, so by doing this, given power tunes of time to solve a test case of the tank, so by doing this, their health gets time and their health gets time and 2018 in this we are not 2018 in this we are not 2018 in this we are not need it need it in such a time, so in such a time, so I know it I know it is okay, now you tell me, if I mean, you ca n't subscribe for the news of the screen, if you like it, then you can put it on the Any can I call you Any can I call you Any can I call you this in the front so the this in the front so the power of activity against anti tank sees a maximum railway power of activity against anti tank sees a maximum railway station good 2018 if it is in it then station good 2018 if it is in it then it will not work because in the list tank power tune of time my code is my one test If you don't want to let me come to Delhi If you don't want to let me come to Delhi If you don't want to let me come to Delhi then I will have to do it at least. So then I will have to do it at least. So from here I understood a little bit that we from here I understood a little bit that we can first see a solution, okay then before doing this let's find a solution, so first of all let me tell you that the way. do the question of quitting, are we able to divide it with water or not, but yes brother, he can do two, three, So I am four So I am four So I am four de Villiers, okay in my mind, from the de Villiers, okay in my mind, from the first to the number, I am able to first to the number, I am able to divide all these numbers, so after divide all these numbers, so after adding them here, we will take all these if it if it doesn't If you do this quickly then this house is happening here, right, you are going from one to the end, okay, you are finding out which number is able to divide I and I, so here you will put a loop, okay How much time will it take, that time How much time will it take, that time How much time will it take, that time and time is pathetic here, okay and time is pathetic here, okay if if 10388 time not not come here then please come here then please subscribe because subscribe because I can do it here, I can do it here, If there is a problem then If there is a problem then If there is a problem then subscribe if others have understood, subscribe if others have understood, then this function was given to you, then this function was given to you, here you were given a number, so I made here you were given a number, so I made two functions, one side was extend sum and the two functions, one side was extend sum and the other was check perfect, okay, that means other was check perfect, okay, that means whatever number is used. whatever number is used. whatever number is used. correct and whatever answer is true or first of all first of all tell me that here I will check again that I have subscribed to this and now whatever is there has gone above it so that Have Have Have you understood this line? Okay, let's you understood this line? Okay, let's move on to the tractor time. If I am move on to the tractor time. If I am inside the tractor, then here inside the tractor, then here we have all the numbers that have made them from one yellow to we have all the numbers that have made them from one yellow to the end. Okay, mean 12345. If If If we are appointed then click on continue here, I pick up this number, I like it, if pick up this number, I like it, if he is able to divide my number, completely at he is able to divide my number, completely at this time, the mode means our ghagra, subscribe to our channel, like and subscribe Let's subscribe till 65. Subscribe button will be perfect. With subscribe, the workers in the restaurant at Rajghat today have understood this problem. Well, now this is the time complexity of it, so where is the work being done? How many times are people running? People are How many times are people running? People are How many times are people running? People are running and minus one time slow. This is how to running and minus one time slow. This is how to solve the problem in Vivo. solve the problem in Vivo. I have seen that the time limit has been exceeded. I have told you I have seen that the time limit has been exceeded. I have told you and if you get time, you have to fold it. In such a situation, you will answer this. you will answer this. you will answer this. we do it, so if we we do it, so if we subscribe, then by extracting these and subscribing, it will be made in two ways, two will come, the fiber will go, the number will go like this, de Villiers and here we will show you, read Chikara, do it well with all these numbers and here if the Had the formation here been quiet, Had the formation here been quiet, Had the formation here been quiet, this list would have become bigger. I am checking. this list would have become bigger. I am checking. Okay, so now the main problem we are facing is that Okay, so now the main problem we are facing is that in all these options, now tell us which in all these options, now tell us which numbers can be removed. If we are not able to do so then We have brought We have brought We have brought butter, we will come and check it till 135, butter, we will come and check it till 135, set the number 19 in the filling, so that we can actually set the number 19 in the filling, so that we can actually divide, we will be able to do 600, divide, we will be able to do 600, we already know the tan device, so the we already know the tan device, so the logic came from here that yes friend, now I am one. logic came from here that yes friend, now I am one. Why are we doing from to the end? We are going to Why are we doing from to the end? We are going to enter by taking this lineage, from one to enter by taking this lineage, from one to nearby, the admin method of vitamin browser, from nearby, the admin method of vitamin browser, from which of us, why are we worried about the number of admin, which of us, why are we worried about the number of admin, we have taken the check from oven to number we have taken the check from oven to number two, then this will increase our two, then this will increase our For something good, it means that it is time for them, For something good, it means that it is time for them, so what will we do now, so what will we do now, this fifth message of 12345, pick out whatever numbers you can in the white part and this fifth message of 12345, pick out whatever numbers you can in the white part and keep them, it will be a little keep them, it will be a little easier, so do that thing here, yes, easier, so do that thing here, yes, absolutely. absolutely. absolutely. changes were made in this line here, which I was doing earlier but the value is hundred, okay, so I was running from one to nine and checking But now But now But now I know that the maximum number which I know that the maximum number which Ragnarok will not be able to develop its skill is 5051, Ragnarok will not be able to develop its skill is 5051, then why will it not be able to do so, now what should then why will it not be able to do so, now what should I do, I have reduced it a bit because I am not a Ranger, I do, I have reduced it a bit because I am not a Ranger, check from 1st to June 15th, brother, check from 1st to June 15th, brother, tell me right, this thing tell me right, this thing tell me right, this thing do, why from number one to number two means fifty plus 151 so that he clicks and subscribes to my channel, I have to write, so now I have I have to write, so now I have actually made some improvement in time, actually made some improvement in time, if if not, it If it is from one to If it is from one to If it is from one to 1008, then you should find out by clicking on the number, it will 1008, then you should find out by clicking on the number, it will take more time, it is okay, if you are take more time, it is okay, if you are going half the distance, it will take less time for going half the distance, it will take less time for you, hence if you apply this process, you, hence if you apply this process, even then the time limit in your board will be even then the time limit in your board will be exceeded. exceeded. exceeded. point till the end, even then I have deleted the message to the time, so marriage 1.21 What is a little photo constant, even if it goes, there is Solving Solving Solving is still not a good approach. Now the question is still not a good approach. Now the question is whether you have done a good approach. So this was the is whether you have done a good approach. So this was the second approach. Now I will tell you second approach. Now I will tell you how to do more additions. I thought a little that if it how to do more additions. I thought a little that if it is on that side, but if it does not come, then it does not is on that side, but if it does not come, then it does not matter. matter. matter. see what other way can be to fold it, as per your suggestion, our value will be fifty, so basically we will make it 11. According to the first approach, we will Then we will Then we will Then we will look at it carefully, it will not come look at it carefully, it will not come and shift will come. Understand in all these numbers, and shift will come. Understand in all these numbers, in all these numbers, we have to find out those numbers in all these numbers, we have to find out those numbers which can be divided by my invalid. which can be divided by my invalid. Okay and understand. Now I ask you to pick Okay and understand. Now I ask you to pick them up and check them. them up and check them. them up and check them. division that you will say because you know that the soil which is there is divided, it gets divided. How do you know, it is 15831, 15831, more more meaning it meaning it gets divided, so you can see here. gets divided, so you can see here. Here Here you have forgotten, have you forgotten that 15th and 1st are you have forgotten, have you forgotten that 15th and 1st are also there, brother, it is difficult to divide, also there, brother, it is difficult to divide, yes, it means that it is good to see here, now tell me, will you do it? Other subscribe to divide in 2002, Look how easy it is becoming, actually Look how easy it is becoming, actually Look how easy it is becoming, actually see there is one number whereas I see the work of two numbers, see see there is one number whereas I see the work of two numbers, see here that the value of our loop will be here that the value of our loop will be found, it will become found, it will become three, then brother no, he is not able to do three medicines, he is three, then brother no, he is not able to do three medicines, he is not able to do four. not able to do four. not able to do four. how would I have done it, how would you know, I will show you a holiday in five divides, 50 feet is fine, so I got 5 feet, I got it, my brother, I picked up five and also picked up the pan, I did not write this, the goods are written here, This is going further, This is going further, This is going further, tan has also come from here, okay, we took out the button of 600 first brother, wisdom is fine, 1112 30 subscribe, definitely subscribe number, so now Sanjay, actually till where should I check, I have done the loop only from one to I ran mine and I found I ran mine and I found I ran mine and I found out the answer for the deputy, out the answer for the deputy, what will we do before that, it is running till 2030, it was what will we do before that, it is running till 2030, it was looped 25 times, I am looped 25 times, I am scared of using cargo planes in the first approach, scared of using cargo planes in the first approach, okay, so now I know from the second one. To separate the Sangh only till five floors, you should understand that this is our giver, training is fine, I will write you and I am and Jaipur to add one of my numbers if I like that also and here So mine becomes, I am getting a So mine becomes, I am getting a So mine becomes, I am getting a little understanding in between, maybe now we can see this, Meghnad, okay, so now we are checking this potato in this, how to get the full subscribe here, if you Okay, so if we do that, then I will take Okay, so if we do that, then I will take what is the question and let us also keep this question what is the question and let us also keep this question with you beforehand, it will become with you beforehand, it will become easier for you. Okay, you must be understanding a little bit easier for you. Okay, you must be understanding a little bit and maybe in future. and maybe in future. and maybe in future. we tell you then it will become a little more clear what is happening here, whatever we do here, from this we have understood how far we have run the loop, look at your loop, now what you have to do, you know that whenever So, I have a number. So, I have a number. So, I have a number. Come, people who are running and together Come, people who are running and together can give us the question time. can give us the question time. Okay mind, so there is one more time and we will take it. We will Okay mind, so there is one more time and we will take it. We will take it and these two numbers will be able to take it and these two numbers will be able to completely divide our completely divide our If you keep to If you keep to If you keep to subscribe, subscribe, then here are two things that will come then here are two things that will come in today's news activist, one will in today's news activist, one will come, two will come, tan will come, front will come, come, two will come, tan will come, front will come, Africa will come, all these will come, which number should we Africa will come, all these will come, which number should we not take, we should not take the person, which person should we not take, we should not take the person, which person should we remove f9 from? remove f9 from? remove f9 from? when we all are trying to find out the value, take out the question, take out these two and keep them, then then then what do we have to do with all these and finally - 50 Paytm App Officer Paytm App Officer Paytm App Officer whether it is equal to the one I have, if it is then our 50 is the perfect number, it is not opposite, it is simple, now here also something is given that it is Malwa number, it is correct, its very If you If you If you find, then if my is find, then if my is being divided by the number, it means can be divided by the number, Cash Withdrawal number Cash Withdrawal number and and this which we have appointed here, okay, okay, okay, okay, what can be the maximum value of these two, what can be the maximum value of these two, that this relation that this relation that this relation if I write here the route number * is the route number then it will also decide. Under the route number can be written in your comment, so this is my idea, this is what my nitin22 was questioning, so Number should be given Number should be given Number should be given here, you must have understood here, you must have understood now if you read the whole thing then you will now if you read the whole thing then you will understand something else better. understand something else better. How did the route number come here? I am just telling you How did the route number come here? I am just telling you that what are you doing instead of here, that what are you doing instead of here, you are driving. you are driving. you are driving. Understanding the above, we raise the High Court and because we raise it, you are right, then how far should the Commission go? If this happens, then because they do do do do do something, they If this happens, then because they do do do do do something, they should subscribe. Okay, here is the house, brother, please forward it to a list, we will make it real this time, okay, we will run this loop, assume that the value of my name here is 50, okay, understand, from There are There are two ways to do the square root of 50, the first is from the importance UID and will give time, the square root of 90 should be simple and on the other hand, it because we have taken it from here because we have taken it from here so so so from this and here and the power that someone has removed, if the answer is coming and it comes to the rotating point, then it has made changes in these things and plus one that we can make There will be under There will be under There will be under root number here which will have to be stirred root number here which will have to be stirred because as our break because as our break must be must be subscribed, so I have posted it here because as long as it posted it here because as long as it continues, now we understand that the continues, now we understand that the appointments of this whole thing means till subscribe appointments of this whole thing means till subscribe to our channel. do this then I will tell you for free that do this then I will tell you for free that it has come here, look it has been added, you have understood, it has come here, look it has been added, you have understood, after this what else do we have to after this what else do we have to check, the value will come, if we know one number check, the value will come, if we know one number then we will have to know the second number, let then we will have to know the second number, let us solve the question. us solve the question. us solve the question. question comes, 50 comes, in this case we are close to us, how will it work, you check what I * I, this note is like this, does 121 mean digits are not equal to 50, it means that you can If you turn on the number then If you turn on the number then If you turn on the number then why does it side side that the value of I is Bittu, then the question will be that the value of I is Bittu, then the question will be how much, the question will come, if the purchase did not understand how much, the question will come, if the purchase did not understand that it is two, then we will keep breaking down, that it is two, then we will keep breaking down, you will add time. you will add time. you will add time. notification? Not subscribe, we will take out the question and put it here. Okay, why are you do it do it and and after this like definitely subscribe here. Now subscribe school. If there was a 2.5 feet person then I would have come even at 10:00. Joined here ok what is happening now this war is over how many years have passed the code will not run on six air will increase 797 ok will the loop run or will I fit in 7010 comes no and then IS will People are angry with me People are angry with me People are angry with me because because my people are running from A to Z. Okay, so my people are running from A to Z. Okay, so how much value did we get here, so we how much value did we get here, so we got Vansh got Vansh with 52255, so one where you can help us with these with 52255, so one where you can help us with these more here. more here. more here. war war subscribe subscribe then I will do it call my number confused till how much and it has come to the fore now Lalu's salty value is my 25. If you will understand in this case then Why is the line written here Why is the line written here Why is the line written here because it is a very important because it is a very important line I * is not equal to a lover, line I * is not equal to a lover, you will have children, okay, from here onwards, subscribe to the number, subscribe, subscribe, if it comes, then the subscribe, if it comes, then the first number one is first number one is now * * * now * * * now * * * Subscribe to my channel. Useful to that tweet. 25201 property white Useful to that tweet. 25201 property white hota hai nahi hoga nahi hota hai. Have you hota hai nahi hoga nahi hota hai. Have you not subscribed? Is it seen doing the 25th family? If it comes, then we will take it all and keep the face If it has come, then you have to keep that If it has come, then you have to keep that If it has come, then you have to keep that one leg is found five, good and because one leg is found five, good and because why not get five in this case 125 why not get five in this case 125 in a completely different object, again five should be kept ready. in a completely different object, again five should be kept ready. You think what are the divisions of 25, You think what are the divisions of 25, this is this is 25 and 25 25 and 25 are from and if are from and if are from and if we were applying then 125 will come, after explaining first the bangles will come, next four-five and five both are necessary because we can leave the question but when should we not It was It was It was definitely felt here after getting the number that we definitely felt here after getting the number that we found that 5 minutes have come here from this line. found that 5 minutes have come here from this line. Okay, now do we Okay, now do we need to add five by 5. It is not needed in our time. need to add five by 5. It is not needed in our time. To stop this, the line has become To stop this, the line has become more conditioned on the force. more conditioned on the force. more conditioned on the force. we have added the question 'Have you ever added it' which was five, so it means that we have removed it by subscribing to 125 and 500. AP, this was important. You must have AP, this was important. You must have understood the use of this line now. understood the use of this line now. Okay, so 125 these days. Okay, so 125 these days. Okay, so 125 these days. got here, now in this we have to like and share the thing after removing which one, we are checking the perfect number, okay then it will come five plus one means 6 is right, okay so this is understood. right, okay so this is understood. right, okay so this is understood. here and stayed here, subscribed to my channel, to not have to subscribe from, this is very not have to subscribe from, this is very important, if you have these questions, important, if you have these questions, then subscribe 5,000 whereas this is a 5,000 whereas this is a 5,000 whereas this is a cash withdrawal, they have to take it only once but cash withdrawal, they have to take it only once but if you put this I here and if you put this I here and simply add this time and abuse it simply add this time and abuse it that at the time we are adding that at the time we are adding this number on or subscribe because These people are appointed on this number 9th May Complexity will be done Vivo SQRT of Nam Vijay What is the time of his career that Bigg Boss The quality of the What is the time of his career that Bigg Boss The quality of the city is constant because we have added it to some list so here can be anything.
2024-03-22 16:07:31
507
https://i.ytimg.com/vi_w…xresdefault.webp
Perfect Number | Leetcode Python Solution | Python
t9pj1Ail2z4
in this video we're going to take a look at a legal problem called at a legal problem called clone graph so given a reference of a clone graph so given a reference of a node that is connected node that is connected undirected graph so undirected graph undirected graph so undirected graph basically means that if node a basically means that if node a is connected to node b that means that is connected to node b that means that no b is also connected to no a no b is also connected to no a right and then we want to return a deep right and then we want to return a deep copy clone of the graph copy clone of the graph so a deep copy basically means that we so a deep copy basically means that we want to create it want to create it we want to create a new brand new um we want to create a new brand new um graph graph in the memory instead of pointing to the in the memory instead of pointing to the the same memory location the same memory location so each node in the graph contains a so each node in the graph contains a value int value int and a list of list node of its neighbors and a list of list node of its neighbors so we want so we want so we have a node like this right has a so we have a node like this right has a value and all the value and all the neighbor node is connected to this neighbor node is connected to this current node and um current node and um here the test case form and the test here the test case form and the test case in this case is going to be case in this case is going to be adjacency list adjacency list and basically you can see here this is and basically you can see here this is the original graph and when we clone it the original graph and when we clone it right once we clone it it right once we clone it it will look exactly like the original will look exactly like the original graph but we're allocating a new graph but we're allocating a new space in the memory right we're creating space in the memory right we're creating a brand new graph in memory a brand new graph in memory so in this case this is how we basically so in this case this is how we basically deep copy right deep copy the graph so deep copy right deep copy the graph so here you can see here you can see we have given input right so in this we have given input right so in this case when we return it's going to be case when we return it's going to be exactly the same exactly the same and the different space in the memory of and the different space in the memory of course course so here you can see we have a another so here you can see we have a another example where we have only one node example where we have only one node and then we just basically you can see i and then we just basically you can see i know that input contains know that input contains one empty list the graph consists only one empty list the graph consists only one node with one node with value one so it does not have any value one so it does not have any neighbors right so in this case neighbors right so in this case uh we're just returning a clone version uh we're just returning a clone version of that of that and if it's null right if it's empty and if it's null right if it's empty graph we're just going to return graph we're just going to return empty graph we're going to return null empty graph we're going to return null um so yeah um so yeah so let's take a look at how we can solve so let's take a look at how we can solve this problem this problem so to solve this problem here you can so to solve this problem here you can see we have a graph right this graph see we have a graph right this graph has one two three four three so one is has one two three four three so one is connected two and four connected two and four and two is connected to one and three and two is connected to one and three and so on so the and so on so the um the goal uh the approach how we're um the goal uh the approach how we're going to solve the problem is going to solve the problem is we're going to use the breadth for we're going to use the breadth for search and we're going to use breakfast search and we're going to use breakfast search to traverse search to traverse level by level to clone the graph from level by level to clone the graph from there and basically there and basically um we're just going to use a cue right um we're just going to use a cue right because because to use a to traverse the graph using to use a to traverse the graph using breakfast search we're going to use a breakfast search we're going to use a queue queue and basically q is basically a first in and basically q is basically a first in first first out date structure so the first element out date structure so the first element in is also the first one in is also the first one out um when we remove element out um when we remove element off of the queue right so basically what off of the queue right so basically what we're going to do is we're just going to we're going to do is we're just going to start from this node right here this is start from this node right here this is going to be the head node going to be the head node right that's given which is no one and right that's given which is no one and then we're going to add then we're going to add this current node onto the queue right this current node onto the queue right so in this case we have one here on the so in this case we have one here on the cube cube um and then we in this case we're also um and then we in this case we're also going to have a hash table to keep track going to have a hash table to keep track of of all the visited visited nodes right so all the visited visited nodes right so in this case in this case we have currently visited that node we have currently visited that node because we're starting from this node because we're starting from this node so we're going to have no one right so we're going to have no one right that's the o node that's the o node this is the o node and the the value is this is the o node and the the value is on this case in this case is going to be on this case in this case is going to be the new node right the the new node right the um the new node that we created in our um the new node that we created in our memory memory so once we create that node we're just so once we create that node we're just going to save it onto the hash table going to save it onto the hash table right and then what we're going to do is right and then what we're going to do is we're just going to we're just going to traverse all the neighbor nodes that no traverse all the neighbor nodes that no one is connected to in this case one is connected to in this case two and four right so in this case what two and four right so in this case what we're going to do is we're going to we're going to do is we're going to create we're going to create we're going to um create that in our table right and um create that in our table right and we're going to we're going to the old node is going to be node 2 right the old node is going to be node 2 right this node right here the new node is this node right here the new node is going to be going to be a brand new node with the value of this a brand new node with the value of this node node so at the end it will look something so at the end it will look something like this right and then like this right and then what we're going to do is because it what we're going to do is because it doesn't really doesn't really exist in our hash table we also have to exist in our hash table we also have to add it onto add it onto our queue right so in this case q we our queue right so in this case q we have node two and no four that we have have node two and no four that we have to to um traverse at the um later right so in um traverse at the um later right so in this case we have no four node two and a this case we have no four node two and a four four on our table and what we have also have on our table and what we have also have to do is for each iteration right we to do is for each iteration right we also have to get our also have to get our new node which is the node one point to new node which is the node one point to those new node that we created in this those new node that we created in this case node two and no four because we case node two and no four because we know that know that the o node no one knows uh no one is the o node no one knows uh no one is connected to node2 and o4 connected to node2 and o4 and then what we do is we're just going and then what we do is we're just going to um remove the nest to um remove the nest the top element or actually say the the top element or actually say the first element in the the first element in the the um the prior uh the queue right so in um the prior uh the queue right so in this case this case um value node two once we remove um value node two once we remove that and then we're just going to that and then we're just going to traverse each and every single node traverse each and every single node that node two is connected to in this that node two is connected to in this case node one and node three case node one and node three and then what we're gonna do is we're and then what we're gonna do is we're just going to see if no one is there just going to see if no one is there right if it's if it's there in the table right if it's if it's there in the table then then we're just going to get new node in this we're just going to get new node in this case node 2 case node 2 point to that node and then if it if point to that node and then if it if it's not there for example node 3 we're it's not there for example node 3 we're going to do is we're just going to going to do is we're just going to create that create that this is going to be the node 4 node 3 this is going to be the node 4 node 3 which is going to point to this node which is going to point to this node right right and then this is going to be the new and then this is going to be the new node which is going to be a brand new node which is going to be a brand new node 3 right so node 3 right so a brand new know that with the value of a brand new know that with the value of 3. so what we're going to do is we're 3. so what we're going to do is we're going to get node 2 going to get node 2 point to this node okay then we're going point to this node okay then we're going to do to do is we're going to add is we're going to add three because three is not was not three because three is not was not um contained in the table so then we're um contained in the table so then we're gonna add it on to the gonna add it on to the prior uh the queue as well so now we prior uh the queue as well so now we have four and three right we have four and three right we we remove two and uh we remove we remove two and uh we remove two and then what we're going to have is two and then what we're going to have is four and three right four and three right so three wasn't there so we added three so three wasn't there so we added three onto q now we just onto q now we just remove four out of the q right remove four out of the q right so what we're going to do is we're just so what we're going to do is we're just going to um going to um traverse all the neighbor notes that no traverse all the neighbor notes that no 4 is connected to in this case 1 and 3. 4 is connected to in this case 1 and 3. we check to see if 1 is there one is we check to see if 1 is there one is there then we're just going to get no 4 there then we're just going to get no 4 is 0.2 is 0.2 no 1. and then we also check to see if no 1. and then we also check to see if no three is there no three is there no three is also there so we're going to no three is also there so we're going to um um get no fourth point to know three right get no fourth point to know three right so if it's not there we're just going to so if it's not there we're just going to um create that in our table and in our um create that in our table and in our memory memory and we also have to add it onto the to and we also have to add it onto the to the queue as well so the queue as well so then what we have to do because we then what we have to do because we didn't because those nodes are all didn't because those nodes are all contained in our contained in our tables then we don't have to add tables then we don't have to add anything onto our anything onto our cube right so now what we have to do is cube right so now what we have to do is we're just going to we're just going to um remove four right no four and then um remove four right no four and then we're just going to we're just going to move on to the next element in this case move on to the next element in this case note three so now note 3 is basically note three so now note 3 is basically um the next node we're just going to um the next node we're just going to traverse all the nodes and no 3 is traverse all the nodes and no 3 is connected to node 2 and o4 connected to node 2 and o4 and then basically we see if no node 2 and then basically we see if no node 2 exists exists no 2 exists then we're just going to get no 2 exists then we're just going to get node 2 pawn to the new node of node 2 pawn to the new node of node 2 and we also going to see if no 4 node 2 and we also going to see if no 4 exists in our table in this case we do exists in our table in this case we do right and we're going to get right and we're going to get no three point to the no force new node no three point to the no force new node in this case it's gonna be this node in this case it's gonna be this node right here right here right and then at the end it will look right and then at the end it will look something like this right and then our q something like this right and then our q is finished is finished right there's no element in the queue right there's no element in the queue and we can just return this top and we can just return this top the first element right here in this the first element right here in this case no one right case no one right so let's try to do this in code so how so let's try to do this in code so how can we do this in code can we do this in code our first step is to do perform our base our first step is to do perform our base case because case because here you can see there could be a here you can see there could be a situation where the current node is not situation where the current node is not right so right so if node is null then we can just return if node is null then we can just return null okay then we're going to do is we're just going to create our table right we're going to have a o node the old vertex um as the key and uh we're going to create a new node the new vertex as the value right so we're going to have hashmap is equal to right basically we're going to store the right basically we're going to store the the adjacent nodes onto the queue right then we're going to because we're currently like visited that node right the current node we visit that node we're going to start by we also have to add that onto our hash we also have to add that onto our hash map as well because we're starting at map as well because we're starting at this node this node so put okay so what we're going to do is we're going to perform now we're going to perform our bfs right so while so while the q is mt is equal to false right so if the queue is not empty what we're going to do is we're going to get the top or the first element off of the queue so it is equal to uh q that remove right this will remove the the top element off of the queue then we're going to do is we're just going to traverse all the neighbor nodes that the first node is connected to right so for each node let's call it current so current node so first dot neighbors right so in this case all the nodes that the first node is connected to then what we're going to do is we're just going to um have two scenarios right so one is that the current node is actually contained in the hash table where we visit that node the other situation is that we didn't visit a node right there's only those two cases but at the end what we have to do is we have to get the new node the clone version of this current node um add it to the uh the new node of the first the clone version of the first node so let's have this clone version so first clone right is equal to map.get first right this will give us the clone version of the node that we removed from the cube right then what we're going to do is we're going to see i'm going to have a current clone a clone version of the curve node so if the hash table right the hash table the hash map dot contains current node right because there only can be two situations where either we can either visit that node or we didn't visit a node let's say we visit a node right let's say we visit that node then what's now what's the current clone is going to equal to is going to equal to hashmap.getcurrent right this will give us the clone version of that node the current node and then if we didn't visit that node well what we're going to do what we're going to do is first we're going to add the current node onto the queue right so because we're going to traverse the node later then we're going to do is we're going to create a node so we're going to have currentclone right is equal to newnode it's going to equal to current.val and then what we're going to do is we're okay so then we're gonna do is we have okay so then we're gonna do is we have to get to get the um the first clone dot neighbors dot add the current clone right so this will give us this will add this current clone onto the list okay and then we're basically going to continuously do that until the queue is finished right the queue is done uh there's no elements in the queue then we're just going to return hashmap.git node right so we're returning the clone version of the given the input node right so let's try to run linked list cannot find this simple okay yeah so this is how we let's try to okay yeah so this is how we let's try to run submit run submit yeah so this is how we solve this yeah so this is how we solve this problem so the time complexity in this problem so the time complexity in this case case is going to be big o of v plus is going to be big o of v plus e right so v is going to be the vertex e right so v is going to be the vertex e is going to be the edges where the e is going to be the edges where the connections and um connections and um space complexity in this case is going space complexity in this case is going to be big o of v to be big o of v right so number of vertex that we were right so number of vertex that we were given given right
2024-03-21 11:56:41
133
https://i.ytimg.com/vi_w…xresdefault.webp
[Java] Leetcode 133. Clone Graph [Search #7]
dJhA1AVz1q0
hey hey everybody this is larry this is me going with q4 of the bi-weekly me going with q4 of the bi-weekly contest 50 contest 50 minimum number of operations to make minimum number of operations to make strings sorted so this is uh strings sorted so this is uh to be short you know uh hit the like to be short you know uh hit the like button to subscribe and join me on button to subscribe and join me on discord before i forget discord before i forget and yeah so this is just a very hard and yeah so this is just a very hard problem there's no way about it um problem there's no way about it um i recommend you watch me salvage live i recommend you watch me salvage live during the contest during the contest you know you can fast forward to skip you know you can fast forward to skip ahead or whatever but i'll have it after ahead or whatever but i'll have it after the explanation the explanation um and the way that i did it was and i um and the way that i did it was and i actually i think i left my code in there actually i think i left my code in there which is that i which is that i generated the brute force solution and generated the brute force solution and then try to figure out a pattern then try to figure out a pattern and and the the math here is not and and the the math here is not as you know interesting um because it's as you know interesting um because it's just about figuring out the pattern just about figuring out the pattern but the idea is that but the idea is that you know um you know key component about you know um you know key component about this problem is just trying to this problem is just trying to rephrase the problem in a way that you rephrase the problem in a way that you can implement the code can implement the code um so here let's say so um so here let's say so you know we're gonna go over the you know we're gonna go over the property of this problem right so that property of this problem right so that here we're basically one at a time what here we're basically one at a time what this algorithm this algorithm or these operations trying to do is one or these operations trying to do is one at a time starting from the end at a time starting from the end keep everything sorted and keep everything sorted and and yeah and so then here's we start and yeah and so then here's we start with d with d and d sorted so that's good now we and d sorted so that's good now we insert the d insert the d uh that's also solid so that's good now uh that's also solid so that's good now we have ode right we have ode right now we have to sort this and the way now we have to sort this and the way that this that this gets sorted is by okay first the o gets sorted is by okay first the o becomes becomes and i'm i'm explaining it um without any and i'm i'm explaining it um without any proofs proofs you really have to just figure out the you really have to just figure out the properties um like i said if you watch properties um like i said if you watch me stop it live during the contest i me stop it live during the contest i actually like actually like like wrote down all these things and try like wrote down all these things and try to figure these things out manually to figure these things out manually so then what happens is that it takes so then what happens is that it takes the it converts the o the it converts the o to a d outside to the next letter to a d outside to the next letter um that's smaller than it so it converts um that's smaller than it so it converts to e to e and then now it's trying to sort the and then now it's trying to sort the rest which is o rest which is o and o and d so we're trying to sort the and o and d so we're trying to sort the rest into d and e rest into d and e uh sorry uh dno and then now the next uh sorry uh dno and then now the next one the yi one the yi is going to um speech to is going to um speech to uh the let the next letter which is d uh the let the next letter which is d and then now and then now it is going to be sorted in d o and then it is going to be sorted in d o and then now this thing is sorted now this thing is sorted and then now we add in the next letter c and then now we add in the next letter c so c it looks good so c it looks good because c is already sorted um and then because c is already sorted um and then now the next letter is t now the next letter is t um and then here's the the suffix um and then here's the the suffix we want to sort this into the next we want to sort this into the next letter as i said so it's going to be oh letter as i said so it's going to be oh i don't know it doesn't matter what this i don't know it doesn't matter what this is but it just sorts it into this is but it just sorts it into this and and yeah and then the next item and and yeah and then the next item after that after that is e so c d o t is e so c d o t um d c e o t um d c e o t and then now at the very end it sorts it and then now at the very end it sorts it into this into this um cool so that's basically the idea um cool so that's basically the idea that's the pattern that you sort it one that's the pattern that you sort it one at a time in these ways at a time in these ways and and then just you know that part is and and then just you know that part is hard to figure out as is because you hard to figure out as is because you have to figure out the second part of have to figure out the second part of well how many operations does it take to well how many operations does it take to to sort a suffix to sort a suffix well it turns out that it it actually is well it turns out that it it actually is just just um the total number of um the total number of combinations with those characters so in combinations with those characters so in this case this case because all the characters are unique it because all the characters are unique it is going to be four factorial because is going to be four factorial because they're four factorial so it takes they're four factorial so it takes here from from here to here here from from here to here four factorial from here to here is four four factorial from here to here is four factorial factorial and then so forth um and then it gets a and then so forth um and then it gets a little trickier when you have to do little trickier when you have to do another when they're duplicate letters another when they're duplicate letters um um but it's still the same concept but but it's still the same concept but let's say we had which one was the one i let's say we had which one was the one i have something like have something like this i think this i think yeah so then first it does b second b yeah so then first it does b second b a second a and then now it it has this a second a and then now it it has this and then it tries to get to this the and then it tries to get to this the next letter b next letter b uh aabc and uh aabc and the the number and actually it it starts the the number and actually it it starts i think i think by you know the reverse so the next one by you know the reverse so the next one after this is actually this and then you after this is actually this and then you want to sort it into this want to sort it into this um and the number of operations that it um and the number of operations that it takes takes it's actually just this formula of 4 it's actually just this formula of 4 factorial factorial over 2 factorial times 1 factorial over 2 factorial times 1 factorial times 1 factorial and i don't know how times 1 factorial and i don't know how you know and this is a very you know and this is a very uh common uh combo tourist counting uh common uh combo tourist counting thing thing so i'm not gonna do the proof here um so i'm not gonna do the proof here um because the proof is a little bit tricky because the proof is a little bit tricky i think what i would recommend as a i think what i would recommend as a prerequisite prerequisite is just doing more commentorical is just doing more commentorical problems problems um and this form this is a common um and this form this is a common numbers that should stick out to you numbers that should stick out to you when that happens when that happens um so yeah and once you're able to do um so yeah and once you're able to do this this um you know from here to here um you know from here to here and then now the next letter is just a a and then now the next letter is just a a b b c c and then now you're done b b c c and then now you're done um so yeah so that's um so yeah so that's oh wait no no this oh wait no no this hmm so c oh yeah and then this goes to hmm so c oh yeah and then this goes to a b b c c oh no no a a b b c c oh no no a h i this and then now you have the h i this and then now you have the second c to add second c to add so then now you have this and then it so then now you have this and then it goes to you know goes to you know um and then um and then a a pvcc right a a pvcc right and of course in this case this is this and of course in this case this is this would be would be you know it would take five factorial you know it would take five factorial over two factorial two factorial over two factorial two factorial one factorial um so that's basically it one factorial um so that's basically it and my and my implementation is um is this implementation is um is this and it i don't think i'm gonna go with and it i don't think i'm gonna go with that deeply because it requires a lot of that deeply because it requires a lot of maybe there's an easier way to do this maybe there's an easier way to do this but it requires some power but it requires some power and uh math with respect to uh modular and uh math with respect to uh modular inverse which i'm not gonna inverse which i'm not gonna go over either because that's you know go over either because that's you know you you these are things that are kind of what these are things that are kind of what makes this problem hard makes this problem hard and and yeah and and yeah i mean these are things that you have to i mean these are things that you have to or for this problem you would i would or for this problem you would i would recommend learning it from other recommend learning it from other problems uh before you are able to problems uh before you are able to tackle this one tackle this one um and yeah and basically um and yeah and basically everything follows uh after this pattern everything follows uh after this pattern after i discovered this after i discovered this i basically just implement this pretty i basically just implement this pretty quickly except for i have a quickly except for i have a i had a minor um bug that took me 15 i had a minor um bug that took me 15 minutes to debunk so it really minutes to debunk so it really tanked my ranking but yeah but i'm happy tanked my ranking but yeah but i'm happy that i solved this without any uh errors that i solved this without any uh errors so yeah so basically just going up so yeah so basically just going up really quickly you know um but i'm not really quickly you know um but i'm not gonna go into diamond details just going gonna go into diamond details just going over over the problem so this is you know just the problem so this is you know just setting up the problem setting up the problem this is just me pre-calculating the this is just me pre-calculating the factorial um factorial um you know given the mod and the modular you know given the mod and the modular inverse given the mod inverse given the mod and then here you know for each and then here you know for each character that we add in character that we add in we keep track of a counts table which is we keep track of a counts table which is just basically the count of every just basically the count of every alphabet alphabet uh which is 26 and then for each uh which is 26 and then for each and then say say this is a c we look can and then say say this is a c we look can we change it to a b we change it to a b if there's a b then we can change it to if there's a b then we can change it to b and then we keep on going downwards b and then we keep on going downwards that way um that way um here we use this character we calculate here we use this character we calculate what we said earlier with respect to the what we said earlier with respect to the factorial times the ma the the product factorial times the ma the the product of the modular inverse of the modular inverse we mod that and uh um we mod that and uh um and then yeah and then we add that and then yeah and then we add that counts back on so that it can be counts back on so that it can be you know use the next one and that's you know use the next one and that's pretty much it and then this is just to pretty much it and then this is just to keep track of the number of characters keep track of the number of characters that we used we got it in another way that we used we got it in another way but that's fine but that's fine um but yeah and then at the very end we um but yeah and then at the very end we return to mod return to mod um yeah and and this is what i had on um yeah and and this is what i had on booth first to kind of check my answers booth first to kind of check my answers on a couple of cases on a couple of cases uh smaller cases obviously but yeah um uh smaller cases obviously but yeah um let me know what you think uh i actually let me know what you think uh i actually go for my thought process go for my thought process as i was doing this during the contest as i was doing this during the contest maybe not 100 clear but maybe not 100 clear but but you can kind of see my thought but you can kind of see my thought process as i do it so i definitely process as i do it so i definitely recommend it recommend it so what is the uh complexity right well so what is the uh complexity right well for each character for each character you know this is going to be of n loop you know this is going to be of n loop and this and this of course will just be at most o of 26 of course will just be at most o of 26 because uh 20. sorry 26 square alpha because uh 20. sorry 26 square alpha squared which is squared which is the number of um number of characters in the number of um number of characters in alphabet alphabet because we for each character we look at because we for each character we look at all the previous characters which is 26 all the previous characters which is 26 and then we do this thing which is also and then we do this thing which is also of 26 we could have probably done some of 26 we could have probably done some math in some funky way but math in some funky way but we didn't do that like we probably could we didn't do that like we probably could eliminate this loop but eliminate this loop but it was not slow enough so i didn't we it was not slow enough so i didn't we have to worry because this is only three have to worry because this is only three thousand thousand so yeah it's gonna be three or n times so yeah it's gonna be three or n times alpha square alpha square um which is fast enough for this problem um which is fast enough for this problem uh cool uh cool uh that's all i have watch me sub it uh that's all i have watch me sub it live during the contest maybe it'll help live during the contest maybe it'll help a little bit a little bit like i said don't feel that bad if you like i said don't feel that bad if you don't get this one because i don't think don't get this one because i don't think i there's a lot of components that you i there's a lot of components that you need to know and it's very muffy need to know and it's very muffy every component is pretty muffy um so i every component is pretty muffy um so i don't i wouldn't don't i wouldn't i don't think it's gonna come up on an i don't think it's gonna come up on an interview anyway unless you're doing interview anyway unless you're doing something like crazy something like crazy quant stuff so i wouldn't worry about it quant stuff so i wouldn't worry about it that much but it is a fun problem hope that much but it is a fun problem hope you enjoyed it you enjoyed it and yeah i will see you later uh yeah and yeah i will see you later uh yeah watch me let's stop it live during the watch me let's stop it live during the contest m oh just okay oh just a this is impossible to understand okay this is impossible to understand okay examples don't make it really that much examples don't make it really that much better j um so largest index it is one index 7 x now that's a then it is one index 7 x now that's a then such that 2 is less than such that 2 is less than b okay so that's b okay so that's a j a j is such that i mean j has to be two at is such that i mean j has to be two at this point swap i might as well swap i might as well check okay i don't know i know this this this one's i don't know i know this this this one's impossible to read that along impossible to read that along yourself okay example here is three and then okay so the biggest number that's so that's four okay let me slow down b and then reverse the string started at some sort of weird insertion sort some sort of weird insertion sort so what is this doing it so what is this doing it takes the first instance of an inversion takes the first instance of an inversion in this case well the latest inversion so b you largest index chair what the numbers are okay so then it's the first instance where uh index eye so i can't even make trivial code correctly that one seems fair i always i can't even get this code right i can't even get this code right bac so that now b and bac so that now b and i should be z that should be one i should be z that should be one is another one is another one oh i see so fun so fun i mean we don't expect this one to be i mean we don't expect this one to be right but that's fine see okay so now we have the correct code just gonna be taking way too long yup 60 25 263. okay so then now we can see what the is doing delete code and see if we could skip steps and yourself here two people solved it so and this is some like weird bubble up hmm how many people cutting this hmm how many people cutting this place what people have gotten it so this is sorted so this is sorted so now that the suffix is sort of what so now that the suffix is sort of what happens let me even just look at the third let me even just look at the third example example 63 this may be a hint actually two to 63 this may be a hint actually two to the the fifth times two fifth times two all right let's look at that one first so the last two okay and what happens when you have a new and what happens when you have a new number so everything after that it should be right so now we look at b right so now we look at b and we have to try to figure out yes the number of inversion isn't just n squared because hmm so so i'll look at it from the back but i i'll look at it from the back but i don't know that i can get anything from it's like a weird insertion sword what does this do what does the reverse hmm so this looks at the next suffix so this looks at the next suffix just these two that i can figure out hmm what happens when you see a new letter what happens when you see a new letter it takes so then now that means that this will be so then now that means that this will be sorted but reverse and then the reverse we're sorted we're trying to get it back to the front i don't know c looks at c c d so then it needs to c looks at c c d so then it needs to do the prefix of huh do the prefix of huh and it does be until it and then it just does stuff which is which is 30 24 moves away 30 24 moves away 4 factorio is 24. and then it does it for and then b and then now we know that it can't do that move the a to the front so then now you have these things which is four fractal 4 factorial again which means that this is 24 is that right i guess that's right so it takes n factorial to sort to thing so now we take the pee okay i mean i have some intuition but now i struggle a little bit and now a and then d has to go to the next i think i get the idea but i don't know what to enter if this is of okay so now we find okay so now we find ont and then now we sort this it's already done with move tests to you g so the c is good before okay just good that we have this before okay just good that we have this a little bit yeah i'm close closer now i have to figure out how to get it and i have to figure out how to handle and i have to figure out how to handle dupes let's take the suffix it's sorted so that's still good at the it's sorted so that's still good at the oh it does not sorted so then it ticks because the first move is moving the yi because the first move is moving the yi and then moving to d and then moving to d so it's two factorial times two so it's two factorial times two factorial factorial and then now we have to sort it c is and then now we have to sort it c is sorted so that's okay sorted so that's okay and then the t will go from the o which is and we go from 4 to 28 just to press 24 yep i have an hour how many people have i have an hour how many people have gotten it so far people are really gotten it so far people are really smart and fast it seems like um do i need inverse path for this maybe okay that's what i expected roughly it's 4 factorial over i always forget how to do modular [Music] [Music] you um oh you forget this by accident so we assume everything after this is sorted and now we [Music] no that's not right what i want to do is now we're looking okay well you have to look at the next i don't know that's not good that's not good oh my god [Music] that's why i put in the math as well now this should be now this is well this should be because then now we're swapping with x because then now we're swapping with x and then we won half white that's well i'm probably off by a little bit of a i'm probably off by a little bit of a constant we should be able to solve this given we should be able to solve this given that we have a lot of time but that we have a lot of time but still tricky i need to do this locally so that doesn't give me this stuff but okay so i think that my mouth is started as that's too hard to print out [Music] something about the uniqueness that's something about the uniqueness that's why i'm a little bit oh why i'm a little bit oh i was wrong why is this particularly hmm maybe i just need to suck it up and figure it out does this is this work okay so it is definitely something with the duplicate letter handling that i'm trying to reduce the case a little bit that's good maybe okay so let's go go oh it's good to see see it's good c so the first thing we're going to do is actually t and c and now it's trying to figure out how to do this is oh it's three is oh it's three it's for fact it was four maybe but i think i've i thought it was six teague so just to get an o o is here so we have t c c i don't know okay no this doesn't know i don't know okay no this doesn't know okay i'm looking the wrong thing okay i'm looking the wrong thing this is an oh so we need to sort this this is an oh so we need to sort this thing which thing which in my math should be 4 factorial over 2 in my math should be 4 factorial over 2 factorial factorial so that's 12 and here we go so that's 12 and here we go 13. right and then here 13 it goes so see we're trying to sort this out so that's gonna be again four factorial over two factorial which is 12 so 25 okay so far so good and now this is an o so to sort this thing out it's going to be five so that's dirty so 55 so that's dirty so 55 i mean i'm i think my math is right so i mean i'm i think my math is right so my implementation is a little bit off my implementation is a little bit off okay um okay um oh that's awkward now one two three four oh that's awkward now one two three four that's why that's why 18 is after 18 is after it does all this so this first four is fine four sense okay so now this is singer c goes to okay so now this is singer c goes to one gets what hey so it should be true that seems right um that math on the whatever is side that math on the whatever is side hmm yeah i mean this is right it does have the 12. another six oh i am dumb okay and this is a bad time for my computer oh but on it's so close oh but on it's so close okay oh come on of course now is the time that it is choosing to be slow my computer gonna cost me some oh there we go oh there we go my chrome always fixed the worst time to my chrome always fixed the worst time to be why is it pending oh come on why is it pending oh come on come on old computer oh because it's printing a lot okay that looks like the right answer let's run it again now without the printing code okay it please cool that was tough i mean i i don't know how other people did it um people are very smart in doing these maps but uh hope you enjoyed that you know this video let me know what you think hit the like button hit the subscribe and join me in discord hope you did well in this contest this problem uh let me know your questions um yeah so take care of yourself take care of others stay good stay healthy stay and to convert to health i'll see you
2024-03-22 18:12:43
1,830
https://i.ytimg.com/vi/d…axresdefault.jpg
1830. Minimum Number of Operations to Make String Sorted (Leetcode Hard)
8T8-j9I-cJg
hey hello there let's talk about today's recording challenge question word search recording challenge question word search given a two-dimensional board of given a two-dimensional board of characters and also a search word characters and also a search word we want to determine whether we can we want to determine whether we can construct the word by construct the word by sequentially connecting adjacent letters sequentially connecting adjacent letters on the board the adjacent here means on the board the adjacent here means horizontal or vertical neighboring horizontal or vertical neighboring so it's a four directional moves note so it's a four directional moves note that the letters cannot be used more that the letters cannot be used more than once than once so once we choose to use certain letters so once we choose to use certain letters to form to form uh the prior part of the word in uh the prior part of the word in subsequent choices subsequent choices we couldn't use it again so we couldn't use it again so that's pretty much the question let's that's pretty much the question let's look at this example we have a board look at this example we have a board with three rows and four columns with three rows and four columns now we are trying to construct the word now we are trying to construct the word abc cde abc cde obviously we want to start this obviously we want to start this construction from the positions on the construction from the positions on the board that starts with the first board that starts with the first letter a so because the word starts with letter a so because the word starts with a so once we match that a so once we match that we try to find the next character we're we try to find the next character we're looking around looking around the neighbor of a and find b so now we the neighbor of a and find b so now we match the two characters match the two characters the third thing the next step is trying the third thing the next step is trying to match the next character in the in to match the next character in the in the word so it's a c the word so it's a c so we see that we're now gradually so we see that we're now gradually building out building out this candidate passed in the world in this candidate passed in the world in on the board so once we match abc on the board so once we match abc we try to do that even further we moved we try to do that even further we moved on to on to get another c for this example get another c for this example and eventually we will basically match and eventually we will basically match everything so the path in the end everything so the path in the end has the same length of the word so has the same length of the word so that's the time that's the time when the candidate pass be promoted to when the candidate pass be promoted to the solution the solution as long as we find one solution we can as long as we find one solution we can return to in the other case return to in the other case let's see that we are trying to let's see that we are trying to construct the word abcb construct the word abcb the partial pass candidate candidate the partial pass candidate candidate passes this passes this highlighted here abc in the first in the highlighted here abc in the first in the next next step we're trying to grab b around the step we're trying to grab b around the neighbor of this neighbor of this highlighted c here we find there's no highlighted c here we find there's no neighbor that's a character b so this neighbor that's a character b so this candidate candidate has been pretty much destroyed so we go has been pretty much destroyed so we go back to a b back to a b and try to find c in other directions and try to find c in other directions since that there are no other c's we'll since that there are no other c's we'll go back to a go back to a uh at that time we will try to find b in uh at that time we will try to find b in the other direction the other direction but it's an s down there so it's not but it's an s down there so it's not possible so we possible so we declare that starting from this a declare that starting from this a there's no way that we can find there's no way that we can find a find a solution to this problem a find a solution to this problem so we will start with other positions so we will start with other positions and pretty much repeat this and pretty much repeat this process so in short is process so in short is backtracking or dfs backtracking or dfs so to handle the case that the letters so to handle the case that the letters may not be used more than once there are may not be used more than once there are a couple of ways one thing is to a couple of ways one thing is to as lo as we are growing this candidate as lo as we are growing this candidate to pass to pass a candidate crossing of the characters a candidate crossing of the characters in the board in the board we can use some extra data structure to we can use some extra data structure to memorize the word we have memorize the word we have used the character we have used or we used the character we have used or we can just can just simply replace the cell on the board by simply replace the cell on the board by some non-character stuff like empty space so that in a subsequent search we would never really use it so so that's also possible as well yeah so let's code this thing before before before code the because it's backtracking it's pretty much to try all the possibilities the time complexity is the number of cells on the on the board that's all the possible starting positions for this kind of candidate building uh tracking process and so that's m multiplied by something the backtracking would take a 4 to the l time because at any given particular cell in the maximum you are looking at the four directions and if the length of the word is l you're going to repeat this for 4 to the power of l times so that's and for space complexity it's basically the lens of the word first thing we grab the size of the first thing we grab the size of the board because we're going to do the looping the next thing we do is to the next thing we do is to [Music] [Music] basically lay out the main part for this basically lay out the main part for this function we're going to examine the board cell by cell if we have the matching in the first position then we start backtracking or we can in the backtracking logic to deal with that if the character doesn't match we term it early so it's it's easier to obviously in the main part we're trying obviously in the main part we're trying to look at to look at the first character in the in the word so that's the main part for the code then what we need to do is to lay out the detail of the spark by tracking process it takes three things the current position on the board and the eyes position ice capture that we want to match so if i is equal to length of the word that's the case when we successfully match the whole word then we just return true otherwise we want to determine so this means finished we want to test whether the character at this given position on the board is equal to the character that we want to uh we need so the condition is that it's a valid position on the board and also it has a value if that's the case we want to look if that's the case we want to look around the four neighbors and kick off around the four neighbors and kick off this backpacking process this backpacking process from that position trying to find the from that position trying to find the next next word but before we do that we want to word but before we do that we want to mask this current character so that we mask this current character so that we don't revisit don't revisit it but we have to restore it it but we have to restore it in the post order so once we determined in the post order so once we determined there's no there's no way there's no there's no way we can match the whole thing uh we can match the whole thing uh in some later stage we want to go back in some later stage we want to go back and restore this character on the board and restore this character on the board so we have to first to remember it [Music] i'm looking at the four neighbors now i'm looking at the four neighbors now and kick off this back tracking again and kick off this back tracking again from the neighbor's position with this from the neighbor's position with this uh uh aiming at finding the next character aiming at finding the next character if we can successfully doing this over if we can successfully doing this over and over and over and reach the end when the and reach the end when the eyes position when the i becomes equal eyes position when the i becomes equal to n to n indicating we match the whole word we're indicating we match the whole word we're going to return true going to return true otherwise we pretty much do nothing otherwise we pretty much do nothing return of force we can we can ignore it return of force we can we can ignore it as well as well so in python if nothing happened it so in python if nothing happened it would just be known would just be known so this should do oh it's called board it's not green ah sorry i have to restore the uh yeah uh yeah yeah so that's it that's the yeah so that's it that's the backtracking solution to this problem backtracking solution to this problem uh basically uh usually when i analyze uh basically uh usually when i analyze backtracking i backtracking i i think of the candidate that's growing i think of the candidate that's growing growing growing growing and growing growing growing and inside the back tracking logic here we inside the back tracking logic here we are making a choice here are making a choice here that's basically this four directional that's basically this four directional moves moves and once we make a choice the next and once we make a choice the next position we go position we go we are growing the candidate by we are growing the candidate by extending that by one more position extending that by one more position in this case it's not a physical in this case it's not a physical candidate i'm carrying candidate i'm carrying in the in the backtrack it's rather the in the in the backtrack it's rather the the empty space on the board the empty the empty space on the board the empty space on the board space on the board is marking the candidate is marking the candidate candidate sequence of characters that candidate sequence of characters that i'm using to i'm using to find the word so find the word so so i have to go back and restore that so i have to go back and restore that after i made the choice and determined after i made the choice and determined that the choice is that the choice is invalid so that's why i'm restoring it invalid so that's why i'm restoring it here here i guess the distinction between i guess the distinction between backtracking and simple dfs is that backtracking and simple dfs is that once you make a choice and you determine once you make a choice and you determine that choice is that choice is fruitless there's no meaning that you fruitless there's no meaning that you have to restore the have to restore the modification you did so that's a that's modification you did so that's a that's an extra step on top of dfs that an extra step on top of dfs that makes backtracking slightly different makes backtracking slightly different from dfs from dfs yeah so the time complexity is all the yeah so the time complexity is all the possible starting locations indicated by possible starting locations indicated by the nested the nested double loop here and double loop here and the four to the l is indicated by the the four to the l is indicated by the this for loop here we try four positions this for loop here we try four positions and every position we just recursively and every position we just recursively call this backtrack call this backtrack so it's a forward to the length of the so it's a forward to the length of the word uh for space complexity word uh for space complexity it's the call stack of this backdrop it's the call stack of this backdrop this can go this can go as long as the i become equal to the as long as the i become equal to the length of the word length of the word so that's the levels of recursive call so that's the levels of recursive call that's going to happen that's going to happen so that's the space requirement because so that's the space requirement because i'm modifying the i'm modifying the board to indicate the board to indicate the the current path is not using any extra the current path is not using any extra data structure data structure uh yeah so that's uh this dfs uh yeah so that's uh this dfs backtracking backtracking solution to word search uh if you're solution to word search uh if you're interested i have a video about the word interested i have a video about the word search two search two which is nothing but you know which is nothing but you know which is nothing but uh search for which is nothing but uh search for multiple words with this uh multiple words with this uh backtrack procedure so instead of just backtrack procedure so instead of just using using uh the in index uh the in index and find the eyes position of the word and find the eyes position of the word uh it's trying to match the try pass so uh it's trying to match the try pass so the stuff you put on the backtrack core the stuff you put on the backtrack core is a is a node object in the try and the current node object in the try and the current position so position so a slightly more complicated but the the a slightly more complicated but the the main part is main part is pretty similar you have the nested loop pretty similar you have the nested loop here and you have a backtrack here and you have a backtrack which is nothing but can we promote this which is nothing but can we promote this candidate to the final solution candidate to the final solution if so we add it otherwise we're going to if so we add it otherwise we're going to verify verify the current matching and the current matching and mask of the board position and go make a mask of the board position and go make a choice of the four directional movements choice of the four directional movements so in terms of the main logic in the so in terms of the main logic in the code it's uh it's pretty much code it's uh it's pretty much identical to this one except that uh identical to this one except that uh it's using a try note it's using a try note try data structure to do the matching try data structure to do the matching but with that you can match but with that you can match a c uh you know a set of different words a c uh you know a set of different words on the board on the board so if you're interested you can check so if you're interested you can check out the the video over there out the the video over there um i'll i'll try to put a link up there um i'll i'll try to put a link up there so that's the so that's the the code that's the question for today
2024-03-20 12:05:38
79
https://i.ytimg.com/vi/8…axresdefault.jpg
Leetcode 79 Word Search
MOS1InReiEI
hello all welcome to netset os today in this video we will know about today in this video we will know about dry data structure dry data structure before going for any data structure before going for any data structure array binary linked list heap data array binary linked list heap data structure structure and also stack we have seen pros and and also stack we have seen pros and cons of each structure cons of each structure in an effort to make it easier to see in an effort to make it easier to see what type of problems that structure was what type of problems that structure was created created to solve now today's data structure is to solve now today's data structure is dry try is the data structure which was dry try is the data structure which was created to solve the problem of created to solve the problem of representing a set of words representing a set of words here throughout the video we'll be here throughout the video we'll be looking for inserting nodes looking for inserting nodes how we can insert node in a try how we can insert node in a try searching nodes searching nodes how we can know the words starting with how we can know the words starting with a particular letter and with that we a particular letter and with that we will know the practical usages of will know the practical usages of drive so basically try comes from the drive so basically try comes from the word word retrieval retrieval here retrieval retrieval here there is try so however there is try so however tries basically a tree data structure tries basically a tree data structure whose note whose note stores the letters of alphabet by stores the letters of alphabet by structuring the notes structuring the notes in a particular way words and string can in a particular way words and string can be retrieved be retrieved by traversing down the branch path of by traversing down the branch path of the tree the tree we'll see this first let's see the usage we'll see this first let's see the usage of price so that will be more excited to of price so that will be more excited to know know how it works internally so if i go to how it works internally so if i go to google google and if i type like sp and if i type like sp a the words coming with a the words coming with spa are spanning tree spanish to spa are spanning tree spanish to english spanning tree algorithms bandana english spanning tree algorithms bandana spa spa online spa near me spa spa online spa near me spanish flu spaghetti spain basically spanish flu spaghetti spain basically auto complete feature as i typed auto complete feature as i typed here in google search engine it will here in google search engine it will complete complete so here we can imagine how typing three so here we can imagine how typing three letters letters into a search box would retrieve into a search box would retrieve a subset of of a much larger tri a subset of of a much larger tri structure it can be spanning trees structure it can be spanning trees spanish to english spanish to english spar now if we see the other usage spar now if we see the other usage it is used for matching algorithms and it is used for matching algorithms and implementing things implementing things like spell checkers so it is quite like spell checkers so it is quite exciting to know how drive works exciting to know how drive works internally so throughout this lecture we internally so throughout this lecture we will be seeing will be seeing how we can retrieve the words so how we can retrieve the words so let's start with how we can insert a let's start with how we can insert a node in a try node in a try so let's start with first inserting so let's start with first inserting nodes nodes so we know tries are often used to so we know tries are often used to represent represent words in an alphabet here in this words in an alphabet here in this example we can start to get example we can start to get a sense of how exactly that a sense of how exactly that representation works representation works each tree has empty root node each tree has empty root node like this and like this and it will be linking to other nodes it will be linking to other nodes so that the shape and structure of so that the shape and structure of try is always a set try is always a set of linked nodes and these link nodes of linked nodes and these link nodes are connecting back to a empty root node are connecting back to a empty root node so each node contains an array of child so each node contains an array of child nodes as we can see this is a parent nodes as we can see this is a parent node which is node which is empty and it will have the empty and it will have the child nodes starting with the letters child nodes starting with the letters of the alphabet the letters in the of the alphabet the letters in the alphabet alphabet are 26 so we can say starting from are 26 so we can say starting from a with a b c a with a b c up till z so up till z so there is one thing to note the size of there is one thing to note the size of tri is directly connected or correlated tri is directly connected or correlated to size of alphabet that is being to size of alphabet that is being represented here represented here we'll see this with example here we'll see this with example here we will take an example where we have a we will take an example where we have a try try that contain empty node now here that contain empty node now here in this example we have an empty in this example we have an empty try which is referencing to children try which is referencing to children nodes here if we notice we have nodes here if we notice we have two things over here first a two things over here first a value which might be null over here value which might be null over here and the second the references and the second the references to other nodes so here it to other nodes so here it is an area of references to is an area of references to child nodes all of which can be child nodes all of which can be null also so basically each node in a null also so basically each node in a try try includes the root node root node includes the root node root node itself when i try representing the itself when i try representing the english language it consists of english language it consists of single root node whose value single root node whose value is usually set to an empty string is usually set to an empty string the root node will have an array that the root node will have an array that contains contains 26 references 26 references which at first will be pointing to null which at first will be pointing to null as try grows those pointer as try grows those pointer starts to get filled up with references starts to get filled up with references to other nodes as well a to other nodes as well a can be referenced to other nodes then can be referenced to other nodes then that that particular node will be referenced to particular node will be referenced to other nodes other nodes similarly with all 26 similarly with all 26 references of english language references of english language and here it will be indexed starting and here it will be indexed starting from from 0 and there are 26 letters that means 0 and there are 26 letters that means it will be starting from 0 index to it will be starting from 0 index to 25 and why they are 26 25 and why they are 26 since there are 26 possible slots since there are 26 possible slots for 26 letters of alphabet for 26 letters of alphabet so enough of theoretical things now we so enough of theoretical things now we will start with will start with first inserting nodes first inserting nodes let's say we have rhyme of words over let's say we have rhyme of words over here here in front of our screen and we have to in front of our screen and we have to make a try make a try so as we have seen so first so as we have seen so first we will take the first letter which is we will take the first letter which is b so i'll start with the first b so i'll start with the first letter b over here now letter b over here now after b there is u after b there is u so it will be making its children node so it will be making its children node with u then g then with u then g then l then e perfect l then e perfect now we have the first word now we have the first word completed in our tribe now we will start completed in our tribe now we will start with with second word which is b second word which is b e so we will see the first e so we will see the first letter is b available in a try letter is b available in a try yes so here only we will take this b yes so here only we will take this b referencing to the second letter which referencing to the second letter which is e is e so here itself it will draw so here itself it will draw e let's say if we had here instead of e let's say if we had here instead of u e we will have taken the help of u e we will have taken the help of this e itself but earlier this e itself but earlier it was u now it is e so we'll be making it was u now it is e so we'll be making the the other child node which is e over here other child node which is e over here then after e it's u then after e it's u so we will take u here then so we will take u here then g then e and thereafter g then e and thereafter we got l now after this we'll be we got l now after this we'll be turning to third word which is turning to third word which is blue gill so we'll start with blue gill so we'll start with first letter which is b we are first letter which is b we are comfortable comfortable we have b over here as our first letter we have b over here as our first letter now we'll be searching for second letter now we'll be searching for second letter which is which is l but we don't have l over here l but we don't have l over here so we'll be making the next one so we'll be making the next one with l then u then with l then u then e then g then e then g then i and then l then i and then l then l s given here l s given here now starting with the other word now starting with the other word which is b u g which is b u g e l now for searching for b e l now for searching for b we have b here then for u we have b here then for u u also we have here so we'll be u also we have here so we'll be taking the help of this b taking the help of this b then this u then we have third letter s then this u then we have third letter s g we will be taking the help of this as g we will be taking the help of this as well well then e but we have here then e but we have here l so we'll be taking the l so we'll be taking the other letter e after this other letter e after this g as g is referencing to l g as g is referencing to l as well as the other letters apart from as well as the other letters apart from l also as we have seen here it is l also as we have seen here it is referencing to referencing to all 26 letters so all 26 letters so taking the help of this feature in a try taking the help of this feature in a try we will point e over here and then we will point e over here and then the last letter which is l the last letter which is l then we'll be going for the next then we'll be going for the next word which is starting from f word which is starting from f earlier we have seen all the words which earlier we have seen all the words which was starting from was starting from b but this time it is starting from b but this time it is starting from f we don't need this b right now f we don't need this b right now so we'll be taking the another letter so we'll be taking the another letter which is starting from f and which is starting from f and here we are pointing to our here we are pointing to our empty node that's why we used to use empty node that's why we used to use here here the root node with an empty string the root node with an empty string so that it will be referencing to all so that it will be referencing to all 26 nodes similarly 26 nodes similarly we are doing here as well it is we are doing here as well it is referencing to b referencing to b as well as f and similarly to as well as f and similarly to the other letters of the alphabet let's the other letters of the alphabet let's start with start with f now here we have f now here we have f then u f then u then g then a then g then a then l then proceeding towards the next then l then proceeding towards the next word here we have f so we will take the word here we have f so we will take the help of this help of this f then u wow we have f then u wow we have u also here then g u also here then g yes we have g also over here we can take yes we have g also over here we can take the help the help f u and g then proceeding further f u and g then proceeding further we have e but earlier we had used we have e but earlier we had used a now we need to divert our path a now we need to divert our path to e this time and then we will have to e this time and then we will have l so with this we have used our l so with this we have used our earlier memory of fugal earlier memory of fugal and using this memory we have made and using this memory we have made the other word f-u-g-e-l the other word f-u-g-e-l now proceeding towards the next word now proceeding towards the next word where we have frugal where we have frugal so frugal will take the help of f first so frugal will take the help of f first yes we have but then we have u yes we have but then we have u so we need to divert our path from here so we need to divert our path from here itself itself r then double o i'll be taking double o r then double o i'll be taking double o over here over here and then g then l and then g then l and then we will have e so till here and then we will have e so till here we have seen each node that we have seen each node that each node has 26 each node has 26 children even though we are not using it children even though we are not using it but they are there now what if but they are there now what if i want to add one more word i want to add one more word which is flugal the new word and i want which is flugal the new word and i want to add to add to our existing try to our existing try so before adding the word to our so before adding the word to our existing try we need to take care of two existing try we need to take care of two points points first we need to check that first we need to check that this new word is existing this new word is existing in a already made try or not in a already made try or not if it already exists then we need not to if it already exists then we need not to add that particular word add that particular word so first we should be confirmed that so first we should be confirmed that the word which we want to insert in a the word which we want to insert in a try try should not exist then should not exist then next if we have traversed down the next if we have traversed down the branch branch step by step because we have already step by step because we have already seen seen whether this word exist or not we have whether this word exist or not we have traversed that means we have traversed traversed that means we have traversed throughout the try throughout the try so now we will insert a value so now we will insert a value into the node referencing where the word into the node referencing where the word should go should go simply as when we have this flugel simply as when we have this flugel first letter is f so we'll be going for first letter is f so we'll be going for first the empty root node first the empty root node and we will traverse down and we'll look and we will traverse down and we'll look for for f here here we have f because f here here we have f because the other one the other child node is b the other one the other child node is b so we will be leaving this and going for so we will be leaving this and going for f over here then we'll be going for f over here then we'll be going for l here l is not there so we'll be making l here l is not there so we'll be making the other branch for f the other branch for f as the l the child node of as the l the child node of f and it will be going to make its f and it will be going to make its flow girl as like this flow girl as like this let's try to understand this in the let's try to understand this in the other way here other way here i want to insert let's say fly i want to insert let's say fly simply f l y and simply f l y and i want this fly should be i want this fly should be given the value as six given the value as six this is a key for fly and this is this is a key for fly and this is value as 6. now you'll say value as 6. now you'll say if you have to insert a key with a value if you have to insert a key with a value you can make use of you can make use of hash or a dictionary right we hash or a dictionary right we can make use of dictionary where we just can make use of dictionary where we just need to give the letter need to give the letter fly and its value fly and its value so there is a difference between hash so there is a difference between hash and try and try we'll see this in the couple of minutes we'll see this in the couple of minutes now now we'll see how we can insert this word we'll see how we can insert this word fly fly with the help of try as we know there is with the help of try as we know there is an an empty root which will have an empty empty root which will have an empty string string firstly and an array firstly and an array with 26 references with 26 references let's say from a to z and you can see let's say from a to z and you can see we will find our null link at f pointer we will find our null link at f pointer so we create a new node over here so we create a new node over here with f as we have to insert with f as we have to insert fly so the first letter is f over here fly so the first letter is f over here so somewhere in the between a to z so somewhere in the between a to z we will have f over here which will be we will have f over here which will be linking to linking to the other child node but before that the other child node but before that it won't be having anything null link it won't be having anything null link we will encounter the another null link we will encounter the another null link which will be referencing from a to z which will be referencing from a to z then then we will create the other l over here we will create the other l over here the other node l the other node l similarly it will be referencing to similarly it will be referencing to other a to z other a to z now we'll be seeing for y over here now we'll be seeing for y over here and as we reached the last character and as we reached the last character which is y it will be allotting which is y it will be allotting its value which is fly its value which is fly value is 6. so this is the one way value is 6. so this is the one way to tell that our word is completed to tell that our word is completed by here here we have fly by here here we have fly as soon as we encounter this as soon as we encounter this 6 over here we will be knowing that this 6 over here we will be knowing that this letter this word is completed by now letter this word is completed by now otherwise if you are going for fl we otherwise if you are going for fl we won't be having any value won't be having any value so let's say here it will have zero so let's say here it will have zero so whenever it reached till l so whenever it reached till l there it won't be encountering any value there it won't be encountering any value that's why that's why it will be knowing that it is an it will be knowing that it is an incomplete incomplete word so basically we will first look for word so basically we will first look for pointer for f since the try does not pointer for f since the try does not have have anything apart from a to z anything apart from a to z the reference at f in our root node the reference at f in our root node will be null before and the root will be null before and the root will have all the empty slots from will have all the empty slots from 0 to 25 as soon as we get this 0 to 25 as soon as we get this f it will be going to the fifth index f it will be going to the fifth index and will fill this f towards and will fill this f towards this null link that contain a reference this null link that contain a reference to one node to one node now we have a node at index 5 now we have a node at index 5 holding the value of f but our string is holding the value of f but our string is fly now we will be doing the same thing fly now we will be doing the same thing it is referencing to f then it is referencing to f then it will be given l l will be it will be given l l will be at index 11 and similarly at index 11 and similarly it will be referencing for y as well it will be referencing for y as well and then it will be allotting its value and then it will be allotting its value of that particular of that particular key which is six though there are other key which is six though there are other ways as well ways as well we'll discuss one by one so in the we'll discuss one by one so in the future future if we want to retrieve the value for the if we want to retrieve the value for the key let's say key let's say fly we will traverse down from one array fly we will traverse down from one array to to another using the indexes to go from another using the indexes to go from nodes nodes f then l then y f then l then y when we get to the node at the index for when we get to the node at the index for y y we will stop traversing retrieve the we will stop traversing retrieve the values values from that node which will be 6 over from that node which will be 6 over here now we have this fly over here here now we have this fly over here and we want to search for the key and we want to search for the key let's say we have already drawn fly and let's say we have already drawn fly and i want to search for i want to search for fly in my try and want to find the node fly in my try and want to find the node at the last letter we can look to see at the last letter we can look to see its value if it has null value it means its value if it has null value it means the word is not a currently the word is not a currently a key over here as here a key over here as here first it will go to the empty node then first it will go to the empty node then it will go to f f is here it will go to f f is here fine enough then it will look for l here fine enough then it will look for l here l is there then it will look for y l is there then it will look for y and as soon as it will see this and as soon as it will see this value to the fly that means value to the fly that means it found the word is it found the word is hit in the search list we got our hit in the search list we got our word now if we want to delete from a try word now if we want to delete from a try let's say we have fly with 6 value and let's say we have fly with 6 value and flies with 14. that means flies with 14. that means there is an empty node where we have f l there is an empty node where we have f l y with 6 value f y with 6 value f l i e s with 14 value l i e s with 14 value now if you want to remove key value pair now if you want to remove key value pair we first find the node for that key we first find the node for that key and set its value to null so that and set its value to null so that when it will encounter flies when it will encounter flies let's say i want to delete this flies let's say i want to delete this flies so as soon as i get after traversing so as soon as i get after traversing f l i e s it will f l i e s it will delete the complete word over let's say delete the complete word over let's say i want to delete flies so first i want to delete flies so first it will traverse down and as soon as it it will traverse down and as soon as it will get will get flies the value it will start flies the value it will start deleting let's say first i will look for deleting let's say first i will look for its parent node whether e has its parent node whether e has another child or not because if this another child or not because if this parent has another child then parent has another child then we won't be able to delete this because we won't be able to delete this because it is also referencing to it is also referencing to another child also so s has another child also so s has e as parent which don't have another e as parent which don't have another child child node so we will delete s from here node so we will delete s from here then we will look for e whether he has then we will look for e whether he has the parent which has the other child so we will delete e from here then for i it will look for parent which has the other child yes here l has two child y and i so we will delete just i o y and our flies is being deleted from our try and also as i have searched in the google engine for spa here it is giving all the words which are starting from sba so let's write a program for implementing a try for a prefix tree which is a try here we will insert search as well as we start with so for inserting first let's define its children so i'll write self dot children equal to all 26 letters let's define by default none into 26 as it is referencing from 0 to 25 now as we have seen the value allotted for the key value means that a word is completed now we can do one more thing we can simply write at the end of each word let's say here as the flugel completes here it should check of each end letter of the word whether it is and or not so for this i'll write self dot is and of word by default we will define it as false and we will see for each word if the last letter is set to true then we will be thinking it as a complete word so let's start with insert so for insert first let's take the current as first we'll define itself then we will iterate letter by letter so here i'll write for i in word here you can also define with the length there you need or to use this n keyword then i'll be looking for this if current.children looking for each letter or we can say the index here let's define index which will have od of i minus the first letter so that it will have the index that particular index of that letter so here i'll write a and we'll be checking for each letter which is index if it is none then it will be going to try so here it will go to try and then we will store it in current only which will have current.children index and as soon as the word completes we will give the end of that word which is end of word set to true so that will be confirmed that a letter has been inserted completely similarly we'll go for search for search i'll take this then we will iterate one by one where current for index and here we will be looking for index and here we will be looking for for each current value if it is each current value if it is none then it will return false none then it will return false and then we will look for the end of and then we will look for the end of word word if it is last letter it will return if it is last letter it will return true else it will return true else it will return false so search will be searching like false so search will be searching like this this whereas in starts with we are not whereas in starts with we are not at all concerned with the last letter so at all concerned with the last letter so we'll be simply copying this we'll be simply copying this and we will delete this last line and we will delete this last line instead of this it will return true instead of this it will return true now when i run this code let's see oh now when i run this code let's see oh rdi here i have used rdi here i have used square brackets instead of this i should square brackets instead of this i should use use i with braces all the i with braces all the places here it's prefix so i need to use over here it's prefix so i need to use over here here prefix let's run it again prefix let's run it again and here this is accepted and here this is accepted so we'll submit here and we'll return so we'll submit here and we'll return back back now we see the difference between hash now we see the difference between hash table and try table and try basically hash table comprises of basically hash table comprises of array plus linked list whereas tries uses arrays plus pointer or we can say references now if we see bigger notation runtime for creating a try structure is completely dependent on how many words the try contains so it will have order of m n m for longest word and n signifies total number of words where we can search insert delete from the try depends on the length of the word so we can say total number of words the complexity it will have a n a signifies to the length of the word so in the try introduction we have seen how we can insert node how we can search node and also starting with letters how we can go for it and also we have seen the code for it and also we have seen the practical usage of drive which is its auto complete feature retrieving the subset of much larger tri structure as well as it is also used for matching algorithms and implementing things like spell checker so hope you got the introduction of try now in the next upcoming videos we'll be taking questions on try though we have covered lead code number 208 we will take more questions based on it so let's meet in the next video till then bye
2024-03-22 10:04:21
208
https://i.ytimg.com/vi/M…axresdefault.jpg
What is Trie | Implement Trie (Prefix Tree) | leetcode 208
aqlZOAt6d80
hey what's up guys this is sean here so let's take a look at last problem of so let's take a look at last problem of this week's this week's weekly contest number 1681 weekly contest number 1681 minimum incompatibility um minimum incompatibility um this one is a medium problem and a lot of people downloaded this problem i i i don't know i don't know i don't know about that but okay let's take a look at the description so you're given like an integer array numbers and then integer k here you're asked to basically to divide these nums into k groups where that's and there's a constraint that's basically each group cannot have two duplicated numbers all right and so that's the constraints to divide this k groups and then it asks you to get basically a subset incompatibility is the diff is the difference between the minimum and the maximum value in this in this array here in this in each group and it asks you to return the minimum possible total income incompatibility of all the and if there's no way you can divide and if there's no way you can divide the into k groups you just you just need the into k groups you just you just need to return minus one to return minus one right so i mean for example right right so i mean for example right so the first one is like this so we have so the first one is like this so we have one two one two one four right so obviously oh and one four right so obviously oh and one of the constraints is that you know one of the constraints is that you know k is k is the the nums the length is divisible by the the nums the length is divisible by k k so it's guaranteeing that the you can so it's guaranteeing that the you can divide those some divide those some those numbers into k groups and those numbers into k groups and for example this one here right so there for example this one here right so there are like how many ways to divide are like how many ways to divide into into a group of of two into into a group of of two right size of two basically that's a right size of two basically that's a combination combination four of of two right it's gonna be uh four of of two right it's gonna be uh four times three divided by two times four times three divided by two times one right which is the uh one right which is the uh which is six i think yeah but not all which is six i think yeah but not all six is six is it's possible it's valid because you it's possible it's valid because you know know one cannot be to one so this one is not one cannot be to one so this one is not it's not optional basically you can only it's not optional basically you can only choose from certain groups choose from certain groups right so yeah basically that's the right so yeah basically that's the description of this problem i mean a description of this problem i mean a naive approach will be will be of course naive approach will be will be of course we can try to use a backtracking i guess we can try to use a backtracking i guess right and because the the length of the right and because the the length of the the number is only the number is only uh to the 16 uh we can try to use uh to the 16 uh we can try to use backtrackings but backtrackings but i think for if you use a regular i think for if you use a regular backtracking it will probably tle backtracking it will probably tle because you know because you know basically at each of the uh the location basically at each of the uh the location at at each each of the the numbers here right each each of the the numbers here right we will try we will try we'll try to pick uh we'll try to pick uh we'll try to pick k numbers we'll try to pick k numbers we'll try to pick the the next k numbers we'll try to pick the the next k numbers from the uh from the uh from the remaining from the remaining from the remaining from the remaining unpicked numbers unpicked numbers right and then we just continue doing right and then we just continue doing that i think that i think for that the backtracking time for that the backtracking time complexity will be similar to n to the complexity will be similar to n to the power of power of k and that will that will tle k and that will that will tle of course right so and then we can of course right so and then we can another option is that you know we we another option is that you know we we just tried the dp right so just tried the dp right so basically we try the dp and dp the state will be the uh like the peaked numbers basically the state will be the how many numbers have we have picked so far right and then we can either use a tuple here we can use a table or we can just use like a mask a bit mask right so tuple which basically we just store the the number itself and for the bit mask we can save some space complexity right and but we we're going to use the the index the the bitmask to represent each of the numbers and so zero means not picked and one means peaked right and one means peaked right and at each of the state here at each of and at each of the state here at each of the dp state here the dp state here you know we're gonna we're gonna loop you know we're gonna we're gonna loop we're gonna have uh find all the uh we're gonna have uh find all the uh and all the non-picked and all the non-picked uh numbers here and then we're going to uh numbers here and then we're going to do a like company we're going to do a do a like company we're going to do a combinations combinations we're going to do a c of this number of we're going to do a c of this number of not not pick numbers we'll call it not not pick numbers we'll call it m and then we'll pick the target and m and then we'll pick the target and we're going to have like target we're going to have like target so the target will be what so we need we so the target will be what so we need we need like the need like the n divided by k right so this is going to n divided by k right so this is going to be the target be the target i call it a target and here so going to i call it a target and here so going to be a target and for each group be a target and for each group so so at each of the the tp here we just so so at each of the the tp here we just do a target do a target do a combinations from the remaining do a combinations from the remaining items items and then we pick this many of the and then we pick this many of the the numbers and we do combination we try the numbers and we do combination we try we try each of them and we'll get the we try each of them and we'll get the minimum minimum total sum among among those right i mean total sum among among those right i mean i don't know if there's a better i don't know if there's a better solutions other than this kind of like a solutions other than this kind of like a brutal force dp solutions but anyway so brutal force dp solutions but anyway so let's try to implement let's try to implement this one so this one so the uh so a few the uh so a few things we have a length of nums right things we have a length of nums right and then we have a and then we have a target right target or let's call it uh target right target or let's call it uh equals to k subsets let's call it equals to k subsets let's call it subsets subsets size how about that so i think this is like more proper name for that so subset size will be undivided by k right and then and then we're going to have like uh the the dp right so that the dp i'm just using a beat mask here and then out also using this python's built-in functions right so to help me do the other memory top-down memorizations and so here's the template right so the at the beginning we have the the system max size right and then in the end we return the the answer right so i mean the the implementation is a little bit trivial because the uh you know there's no other options but like but i have to find basically we need to find the remainings the remaining uh the remaining numbers which has not been picked right so here i use i for in range in range n right basically i loop through everything for n and i find if the mask i use this one equals to zero basically i use this one equals to zero basically this is like a this is like a short short version of the for loop short short version of the for loop so among all those kind of numbers i i so among all those kind of numbers i i find find the the index index whose mask is zero the the index index whose mask is zero because zero means the uh because zero means the uh it has not been picked because here it has not been picked because here in the end i'm gonna do a dp0 right zero in the end i'm gonna do a dp0 right zero means means everything at each bit mask is zero so everything at each bit mask is zero so now i have a remaining now i have a remaining and now i just need a combination so for and now i just need a combination so for combinations i just use a combinations i just use a python combinations helper functions python combinations helper functions that's that's very convenient for us to find all the very convenient for us to find all the combinations right otherwise combinations right otherwise to implement the combinations will be to implement the combinations will be kind of annoying so here i'm going to have sub sets of size right so now we have a combinations here so but i think the combinations we should have converted to at least otherwise it's going to be a iterator here and then for each of the combinations and so for each of the combinations like and so for each of the combinations like i said not other combinations of valid i said not other combinations of valid combinations because we combinations because we we need to make sure there's no we need to make sure there's no duplicate numbers in each of the duplicate numbers in each of the combinations combinations so i mean um a easier way to do it is that since we also need to get the maximum and the minimum numbers into the uh for this group i'm going to uh convert them into so i'm going to do a nums so i'm going to do a nums dot i right for dot i right for i in c because c we have a we have index i in c because c we have a we have index in in the c here right and then in in the c here right and then i just convert them into a into a number i just convert them into a into a number here into here into yeah a number of lists and yeah a number of lists and then i just also convert them into a set then i just also convert them into a set because that's the easiest way to find because that's the easiest way to find if there's any if there's any duplicated numbers into it because if duplicated numbers into it because if there is there is then the length of the the current then the length of the the current numbers numbers one will be smaller right than one will be smaller right than than the target than the uh than the than the target than the uh than the subset subset size right so if that's the case simply size right so if that's the case simply continue continue right i check if there is i check if there is any duplicate number any duplicate number right and now right and now i just need to have like a new mask i just need to have like a new mask because now because now since this this combination is a valid since this this combination is a valid one so i need to one so i need to mark those mark the bit for those for mark those mark the bit for those for each of the uh each of the uh the index basically for i in c right and the index basically for i in c right and then the new then the new mask equals the new mask equals the new i'll do a this one right so that's that that's why i mark this index the bit to one and then we just have this answer equals and then we just have this answer equals the minimum of the answer the minimum of the answer right that's the at the actual dp part right that's the at the actual dp part and we have a new and we have a new mask and then plus what plus the uh mask and then plus what plus the uh plus the uh the difference the plus the uh the difference the difference for this kind for this difference for this kind for this combination which is the uh which is the combination which is the uh which is the at the max at the max of current nums miners minimum of current nums miners minimum of current numbers right so here i know of current numbers right so here i know this is not the most efficient way but this is not the most efficient way but you know it will not affect the total you know it will not affect the total time complexity and so i just use this time complexity and so i just use this one one just to for simplicity here right just to for simplicity here right and yeah so how about the minus one and yeah so how about the minus one right so here right so here i mean so the minus one is pretty i mean so the minus one is pretty straightforward i mean if the answer straightforward i mean if the answer is it's it's not smaller is it's it's not smaller basically we only return the answer if basically we only return the answer if the answer is is smaller than the max the answer is is smaller than the max size right else minus one which means that you know if we never we never find the solutions here right i mean the uh the the final answer the answer will be uh will be system max size oh sorry i forgot about the the base case right so the base case is what base case is we have we have picked all the outer mask right so which means that if the mask is equal to the uh i uh by this right if the mask is all one then we return zero that's the uh that that's the base case because because right here right at at the end let's say let's say the uh this this combo is the last four or is the last it's the last few numbers we we need to pick for the last subset and then we'll have this one but here we have dp now the new the new mask here will be a one one one one right there will be one so in this case we should return like a zero here so we can get the final answer right correctly that's why we need this uh final uh exit cool and like i said for this minus one cool and like i said for this minus one case right i mean case right i mean if we never find any valid if we never find any valid case right and which means that you know the uh the dp here so the dp it will return this one the dp as the uh the maximum one right so some of the dp if if there's no valid for appear in the end the dpu will return that system maximum size right and then in the end the answer will be bigger than this one so in for that case we just need to return -1 which means that we never find cool yeah i think that's pretty much it cool yeah i think that's pretty much it is let me try to run the code is let me try to run the code all right so accept it submit yeah so it barely passed because you guys can see it's almost 10 10 seconds right i mean because the the time complexity right i mean it's pretty obvious right time complexity at what is the 2 to the power of of n right because that's the total the total states of this of this beat mass and that's 2 to the power of n and 2 to the power of n and for each of the the beat mask for each of the the beat mask we have uh we have this we have uh we have this this for loop here right so the for loop this for loop here right so the for loop will be uh yeah actually the time complexity will be a little bit complicated because there here we have end but we also have this kind of combinations so for combination is uh is c to the uh c to the uh n of n of of k of the uh of the sub the subsets of k of the uh of the sub the subsets right of right of n divided by by k yeah actually i'm not quite sure how yeah actually i'm not quite sure how what is the correct what is the correct uh correct uh time complexity for this uh correct uh time complexity for this i think it's close to i think it's close to close to to this one but i'm not 100 close to to this one but i'm not 100 sure because sure because it's quite complicated we have a it's quite complicated we have a combinations here and for each of the combinations here and for each of the combinations combinations we also have like this uh we also have like this uh this for loop here yeah so this for loop here yeah so for the cut time complexity i'll just for the cut time complexity i'll just leave it here so if you guys have a leave it here so if you guys have a better better idea about this one i i would more than idea about this one i i would more than happy happy to know that and yeah as you guys can to know that and yeah as you guys can see because the time complex is pretty see because the time complex is pretty pretty big that's why the uh the running pretty big that's why the uh the running time is not that time is not that that good but that good but but for me i basically i couldn't find but for me i basically i couldn't find another another under another way to solve this this under another way to solve this this problem you know all the other ways they problem you know all the other ways they are they're all are they're all they've got tle and so and this is like they've got tle and so and this is like more like more like a brutal force way to solve this right a brutal force way to solve this right even though it's even though it's it's even though it's a dp but inside it's even though it's a dp but inside each of the dp here each of the dp here we uh we have a bunch of combinations we uh we have a bunch of combinations and the four loops and the four loops nicely four loops and blah blah blah nicely four loops and blah blah blah right all right cool i think i'll just stop here and thank you so much for you guys to watch this video and stay tuned and see you guys soon
2024-03-20 12:07:57
1,681
https://i.ytimg.com/vi/a…axresdefault.jpg
LeetCode 1681. Minimum Incompatibility
b0PC0-NRCxw
hey guys persistent programmer here and welcome to my channel welcome to my channel so in this channel we solve a lot of so in this channel we solve a lot of problems and today we're going to look problems and today we're going to look at the problem happy number at the problem happy number so let's go ahead and get started right so let's go ahead and get started right away this problem states that write an away this problem states that write an algorithm to determine if a number n algorithm to determine if a number n is happy so what does this mean if the is happy so what does this mean if the number n is happy number n is happy um they say that a happy number is a um they say that a happy number is a number defined by the following process number defined by the following process starting with any positive integer starting with any positive integer replace the number by the sum replace the number by the sum of the squares of its digits and repeat of the squares of its digits and repeat the process the process until the number equals one so until the number equals one so let's look at this example over here so let's look at this example over here so we have 19 we have 19 um and what they have done here is um and what they have done here is they've taken the square of 1 plus the they've taken the square of 1 plus the square square of 9 so that's 9 square is 81 of 9 so that's 9 square is 81 plus 1 that gives you 82. and then now plus 1 that gives you 82. and then now they've taken this 82 they've taken this 82 and then they've done 8 squared which is and then they've done 8 squared which is 64 64 plus 2 square which is 4. so 68. so this plus 2 square which is 4. so 68. so this is the way is the way um the algorithm needs to work to um the algorithm needs to work to determine determine if we can get a final sum of one if we can get a final sum of one so that's what the problem is asking so so that's what the problem is asking so if this is the case then we need to if this is the case then we need to return return true um otherwise we need to detect if true um otherwise we need to detect if there is a loop there is a loop so if a number is not a happy number so if a number is not a happy number then then what will happen is the sum will keep what will happen is the sum will keep repeating itself and we'll see an repeating itself and we'll see an example of this when we're discussing example of this when we're discussing the solution the solution so in that case we need to return false so in that case we need to return false okay so let's dive into the solution okay so let's dive into the solution okay so let's look at this example over okay so let's look at this example over here where n is two here where n is two so if we were to take all the sums of so if we were to take all the sums of two so two square is 4 and then 4 square two so two square is 4 and then 4 square is 16 and then at 16 we is 16 and then at 16 we take the square of 1 and 6 so 36 plus 1 take the square of 1 and 6 so 36 plus 1 37 37 and if we kept going like this we would and if we kept going like this we would get get a sum of 20 and if you look here that um a sum of 20 and if you look here that um if we take the digits out of 20 and if if we take the digits out of 20 and if we um we um add them up so that gives us 2 squared add them up so that gives us 2 squared plus 0 squared which is 4. so plus 0 squared which is 4. so we've already seen this 4 over here we've already seen this 4 over here and what this means is that um there and what this means is that um there will be a continuous cycle will be a continuous cycle when there is an input like this so when there is an input like this so again we'll take four and then square it again we'll take four and then square it and then we'll get 16. so it's just and then we'll get 16. so it's just gonna go in this gonna go in this endless cycle over here and this is what endless cycle over here and this is what um um we want to say is false right so it's we want to say is false right so it's not a happy number so we need to return not a happy number so we need to return false in this case um and then the false in this case um and then the example that we looked at in the example that we looked at in the solution solution is where uh once we keep taking the sums is where uh once we keep taking the sums we we get we eventually get a one and that's get we eventually get a one and that's what what is defined as a happy number so in this is defined as a happy number so in this case we are going to return true case we are going to return true okay now a few things to keep in mind okay now a few things to keep in mind here um here um while doing the code is how to get while doing the code is how to get each digit right so um one of the ways each digit right so um one of the ways that that this can be done is to use the mod this can be done is to use the mod operator over here operator over here which looks like this so which looks like this so what this does is anytime we take the what this does is anytime we take the mod mod um we take the mod of the number uh mod um we take the mod of the number uh mod 10 10 it will give us um this number so like it will give us um this number so like 19 divided it will give us the last 19 divided it will give us the last number number um of all the digits so here in this um of all the digits so here in this case case we have 19 mod 10. so um we have 19 mod 10. so um 19 if you divide 19 by 10 you will get a 19 if you divide 19 by 10 you will get a remainder of 9. remainder of 9. so that's how we can get the last number so that's how we can get the last number and you can practice over here i've put and you can practice over here i've put in some in some logs if you haven't used the mod before logs if you haven't used the mod before but um this is one way to get but um this is one way to get the last number and then so that's okay the last number and then so that's okay but how do we get but how do we get how do we get this number before it how do we get this number before it right and any other numbers before that right and any other numbers before that so how do we move forward so so how do we move forward so what we can do is we can take the 19 and what we can do is we can take the 19 and we can divide it by 10. we can divide it by 10. so what this would give you is one point so what this would give you is one point some number right so if you do some number right so if you do math.floor math.floor what this function returns is um what this function returns is um anything that's any integer that is anything that's any integer that is before before that um decimal value so it's it'll it that um decimal value so it's it'll it won't round up won't round up so it won't take any decimals into so it won't take any decimals into consideration it will just return you consideration it will just return you um this one over here for this case um this one over here for this case right so right so what do we need to do after this so what what do we need to do after this so what we need to find the we need to find the squares um and we need to keep squares um and we need to keep accumulating them so we need to add accumulating them so we need to add 9 square which is 81 and then we need to 9 square which is 81 and then we need to add 1 square which is 1 right so this is add 1 square which is 1 right so this is how you would get how you would get 82 right so that's how you keep getting 82 right so that's how you keep getting the numbers the numbers and if this all makes sense we can and if this all makes sense we can quickly do a walkthrough of what the quickly do a walkthrough of what the solution would look like so for this solution would look like so for this type of situation where we want to check type of situation where we want to check if the number is repeating or not um if the number is repeating or not um using a set using a set is a good candidate because um a set is a good candidate because um a set only stores unique values so we can only stores unique values so we can we can check against the set to see okay we can check against the set to see okay does this is this number repeating is does this is this number repeating is the sum repeating itself or not the sum repeating itself or not um and then if it's not repeating then um and then if it's not repeating then we're good that means it could still be we're good that means it could still be a happy number a happy number so what we do is we add that number to so what we do is we add that number to the set and then we will the set and then we will uh we will initialize this square sum so uh we will initialize this square sum so what we saw over here right so we need what we saw over here right so we need to do this to do this accumulation here we need to square the accumulation here we need to square the digits and then add them digits and then add them right and then finally we can check if right and then finally we can check if the square sum equals 1 then we know the square sum equals 1 then we know it's a happy number so we can return it's a happy number so we can return true true otherwise we're going to return false otherwise we're going to return false because this if this condition does not because this if this condition does not meet meet we can just return false because uh we can just return false because uh let's take this example here right after let's take this example here right after this case this case um we're gonna see a four from if we um we're gonna see a four from if we take the input as take the input as 20 and when we see that four we can see 20 and when we see that four we can see oh the set has this four so oh the set has this four so we know that this would be a cycle so we we know that this would be a cycle so we can just return false can just return false awesome so i'm back in the code and i've awesome so i'm back in the code and i've put the question um put the question um example up top here so we can refer to example up top here so we can refer to it when coding it when coding so the first thing i've done here is so the first thing i've done here is created an empty set called scene created an empty set called scene and this is going to be used to track and this is going to be used to track whether we have seen that number or not whether we have seen that number or not so i can say while um we have not so i can say while um we have not seen that n so this is our auger while loop and now what we need to do is if we haven't seen it we're going to add it to the set um so for next time we're not tracking the same number right so i can say um scene dot add that number all right now we need to go through each digit and we need to uh find the square root sum so first of all i will initialize that square sum variable so i will say sq sum is going to be zero and and this refers to the fact that okay like we need to have um a first sum so first let's initialized to zero and then now what we're gonna do is find this nine square and this one square and then add it up and get the uh set the end value to 82 which is going to go back up here um for analysis again so to see if that 82 exists in the scene right so we have initially put that squares up to zero and now what we're going to do is have a way to iterate over each digit so we'll say while um our number is greater than zero right um what we want to do is go to that nine first so we're going to say square some is going to be equal to n mod n mod 10 so this will give us the last value 10 so this will give us the last value of the n of the n and we're just going to uh times it to and we're just going to uh times it to itself so this is how we're going to get itself so this is how we're going to get the square you can also use the the square you can also use the math power function here um if you want math power function here um if you want so once we have that square sum what we so once we have that square sum what we need to do then need to do then is get that uh value before that number is get that uh value before that number and also and also add it to the sum so to do that we can add it to the sum so to do that we can use the use the floor function so we'll save mata floor floor function so we'll save mata floor and we will get and we will get n divided by 10 so that's how we're n divided by 10 so that's how we're grabbing that grabbing that uh digit before this number before it uh digit before this number before it and what we're going to do is we and what we're going to do is we now have this one for example here and now have this one for example here and we need to um we need to we need to um we need to set the um n set the um n to this so it goes back up here and then to this so it goes back up here and then adds back to the square sum again so we adds back to the square sum again so we want to add that one square want to add that one square uh back here right so we are going to uh back here right so we are going to set set n equals math.floor n equals math.floor and divided by 10 yes so that's going to and divided by 10 yes so that's going to give us if give us if our n is 19 in the first iteration it our n is 19 in the first iteration it will give us the one okay so will give us the one okay so this is going to be said come back up this is going to be said come back up here and yes one is greater than zero so here and yes one is greater than zero so it's going to add itself to the sum so it's going to add itself to the sum so this is how we can create a loop this is how we can create a loop for the number to keep um adding the for the number to keep um adding the square of itself square of itself all right awesome so now what we need to all right awesome so now what we need to see is see is if we're able to get that square sum if we're able to get that square sum equal to 1 or not because if that is equal to 1 or not because if that is equal to 1 then we can just return true equal to 1 then we can just return true so we will do that check here so we can so we will do that check here so we can say if say if square sum is equal to one square sum is equal to one then just go ahead and return then just go ahead and return true and if it's not one yet so for true and if it's not one yet so for example if we're at 82 and we need to example if we're at 82 and we need to keep going keep going and check um if we have other numbers and check um if we have other numbers that can get us to that one that can get us to that one we need to send it back up to this while we need to send it back up to this while loop here loop here so what we're going to do is just going so what we're going to do is just going to set the n value so we'll set to set the n value so we'll set n equals that square sum n equals that square sum so what we did here is we just set the n so what we did here is we just set the n uh uh to 82 here so then in the next iteration to 82 here so then in the next iteration it's going to go and compute the it's going to go and compute the 2 squared plus 8 square 68 and then set 2 squared plus 8 square 68 and then set n to 68 and then go back up again so it n to 68 and then go back up again so it will keep doing that will keep doing that until it finds a one um so that's what until it finds a one um so that's what we're doing here and then we're doing here and then if we don't find a one um after we have if we don't find a one um after we have gone through all the numbers gone through all the numbers um then or we've encountered the same um then or we've encountered the same number over that means we're not going number over that means we're not going to get to a one to get to a one um so in that case we will return false um so in that case we will return false so we'll go ahead and return false here so we'll go ahead and return false here okay okay it looks okay to me okay okay it looks okay to me i'm going to run this okay accept it i'm going to run this okay accept it and submit yay success
2024-03-22 09:42:56
202
https://i.ytimg.com/vi/b…axresdefault.jpg
Happy Number Javascript 202 Leetcode | Google Interview question
M0M8T4BOGmY
hey guys welcome back uh today in this video we gonna solve a problem video we gonna solve a problem uh from lead code uh from lead code uh number uh number 753 cracking the safe so this 753 cracking the safe so this problem is problem is from graph data structure and the from graph data structure and the solution we use is solution we use is dfs or dipped first search dfs or dipped first search and also and also google was the last company that had this problem in interview so let's go and learn more about the problem at the beginning and then start to solve it okay yeah so problem is uh name is cracking the safe but for sure your interview are not gonna tell this to you so if they're being really good then they give you texts like this for you and some example you can take this and move forward so you can take this and move forward so but sometimes even they come with an but sometimes even they come with an empty uh you know description and they empty uh you know description and they just verbally tell you something so you just verbally tell you something so you need to write it down yourself so uh my need to write it down yourself so uh my approach usually is going to be like approach usually is going to be like this so as soon as i start i go for this so as soon as i start i go for [Music] [Music] a problem a problem also let me also let me write down time here to find out you write down time here to find out you know how quick we can do this so know how quick we can do this so 2 23 is the start time so first of all 2 23 is the start time so first of all we we focus on the problem to understand it focus on the problem to understand it and then right after in middle of the and then right after in middle of the writing problem we will write markdown writing problem we will write markdown comments to make it organized and get comments to make it organized and get signature of a signature of a problem and problem and then we will go for then we will go for visualize visualize problems and actually examples this is problems and actually examples this is very important part so at this point uh very important part so at this point uh hopefully you will remember what's the hopefully you will remember what's the problem or you will some some solution problem or you will some some solution come in your mind so we will go for code come in your mind so we will go for code and and uh for unit tests uh and uh for unit tests uh and at the end we will go for at the end we will go for complexity complexity okay okay so to start this so to start this we will we will start from where we gonna write down our start from where we gonna write down our unit unit tests which is uh the best part is uh tests which is uh the best part is uh top and then top and then where we will come with the solution where we will come with the solution yeah so yeah so solution and language we're using it's a solution and language we're using it's a swift today swift today so maybe this been there or not you you're going to type it but you don't have signature of the function or api of the function so you need to start from this point so first of all we say okay we're looking for a function to do what yeah that will tell you yes that will tell you yes there is a safe protect by password the there is a safe protect by password the password is sequence of password is sequence of n digits n digits so so here i start from here i start from parameters and then my first parameter gonna be n which is n digit uh and so it's digits so it's gonna be integer so first question you will ask from your interviewer what's the range of n make sure to ask this they need to clear this for you so uh [Music] here in this example between one and four and k is between between one and four and k is between one and ten so just keep in mind okay so one and ten so just keep in mind okay so if this is one if this is one and four is digits and here we will say n digits so sequence of n digits the very digit can be in range of zero until k minus one so okay gonna be the second integer we will get so uh and and 10. 10. okay okay so so we almost got we almost got all information for inputs here you can write down description of the uh your problem and don't forget to write down you know to mention yourself about complexity and we don't know at this point uh we'll we don't know at this point uh we'll figure it out at the end usually and uh figure it out at the end usually and uh for sure we need to find out what we're for sure we need to find out what we're gonna return so gonna return so what we return what we return so what we return is uh so what we return is uh kind of s string but let's see what is kind of s string but let's see what is yes yes here we will see return any string of here we will see return any string of minimum length that will unlock minimum length that will unlock the save at some point of the save at some point of entering it so it's gonna be a string which is the password here let me here let me write down description here okay but it is important that we know what is the problem and how idea yeah so here i will write the description of the uh comments uh sorry description of the problem so this we will be looking for technically this minimum length so we write a function to crack you know safe you know safe so to understand this problem now we need to go for visualize you know for now we get that we have two you know two digit and we'll have one and put that string so and from base of these two digits we will find you know what is the you know what you know our output supposed to be as end digits gonna be number of the password and digit and k is range of the password characters could be so based of all of this before i jump to visualization i try to write my you know function signature so function crack safe underline n which is integer and underline k which is integer and we return one string so this is going to be my function but to find out what exactly we're looking for we need to visualize it so i start from example number so in this example so in this example we learned that our length is 1 k is 2. so k is 2. so if we want to write down our all of our if we want to write down our all of our possibilities we say okay we have possibilities we say okay we have possibility was zero possibility was zero and we have a possibility of one so base of this yeah my string yeah my string can be can be zero and here or opposite so this could be or opposite so this could be you know one and zero one and zero which match with uh you know our outputs that we're looking for but still we are not clear let's go to example number two so in example number two if you want to visualize it we need to make something like this we should say okay so zero zero could be one the answer okay so i can go by this uh that say okay if i start from zero zero you know and my so i put this output here okay yeah i say okay zero zero okay and at the rest gonna be one one zero so the second possibility of uh you know pro answer will be zero one so i can go by this so here's okay zero and zero one and a again one zero so this is the answer yes and it's gonna open it for me so if i go zero zero so if i go zero zero and then bond one is gonna open and then and the last possibility is could be one okay so 0 0 1 and then 1 0 which is the answer separately it is important that you do visualization the solution in your mind also the solution in your mind also you will get you know some answer sometimes this help you to you know figure out what bill could be an answer so okay so now at the visualization i write down my time is okay i actually forget i have the okay i actually forget i have the interruption between this so uh interruption between this so uh i'm not gonna go over that okay so uh i'm not gonna go over that okay so uh let's go for uh solution now so for let's go for uh solution now so for solution uh you know solution uh you know i can say i can say my approach my approach will be dfs which is deep first search and backtracking because uh you know i'm i have to guess and find out if it's true and then if it's true i can move forward and if not and i go i come back and continue and i use dfs because uh if i want to say okay my decision tree is gonna be something like this uh so for example i just say okay 0 is my first decision actually 0 0 is going to my first decision so the second decision of me could be 0 1 and 1 1 for example uh or one zero so uh i need to go and uh do you know by this three uh as a you know deep first search uh so means that i go uh you know by uh this way not by level okay uh if it was breathes first search then i'll go by level but you know i need to go from my tree down in one line which could be answer okay so let's go and start solution to keep this uh video short so first of all i start from and so for and so for best case i just say if n and k was equal one as well so [Music] my zero zero so i can i i will return so i can i i will return my only answer gonna be zero because k my only answer gonna be zero because k minus one can be zero minus one can be zero okay and then okay and then i'm gonna i'm gonna start start for for memo or memoize memo or memoize okay okay so here so here i declare one variable i name it i declare one variable i name it visited as usually we do for visited as usually we do for backtracking backtracking and so i make this to be a set in and so i make this to be a set in swift swift from type of from type of string string yes and i do parenthesis which is means yes and i do parenthesis which is means that fill it with empty that fill it with empty value for me then also i'm gonna value for me then also i'm gonna create one value one variable by the create one value one variable by the name of start name of start so this variable will be equal fill it with the string by with zero in there and with a count of with zero in there and with a count of how many it's gone it's gonna be how many it's gone it's gonna be n minus one n minus one so this is gonna be my string for zero so this is gonna be my string for zero then i'm gonna then i'm gonna call call dfs dfs but i did not declare this but uh but i did not declare this but uh signature i signature i like to be for dfs we're gonna be uh get like to be for dfs we're gonna be uh get starts here and starts here and also also gonna get gonna get k k here and at the end gonna get here and at the end gonna get visited visited but i make a visited but i make a visited as a pointer because i want to make it as a pointer because i want to make it make change on this visit that i need i make change on this visit that i need i want to keep updated want to keep updated okay so after i called dfs okay so after i called dfs then i should have a result okay but uh okay but uh first i am coming here and first i am coming here and on top of this on top of this in my class i'm gonna in my class i'm gonna define define results results results equal equal empty string happened what's happened what's for me for me i want to say append for me starting i'm gonna i'm gonna return return results so this is gonna be my main results so this is gonna be my main function and then i'm going to write my function and then i'm going to write my dfs dfs function which i call it here so i write function which i call it here so i write a function by the name of dfs and so what gonna be signature so uh underline uh from type of string from type of string and also underline from type of integer visited sets sets of of a string so this is to be capital a string so this is to be capital also here s need to be capital also here s need to be capital okay okay so so i gave my signature here something that i gave my signature here something that i forgot is that this should be i forgot is that this should be in out because i'm gonna move you might in out because i'm gonna move you might want to take this so i use in out and i use and sign here to be able to changed it still you know i add here start but uh here i don't think so i changed that one so let's uh see what is work uh for i'm gonna look at it later okay so here i write one in one for loop above index in range of 0 to not not exactly just just k minus one not not exactly just just k minus one and and so from this range so from this range i want to i want to do my loop okay so here i write a variable i named and i say okay this value will equal and i say okay this value will equal what equal back slash and again practice okay so here i use start and [Music] here i use and then i'm gonna write some my and then i'm gonna write some my logic so if logic so if not not visited so if you could apply maybe visit it then with not it's going to be true so if you cannot find it then go through and do this for me so what add this to visited yeah i'm gonna add neighbor in visited yeah i'm gonna add neighbor in visited first first then i'm gonna say okay variable then i'm gonna say okay variable char array area over characters area over characters and and neighbors filled with the neighbors and again now here i'm gonna call give us so i'm gonna call dfs so this is recursive as you see and uh so this time i'm gonna say okay a string char array we just char array we just i just defined it on top i just defined it on top from one to and also k and also k and also and and also and visited and i'm gonna save my results which is public up on top one string in there one string in there of of index think we've done just one part uh remain think we've done just one part uh remain because uh i use you know because uh i use you know access to uh string access to uh string which i don't have it there so i have to which i don't have it there so i have to go to go to extension extension of of string and define subscript for that so of of index index from type of return for me return for me character character how come how by this space to how come how by this space to return and and self.index then the self dot index offset by index so i add this to a function that you know two is a string protocol then on top you will see that i use it so i'm gonna run this to see if it's work mostly there will be some typo and i need to fix them so i go by and get to 29 line 29 here i return 0 which is uh not correct actually it's returning string so i can run so line 43 this time and what's the problem line where the three set of string has no member yeah so that fixed and now i go to line yeah so that fixed and now i go to line for this six for this six this time and the ad sign visited i this time and the ad sign visited i think again uh think again uh my visited is not typed correctly let me my visited is not typed correctly let me see see so it seems okay so it seems okay so let's see what's the problem and say so let's see what's the problem and say visited in scope visited in scope solution cannot find yes solution cannot find yes oh i wrote end oh i wrote end sorry dollar sign should be end okay sorry dollar sign should be end okay here we go here we go yeah yeah we're done so uh as you see yeah yeah we're done so uh as you see we got we got you know you know i test you know right actually we got i test you know right actually we got the minimum test uh done uh so the minimum test uh done uh so but but uh you know to be more professional and uh you know to be more professional and convince your uh you know interviewer convince your uh you know interviewer you need to write test case as well for you need to write test case as well for that that you know i use assert because uh you know i use assert because uh you know xc test not working inside here you know xc test not working inside here but you can write a exit test if you but you can write a exit test if you have time as well to to make have time as well to to make your your interviewer interviewer convinced to hire you so example number one make sure to write all examples and so first of all i'm gonna create an object uh my solution my solution and then i'm gonna write my inputs and and then i'm gonna write my inputs and actually define my input then i'm gonna actually define my input then i'm gonna define my output define my output so i'll put supposed to be this asserts okay so inside asserts i will call my you know object and then and inside function i will pass n and k and inside function i will pass n and k and output should be equal and output should be equal output so if this is not working fine we will write example one two we know that which example one two we know that which example failed yeah here you will see that solution yeah it's working fine yeah it's working fine so now you will see everything into this so now you will see everything into this unit test is independent so i'm gonna unit test is independent so i'm gonna write my second one which is available write my second one which is available here here i advise you to write couple more i advise you to write couple more for base of your for base of your self and should i submit that but anyway let's submit this it's working fine and you know that's the speed is not too bad and yeah it's uh street and time is 36 seconds and you know if i run this when this submit pushes one is work okay yeah that's it uh for today and i okay yeah that's it uh for today and i hope you liked this video and if you hope you liked this video and if you like it please make sure to give it a like it please make sure to give it a thumbs up thumbs up and uh don't forget uh to be subscribed and if you have any idea or any advice about this that will be helpful could be helpful for other other folks just please make sure to leave a comment below have a good one
2024-03-21 15:49:17
753
https://i.ytimg.com/vi_w…Y/sddefault.webp
Interview, Swift, Graph, leetcode, 753. Cracking the Safe (Google , DFS, Graph, Eulerian Circuit)
yYQB0l3Mgmg
Hello Hello Everybody Welcome To My Channel It's All The Record Problem All Elements All The Record Problem All Elements In Two Remedies At Trees Should Give Into In Two Remedies At Trees Should Give Into Binary Search Tree And Root To Return Ali Binary Search Tree And Root To Return Ali Containing All India From Both Recited In Containing All India From Both Recited In Ascending Order Showcases Subscribe Combination Problems Like To Subscribe Combination Problems Like To Travel In Travel In To- To- To- Will Solve This Problem Actually History History Video 0 Video 0 That This Vansh Wednesday List For The Tree Will That This Vansh Wednesday List For The Tree Will Exist This To-Do List And Will Get Answers Exist This To-Do List And Will Get Answers Active 1234 Sudhir and Souhard Universal Soul Will First Go to the Left Most Famous Channel Subscribe Veerwal The Veerwal The Video then subscribe to the Page if you liked The Video subscribe to the Channel subscribe to the Channel subscribe Kare subscribe Kare To Bilkul Channel Affidavit Communal Forces Will To Bilkul Channel Affidavit Communal Forces Will Come Back Shabbir Will Go Back To Subscribe Mid-Day Mid-Day Meal Meal Distance No Problem Solved List Play List Play List New A A Relaxed Also Defined As Too For The Road Too Soon You Will Call In Adhruv Veer Will Call In Subscribe Civil Hospital List In Turn Will Help Sexual Aid Untouchables Channel Untouchables Channel Subscribe Subscribe List List Check Root Canal Check Root Canal Ki dance simply return form hair otherwise Ki dance simply return form hair otherwise call in order for daughter of a call in order for daughter of a ki and similarly id list start and ki and similarly id list start and into new delhi in to-do list call log into new delhi in to-do list call log in 9th 1540 e hai so disawar inverter method vishal soni to A A A private private and will return list of teachers in summers and will return list of teachers in summers list will guide you to list in danger list list will guide you to list in danger list first class list of teacher a first class list of teacher a place to enter in the fair will create another list which means to return to find job is latest and will screen is latest and will screen is latest and will screen Points On A Gift For Tracking Also Index For List 2 And Jobs For College Students Will Spoil That I Lash 0 Electronic List wn.com Play List World Outside That And Jewelers In The Least Two Dot Size Page Will Check List Dot Festivals not at least one so that data side plus plus similarly it will do males will hide from the list play list on based of five and after that will also on and after that will also on is half of wild life India and like one of is half of wild life India and like one of the the the e-mail se contest will do for ne which e-mail se contest will do for ne which important elements of two boys and important elements of two boys and elements from delhi to that elements from delhi to that happy next z plus 2 directions happy next z plus 2 directions india and will return list india and will return list samridhi implementation former samridhi implementation former subscribe element from Life Life Life Is The Is The Chief Chief In In More Calling That And See Its Passing Dedicated Answers That And See Its Passing Dedicated Answers Flat Submit Record The City Has Accepted So What Is The Time Complexity Of Dissolution So Lets Say Electronic Bulb Screen Saver Mode On Is The President Times The Time Total subscribe to that similarly space complexities also fine that Bigg Boss this is a are using also I like it is a sorry for treating them I quit Saudi cigarettes teams were that that using to states first of all will guide This text by This text by This text by Calling Labs will always love you to my Calling Labs will always love you to my channel subscribe and they will fix element from drought and flood water values ​​where drawn appointed appointed electronic for the element from subscribe and subscribe the Channel and tap on the subscribe thanks subscribe thanks subscribe thanks
2024-03-20 11:52:34
1,305
https://i.ytimg.com/vi/y…axresdefault.jpg
all elements in two binary search trees leetcode | leetcode 1305 | bst
PPlHrKq4j1w
Hello Hello friends, in today's video we are going to discuss about delete list, discuss about delete list, question number three of 225, minimum tax, difference between question number three of 225, minimum tax, difference between target and suji, is the language target and suji, is the language problem, what is the problem of labs, problem, what is the problem of labs, what can you do, you have one element out of every two, what can you do, you have one element out of every two, you have to do CR. you have to do CR. you have to do CR. take a committee of all of them and together you target them - that is to tell you the updated answer, what comes at minimum, to give minimum distance, what you can do, from every summer, you have to use one green chilli, it is serious. And at that time, you can definitely subscribe by doing [music], you have the option here, either, you have the option here, either, what can you do, if you what can you do, if you use one of the two nets, then if you do all your rover use one of the two nets, then if you do all your rover missions, then you will get bread from romance. missions, then you will get bread from romance. What are the options for you to do, either you What are the options for you to do, either you can get the certificate by taking flowers, then can get the certificate by taking flowers, then set your floor here, you can get it by taking set your floor here, you can get it by taking real number three marks and salt, real number three marks and salt, you can do it from excessive consumption to active chocolate you can do it from excessive consumption to active chocolate syrup. syrup. syrup. we are okay here too so this products is going to be Ankita one plus plus 7 inch 3330 3330 - subscribe school subscribe subscribe to school subscribe subscribe to but 8 - 3139 settings duty you will have You do You do You do not need to check that this can make your dry ginger, not need to check that this can make your dry ginger, but if we talk about the method, then but if we talk about the method, then I will come to you personally and if you go I will come to you personally and if you go there and there and buy it for ₹ 10, then you can prank him with water for as long as you want. buy it for ₹ 10, then you can prank him with water for as long as you want. buy it for ₹ 10, then you can prank him with water for as long as you want. quarter of an inch, subscribing, do not forget to subscribe to School and Gas and if not forget to subscribe to School and Gas and if secondly, if you are trained here, then secondly, if you are trained here, then you will learn about something in chapter you will learn about something in chapter 789. 789. 789. free what is your use, if you have any problem, if you submit all the western tips in a lovely question, then what is your time complexity going to be and to the power and If the work If the work If the work doesn't work then what will we do? Here we will have to put a doesn't work then what will we do? Here we will have to put a DP. Let's see how we do it. We will leave Abu Zuhari. We will break his duty. The best decision is that he got his room, which means that he is real and in the column, you should have read his modern volume. Okay, you test your Aadhaar number to see that it is zero from time to time. This Raju Raju 2008, start doing 0.5 inches from time to time. If I will kill you, I will train you. You will do cash withdrawal from shampoo to electronics Custom what is going to Custom what is going to Custom what is going to happen part plus matrices RJ happen part plus matrices RJ please it will keep its first element Tamil Nadu please it will keep its first element Tamil Nadu Yagya then definitely everything will be fine on Play Store Yagya then definitely everything will be fine on Play Store I will be I will be updated with it at the life time of the members of the districts rally and updated with it at the life time of the members of the districts rally and whenever you now reached the last whenever you now reached the last whenever you now reached the last belligerent then you will check the return of Superman on this target. If you have selected here and want to use it in your phone, then you have done something here, then you understand that it is the best. If Know this minute what the rule number will be, if it is Know this minute what the rule number will be, if it is equal, then you update it from here, the difference here, how much will be returned, the third camera setting day is declared, so you returned the updates and the same thing Do Do Do not repeat in which the audio system and if it not repeat in which the audio system and if it is behind the previous one then we will return you the videos is behind the previous one then we will return you the videos that what will happen due to which you will not have to change your taste that what will happen due to which you will not have to change your taste now and whatever now and whatever update you want to do with the power and what update you want to do with the power and what happened after the previous 500 happened after the previous 500 500 600 500 600 By doing this, we compete on By doing this, we compete on how to know that whatever number of how to know that whatever number of winning numbers are followed in Profitable, when all the maximum is the winning numbers are followed in Profitable, when all the maximum is the same thing, next time if it happens again, then same thing, next time if it happens again, then you have made the first hit of that, then there will be more contact you have made the first hit of that, then there will be more contact and contest. and contest. dividing it into duplicate developed, from here, dividing it into duplicate developed, from here, what happened to the meeting which is received in medium form, what happened to the meeting which is received in medium form, along with which you said along with which you said that I am present, I have taken my Ajit that I am present, I have taken my Ajit element, you blacklist his roll number. element, you blacklist his roll number. Gone like this, Gone like this, every west difficult crore of your time, like once every west difficult crore of your time, like once you have taken Schezwan, shatter one by taking the photo and making you have taken Schezwan, shatter one by taking the photo and making any judgment of all the animals of your heart any judgment of all the animals of your heart and at the same time you are seeing this, the and at the same time you are seeing this, the way the answer is going on this. way the answer is going on this. way the answer is going on this. answer option of 'Submit' and you will see that you are 'Accept Pregnant'. I hope that after getting the explanation and understanding yourself that apart from this, if you do not want the code, then you can ask in the comment section if you want If you want to take a particular topic and understand how to give good If you want to take a particular topic and understand how to give good If you want to take a particular topic and understand how to give good gifts, then you must tell in the comment box gifts, then you must tell in the comment box and if you got it in this way, then yours is very light and also like the channel and subscribe, this will keep you motivated.
2024-03-25 12:46:22
1,981
https://i.ytimg.com/vi_w…xresdefault.webp
Minimize the Difference Between Target and Chosen Elements | Leetcode 1981 | DP | DSA
0yTFvjeo1P8
hey there flow coders welcome back to another episode on COD master sequest in another episode on COD master sequest in today's episode we are dealing with a today's episode we are dealing with a captivating physic based puzzle in a 2° captivating physic based puzzle in a 2° so without any further delay let's find so without any further delay let's find out the problem statement and Le out the problem statement and Le code where will the ball fall you have a code where will the ball fall you have a 2d grid of size M rows and N column 2d grid of size M rows and N column representing a box and you have N Balls representing a box and you have N Balls uh and the Box is open and on the top uh and the Box is open and on the top and bottom sides so each cell in the box and bottom sides so each cell in the box has a diagonal board sping two corner of has a diagonal board sping two corner of the cell that can redirect a ball to the the cell that can redirect a ball to the right or to the left we have two kind of right or to the left we have two kind of cell in this grid right a board that cell in this grid right a board that redirect the ball um to the right spans redirect the ball um to the right spans the top left corner to the bottom right the top left corner to the bottom right corner and is represented in the grid as corner and is represented in the grid as one and a board that redirect the ball one and a board that redirect the ball uh to the left spand the top right uh to the left spand the top right corner to the bottom left corner and is corner to the bottom left corner and is represented in the grid as minus one and represented in the grid as minus one and we drop one ball at the top of each we drop one ball at the top of each column of the box and each ball can get column of the box and each ball can get stuck in the box or fall out of the bom stuck in the box or fall out of the bom a ball gets stuck if it hits a v-shaped a ball gets stuck if it hits a v-shaped um you know pattern between two board or um you know pattern between two board or if a board redirect the ball into either if a board redirect the ball into either wall of the box and at the end we should wall of the box and at the end we should return an arrow answer of size n uh return an arrow answer of size n uh where answer R is the column that the where answer R is the column that the ball fall out uh of at the bottom after ball fall out uh of at the bottom after dropping the ball from the column at dropping the ball from the column at index I um or minus one if the ball get index I um or minus one if the ball get stuck in the box so if you look at the stuck in the box so if you look at the example number one if we receive um you example number one if we receive um you know a grid like this one and if we drop know a grid like this one and if we drop one ball from each column you know for one ball from each column you know for B1 we will um you know get a stuck in B1 we will um you know get a stuck in the in the Box because we have a vshape the in the Box because we have a vshape pattern here same thing for B4 the B4 pattern here same thing for B4 the B4 will be stuck here in in this vshape will be stuck here in in this vshape pattern and for B2 and B3 we will get a pattern and for B2 and B3 we will get a stck in this vshape pattern right but stck in this vshape pattern right but for b0 at the end of the move we will um for b0 at the end of the move we will um you know it will fall out from column you know it will fall out from column number one right so for this example we number one right so for this example we should return this array uh for b0 it should return this array uh for b0 it will drop out from column number one so will drop out from column number one so we should return minus one actually one we should return minus one actually one for for B zero but but for other um you for for B zero but but for other um you know for other balls since the balls know for other balls since the balls will get stuck in the grid we should will get stuck in the grid we should return minus one so this would be the return minus one so this would be the return value you um you know for other return value you um you know for other BS now to solve this question let's get BS now to solve this question let's get back to the visual studio code and try back to the visual studio code and try to solve to solve it to solve this question let me mention it to solve this question let me mention a few number of observation let's come a few number of observation let's come back to the browser and check this back to the browser and check this example we have two kind of cell in this example we have two kind of cell in this screen right left diagonal and right screen right left diagonal and right diagonal cells a right diagonal cell diagonal cells a right diagonal cell would be same something like this and we would be same something like this and we are representing these cells in the grid are representing these cells in the grid with one and left diagonal cell would be with one and left diagonal cell would be something like this one row zero and something like this one row zero and column 4 and we are representing this column 4 and we are representing this kind of cell in the grid with minus one kind of cell in the grid with minus one to solve this question we need to have to solve this question we need to have two observation what is the U the two observation what is the U the position of the ball after one move in position of the ball after one move in this grid and what is the U condition to this grid and what is the U condition to get stuck in a v-shaped pattern so let's get stuck in a v-shaped pattern so let's get started with B1 if we started with get started with B1 if we started with B1 from row zero and column one since we B1 from row zero and column one since we are facing with a right diagonal cell are facing with a right diagonal cell we would move to the right and for B4 we we would move to the right and for B4 we would Mo move to the uh left uh because would Mo move to the uh left uh because we are facing with a u left diagonal we are facing with a u left diagonal cell and since we are representing this cell and since we are representing this um this kind of cell with one and this um this kind of cell with one and this kind of cell with minus one uh to kind of cell with minus one uh to calculate the position of the ball after calculate the position of the ball after one move it's good enough to uh one move it's good enough to uh calculate the column number by calculate the column number by increasing um the value of the previous increasing um the value of the previous uh column with the value of this cell in uh column with the value of this cell in the grid right and U to find out what is the grid right and U to find out what is the condition to get St in a vshape the condition to get St in a vshape pattern if you look at here for B3 if we pattern if you look at here for B3 if we start from row zero and column 3 we start from row zero and column 3 we would move to the left because we face would move to the left because we face with the left um diagonal cell and the with the left um diagonal cell and the value of this um this cell in the grid value of this um this cell in the grid is not equal to the previous one right is not equal to the previous one right so the condition to get a stuck um so the condition to get a stuck um inside the vshape pattern is that um the inside the vshape pattern is that um the next position of the ball in the grid uh next position of the ball in the grid uh have a value different from what we have have a value different from what we have in the previous uh you know position so in the previous uh you know position so this is the condition to get stuck in this is the condition to get stuck in the vshape pattern now that we have this the vshape pattern now that we have this observation let's come back to the observation let's come back to the visual studio code and try to solve this visual studio code and try to solve this problem same as always and as a first sh problem same as always and as a first sh let's define the function signature here let's define the function signature here so let's say fun so let's say fun find ball then input for this function find ball then input for this function which is an a grid an array of integer a which is an a grid an array of integer a 2d array of integer actually and at end 2d array of integer actually and at end we are going to return an array of we are going to return an array of integer and to sort the return value for integer and to sort the return value for this function let me Define a variable this function let me Define a variable here result area of integer and it's here result area of integer and it's empty by default and at the end we are empty by default and at the end we are going to return this result right so in going to return this result right so in the body we need to define the movement the body we need to define the movement logic uh and for this purpose to logic uh and for this purpose to implement the movement logic I want to implement the movement logic I want to define a helper function that will define a helper function that will receive the coordination of above and receive the coordination of above and calculate the the movement for calculate the the movement for a so let me say find find ball drop a so let me say find find ball drop column it's going to receive the column it's going to receive the coordination of a ball in this grid so coordination of a ball in this grid so let's call let's call row column integer and for sure we need row column integer and for sure we need to have the grid as well so and at the to have the grid as well so and at the end of this function we are going to end of this function we are going to return uh the position of the uh the return uh the position of the uh the ball right so to find out whether uh ball right so to find out whether uh this ball is already dropped out from this ball is already dropped out from the bottom of the grid let me say if row the bottom of the grid let me say if row is equal equal to grid. count then this is equal equal to grid. count then this means that we follow out from the bottom means that we follow out from the bottom of the grid and we we need to return uh of the grid and we we need to return uh column as a result now we need to find column as a result now we need to find out the the column after one move and out the the column after one move and based on our observation we can say next based on our observation we can say next column is going to be column plus G for column is going to be column plus G for row and column right so this would be row and column right so this would be the position of the ball after one move the position of the ball after one move regarding the column now it's we need to regarding the column now it's we need to check whether we get out of the the grid check whether we get out of the the grid system from the Wes or we suck in a system from the Wes or we suck in a vshape pattern so for this purpose if vshape pattern so for this purpose if next call is less than Z zero or next next call is less than Z zero or next call is greater than grid z. count minus call is greater than grid z. count minus one this means that we we are out of the one this means that we we are out of the grid from the right hand side grid from the right hand side or grid for row and or grid for row and column is not equal to column is not equal to grid for row and next column right based grid for row and next column right based on our observation in this case we on our observation in this case we should return minus one based on the should return minus one based on the question description otherwise we should question description otherwise we should find out with the recursive call to the find out with the recursive call to the same function right so let's say return same function right so let's say return find ball drop column for row + one and find ball drop column for row + one and next column and we should pass the grid next column and we should pass the grid as well now let's come back to the as well now let's come back to the movement Logic for movement Logic for I and I and zero to um let's say zero to um let's say grid grid z. z. count let's say result that appen find count let's say result that appen find drop ball column or find ball drop drop ball column or find ball drop column actually column actually for row number zero column number I and for row number zero column number I and gries great right and this should be the gries great right and this should be the correct correct implementation but to make sure about it implementation but to make sure about it let's come back to the browser let's come back to the browser find out the input here where's the find out the input here where's the input yeah there we go here and now input yeah there we go here and now let's come back to theual Studio code let's come back to theual Studio code paste it just right here maybe I can paste it just right here maybe I can copy this part let's say let grid equal to this one and print find ball for this grid right should be a correct call to our function okay there we go let's see whether it's working uh sa problem let's see we expect to receive one minus one minus one minus one and minus one so it seems we have a correct solution as the last job let's submit our solution to Le code uh change the browser and paste our code just right here and hit the submit there we go here's the solution for this there we go here's the solution for this question thank you
2024-03-20 15:01:14
1,706
https://i.ytimg.com/vi/0…axresdefault.jpg
Where Will the Ball Fall - LeetCode 1706 - Swift
wDgDAOVqhhA
we're looking at leak code number 141 linked list linked list cycle this is a classic linked list cycle this is a classic linked list problem problem very classic pattern definitely one to very classic pattern definitely one to know know definitely shows up all the time highly definitely shows up all the time highly recommend to be familiar with this recommend to be familiar with this pattern also once you know this pattern pattern also once you know this pattern you can solve many other com questions you can solve many other com questions that come up with that come up with linked lists and even other types of linked lists and even other types of data structures that don't involve data structures that don't involve linked lists but linked lists but follow the same principles so what are follow the same principles so what are we doing here we are based we doing here we are based we're going to be given a linked list we're going to be given a linked list and we want to detect and we want to detect is there a cycle in this linked list and is there a cycle in this linked list and if it is we return true and if there's if it is we return true and if there's not we return false not we return false so here we have 3 2 0 minus 4 so here we have 3 2 0 minus 4 and we can see that if we we go from and we can see that if we we go from three to two three to two three to zero to minus four and then three to zero to minus four and then this goes back to two and we can see this goes back to two and we can see that there's a cycle here that there's a cycle here we return true this is also going to we return true this is also going to return true because we have a cycle here return true because we have a cycle here this two pointer points back to the one this two pointer points back to the one and then here we have a one it doesn't and then here we have a one it doesn't point to anything else so it's false point to anything else so it's false and so let's think about this there's and so let's think about this there's there's a couple different ways to there's a couple different ways to approach this approach this let's go ahead and move over to the let's go ahead and move over to the conceptual room we have 3 conceptual room we have 3 2 0 -4 so here we have we have a list 2 0 -4 so here we have we have a list with 3 3 with 3 3 2 0 -4 let me write this again and just give a little more space so we have a list with three two zero okay and now this four points back to okay and now this four points back to this this two this four points back to this two and and so what's what's a what's a brute and so what's what's a what's a brute force way force way we could do this well what we could do we could do this well what we could do is we could say say if there's a cycle is we could say say if there's a cycle then then then what we could say the number will then what we could say the number will have already been seen have already been seen right so let's say we had pushed all right so let's say we had pushed all these numbers into an array these numbers into an array and we had 3 2 and we had 3 2 0 minus 4 we could even just put all 0 minus 4 we could even just put all these nodes in that array these nodes in that array and then when we come back here to 2 and then when we come back here to 2 we can say well this has already been we can say well this has already been seen it's already in there seen it's already in there and and if it's already in there then we and and if it's already in there then we we have a cycle we have a cycle that is one way to do it the only issue that is one way to do it the only issue with that is we're going to create a with that is we're going to create a bunch of extra space bunch of extra space and it's going to also be extra time and it's going to also be extra time because if we have an array which is a because if we have an array which is a contiguous structure contiguous structure every time we want to check if every time we want to check if something's in there we're going to have something's in there we're going to have to iterate over that entire array to iterate over that entire array worst case so immediately we're looking worst case so immediately we're looking at at linear space and we're looking at linear space and we're looking at quadratic time which is not great quadratic time which is not great so what's another way we could do this so what's another way we could do this and that is using the method and that is using the method called using uh two pointers okay called using uh two pointers okay and this is a very classic pattern and this is a very classic pattern definitely one one that you want to know definitely one one that you want to know and the idea is you're going to have two and the idea is you're going to have two pointers you're going to have a fast pointers you're going to have a fast pointer pointer and you're going to have a slow pointer and you're going to have a slow pointer and every time you iterate and every time you iterate the fast is going to move two steps and the fast is going to move two steps and the slow is going to move one step the slow is going to move one step okay so let's just kind of step through okay so let's just kind of step through this on our first iteration the fast this on our first iteration the fast will move one will move one two steps the slow will move one step two steps the slow will move one step fast will move one and two steps it'll fast will move one and two steps it'll come back here to number two come back here to number two and slow will also move over here to and slow will also move over here to zero zero and then fast will again move two steps and then fast will again move two steps back to the minus four and slow will back to the minus four and slow will move here to the minus four move here to the minus four and when we get here if these two nodes and when we get here if these two nodes are equal are equal then we have a cycle and if they're then we have a cycle and if they're unequal then unequal then then there's not a cycle because they'll then there's not a cycle because they'll never actually cross each other never actually cross each other okay and so that's it that's how you okay and so that's it that's how you detect cycles in linked list detect cycles in linked list it's very simple you just want to use it's very simple you just want to use two pointers one fast and one two pointers one fast and one slow and if any time during that slow and if any time during that traversal as they're traversal as they're going through the the list two nodes going through the the list two nodes intersect intersect you you both those pointers point to the you you both those pointers point to the same node then we have a cycle same node then we have a cycle that is that that's where that cycle is that is that that's where that cycle is okay so let's go ahead and jump into the okay so let's go ahead and jump into the code okay so all we want to do here is we just go ahead and get a fast pointer and go ahead and set that to the head and we get a slow pointer and set that okay and now we just want to do while okay and now we just want to do while fast fast and fast dot next okay and now what we're going to do is uh we're just going to update fast and slow so fast is going to go fast dot next dot next and slow and if fast equals and if fast equals slow return true slow return true else we'll break out of this loop we'll else we'll break out of this loop we'll get to the end of the this the linked get to the end of the this the linked list list and we'll go ahead and return let's go ahead and run that and yeah let's go ahead and run that and yeah we're good we're good okay some things to think about here now okay some things to think about here now why fast fast dot next why fast fast dot next right this line right over here why do right this line right over here why do we have to do that we have to do that okay let's go ahead and jump back to the okay let's go ahead and jump back to the the whiteboard here so we need to make sure that we get to the end of the list and that every everything that we're that we're iterating over we don't have a null value on the next okay so let's say let's say we have here we have 1 2 3 4 5 and 6 right and this is going to point to null right and so now we're going to have a right and so now we're going to have a fast fast and a slow and so let's just kind of and a slow and so let's just kind of walk through this so walk through this so here fast is going to increment 2 and here fast is going to increment 2 and slow is going to increment 1. slow is going to increment 1. we're going to check does fat is fast we're going to check does fat is fast true and is fast dot next true true and is fast dot next true okay if they are go ahead and increment okay if they are go ahead and increment fast twice fast twice to the 5 5 place and increment slow ones to the 5 5 place and increment slow ones now we check is fast true and is fast now we check is fast true and is fast dot next true if it is then this dot next true if it is then this fast can increment to this null that's fast can increment to this null that's where it's going to be where it's going to be and then this slow we'll go ahead and and then this slow we'll go ahead and increment over here and then increment over here and then fast is not true and we can go ahead and fast is not true and we can go ahead and exit out of the loop exit out of the loop okay and so the reason we want to do okay and so the reason we want to do fastfast.next is that fastfast.next is that when we get to the next iteration we're when we get to the next iteration we're not calling fast not calling fast dot next on a null value that's that's dot next on a null value that's that's the main point of it because if we do it the main point of it because if we do it the other way the other way we're going to be calling fast dot next we're going to be calling fast dot next on null which will which will throw an on null which will which will throw an error error and so that's why we are on this line and so that's why we are on this line over here over here we're using while fast and fast dot next we're using while fast and fast dot next okay so just something important to okay so just something important to remember remember when you're when you're um doing using when you're when you're um doing using two pointers two pointers this is a pattern that you want to have this is a pattern that you want to have memorized you you want to just memorized you you want to just know this uh it's it's very common in a know this uh it's it's very common in a lot of linked list questions that you're lot of linked list questions that you're gonna have to traverse find a cycle gonna have to traverse find a cycle find the start of the cycle it just find the start of the cycle it just comes up all the time so comes up all the time so this particular pattern it's just you this particular pattern it's just you know it's probably good to just have it know it's probably good to just have it memorized that way when it comes up memorized that way when it comes up you don't have to think about it too you don't have to think about it too much much okay that is linked list 141 or that is okay that is linked list 141 or that is sleep code 141 sleep code 141 linked list cycle hope you enjoyed it linked list cycle hope you enjoyed it and i will see you on the next one
2024-03-21 12:31:55
141
https://i.ytimg.com/vi/w…axresdefault.jpg
LEETCODE 141 (JAVASCRIPT) | LINKED LIST CYCLE I
afTpieEZXck
hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve the problem binary tree let's solve the problem binary tree pre-order traversal we're given the root pre-order traversal we're given the root of a binary tree and we want to return of a binary tree and we want to return the pre-order traversal of all of its the pre-order traversal of all of its values so this is a really simple values so this is a really simple problem to solve if you're doing it problem to solve if you're doing it recursively it's kind of one of the recursively it's kind of one of the first algorithms that you learn when it first algorithms that you learn when it comes to Binary trees but solving this comes to Binary trees but solving this problem iteratively is a bit more problem iteratively is a bit more difficult and it's definitely useful to difficult and it's definitely useful to know especially for interviews so that's know especially for interviews so that's what we're going to be focusing on in what we're going to be focusing on in this video let's say we're given a this video let's say we're given a binary tree like this first of all what binary tree like this first of all what is the pre-order traversal well we're is the pre-order traversal well we're going to start at the root and pre-order going to start at the root and pre-order basically means that we're going to basically means that we're going to process this node AKA in this case add process this node AKA in this case add it to the array that we're trying to it to the array that we're trying to build we're going to do that first and build we're going to do that first and then we're going to recursively run then we're going to recursively run pre-order traversal on the left subtree pre-order traversal on the left subtree and then after that run pre-order and then after that run pre-order traversal on the right subtree so our traversal on the right subtree so our output would look look like this we output would look look like this we visited this then we'd go left we would visited this then we'd go left we would visit this so add 2 to the output array visit this so add 2 to the output array we'd try to go left at this point but we we'd try to go left at this point but we can't there's nothing there and then we can't there's nothing there and then we would recursively pop back up to our would recursively pop back up to our parent node and then try to go right parent node and then try to go right again we can't there's nothing there so again we can't there's nothing there so then from here we would pop back up to then from here we would pop back up to this parent node and then from here this parent node and then from here we're basically done running pre-order we're basically done running pre-order traversal so then we would pop back up traversal so then we would pop back up to the parent here and from here we know to the parent here and from here we know that we're done with the left side of that we're done with the left side of the tree and since it's pre-order we've the tree and since it's pre-order we've already done this node so then we'd already done this node so then we'd recursively run pre-order traversal here recursively run pre-order traversal here so we'd get to three we'd add 3 to the so we'd get to three we'd add 3 to the output then we'd go left add 4 to the output then we'd go left add 4 to the output try to go left can't do that try output try to go left can't do that try to go right can't do that pop back up to go right can't do that pop back up here then pop back up here then try to here then pop back up here then try to go right we'd add 5 to the out output go right we'd add 5 to the out output and then at this point we can't go left and then at this point we can't go left can't go right we'd pop back up and then can't go right we'd pop back up and then we'd say well we're done here because we we'd say well we're done here because we already went to both sides then pop back already went to both sides then pop back up here and we're done here because we up here and we're done here because we already did the left and right subtree already did the left and right subtree so then we'd basically be done so how do so then we'd basically be done so how do we take this solution and then emulate we take this solution and then emulate it iteratively well the main thing that it iteratively well the main thing that we need to do is we'll have a single we need to do is we'll have a single pointer that will tell us like what the pointer that will tell us like what the current node we're at is that's the easy current node we're at is that's the easy part but the hard part is after we go part but the hard part is after we go left or after we go right how do we go left or after we go right how do we go back up because there's not a pointer back up because there's not a pointer connecting a child node to its parent so connecting a child node to its parent so we kind of have to do that ourselves and we kind of have to do that ourselves and the easiest way to do it is with a stack the easiest way to do it is with a stack data structure and actually recursively data structure and actually recursively that's what the problem is doing well that's what the problem is doing well that's what our function recursively is that's what our function recursively is doing it's not explicitly creating a doing it's not explicitly creating a stack but there is an implicit stack aka stack but there is an implicit stack aka the recursive call stack so we're the recursive call stack so we're basically going to emulate this pretty basically going to emulate this pretty similarly so I'm going to go ahead and similarly so I'm going to go ahead and draw that out for you so this is our draw that out for you so this is our stack we're also going to have our stack we're also going to have our result that's also going to be an array result that's also going to be an array so now we start at the root we're so now we start at the root we're running pre-order we're going to take running pre-order we're going to take this value and append it to the result this value and append it to the result it's 1. now we want to go left but we it's 1. now we want to go left but we know that after we're done with this know that after we're done with this left subtree we're going to need to go left subtree we're going to need to go back up to the root so what should we do back up to the root so what should we do should we take this node and add it to should we take this node and add it to the stack let's just draw it like a node the stack let's just draw it like a node one and add it to the stack so that we one and add it to the stack so that we can pop back up to it that's definitely can pop back up to it that's definitely a valid way to do this but what I'm a valid way to do this but what I'm going to do is just skip that all going to do is just skip that all together I'm just going to take actually together I'm just going to take actually the right child of one and append that the right child of one and append that to the side because this is pre-order We to the side because this is pre-order We Know by the time we pop back up here Know by the time we pop back up here we've already added this to the result we've already added this to the result there's no need to visit this again why there's no need to visit this again why not just skip that step altogether and not just skip that step altogether and just add Its Right child to the stack just add Its Right child to the stack because we know by the time we're done because we know by the time we're done with this left subtree all we want to do with this left subtree all we want to do is do the right subtree next not the is do the right subtree next not the root so that's what I'm going to do here root so that's what I'm going to do here before we go left let's append three the before we go left let's append three the right child not the value we're gonna right child not the value we're gonna append the node because we want the append the node because we want the pointers as well I'm just writing out pointers as well I'm just writing out the value to make it simple I guess I the value to make it simple I guess I can put a circle around it if it makes can put a circle around it if it makes it more obvious but then we're going to it more obvious but then we're going to be at the left child over here so then be at the left child over here so then add 2 to the result now from here we're add 2 to the result now from here we're going to do the same thing even though going to do the same thing even though we don't know that the left child is we don't know that the left child is null or that the right child is null null or that the right child is null we're still going to follow the same we're still going to follow the same algorithm because it doesn't hurt us it algorithm because it doesn't hurt us it still works in this case so what we're still works in this case so what we're going to do here is before we go to the going to do here is before we go to the left child we're going to add the right left child we're going to add the right child to the stack even though it's null child to the stack even though it's null so I'm just going to draw an N to so I'm just going to draw an N to indicate that it's null and then we're indicate that it's null and then we're going to go left we're going to be here going to go left we're going to be here our pointer is going to be at a null our pointer is going to be at a null value there's not thing for us to do by value there's not thing for us to do by the time we get to a null value we know the time we get to a null value we know we can't go any further with pre-order we can't go any further with pre-order we're trying to go as far left as we we're trying to go as far left as we possibly can until we reach null and possibly can until we reach null and when we reach null that's the signal when we reach null that's the signal that we need to pop back up in this case that we need to pop back up in this case that's the signal that we need to pop that's the signal that we need to pop from our stack so I'm going to do from our stack so I'm going to do exactly that I'm going to pop the last exactly that I'm going to pop the last value from the stack which is null so value from the stack which is null so now our pointer is going to again be at now our pointer is going to again be at null so when our pointer is at null we null so when our pointer is at null we just pop from the stack so once again just pop from the stack so once again I'm going to pop now three from the I'm going to pop now three from the stack so that means now our current stack so that means now our current pointer is here at three so it's a pointer is here at three so it's a non-null node so we're going to add the non-null node so we're going to add the value 3 to the result now we're going to value 3 to the result now we're going to go left but before we go left make sure go left but before we go left make sure to add the right child to the stack so to add the right child to the stack so I'm going to add 5 to the stack and then I'm going to add 5 to the stack and then we're going to be at four we're going to we're going to be at four we're going to add 4 to the result we're going to try add 4 to the result we're going to try to go less but before we do that we're to go less but before we do that we're going to add null to the stack so I'm going to add null to the stack so I'm going to add a null value here we're going to add a null value here we're kind of running out of space but you kind of running out of space but you probably get the idea at this point now probably get the idea at this point now our current pointer is at null so we're our current pointer is at null so we're going to pop from the stack popping null going to pop from the stack popping null so now our current pointer is again at so now our current pointer is again at null so we're going to pop from the null so we're going to pop from the stack one more time popping five so now stack one more time popping five so now our current pointer is at five we're our current pointer is at five we're going to add five to the result and going to add five to the result and we're going to try to go left adding we're going to try to go left adding null to the stack and you probably get null to the stack and you probably get the idea at this point we're going to the idea at this point we're going to add null to the stack we're going to go add null to the stack we're going to go here to the left we're going to be at here to the left we're going to be at null we're going to end up popping that null we're going to end up popping that null from the stack and then at this null from the stack and then at this point our current pointer is going to be point our current pointer is going to be at null and our stack is going to be at null and our stack is going to be empty so if we try to pop from the stack empty so if we try to pop from the stack we can't pop anything that's the signal we can't pop anything that's the signal that we're done when our current pointer that we're done when our current pointer is null and the stack is empty so that's is null and the stack is empty so that's basically the algorithm you can see basically the algorithm you can see we're pretty much still visiting each we're pretty much still visiting each node twice we are kind of visiting some node twice we are kind of visiting some null nodes but that's not going to null nodes but that's not going to change the over overall time complexity change the over overall time complexity this is still going to be Big O of n this is still going to be Big O of n time complexity we visit each node once time complexity we visit each node once and we do have extra memory for the and we do have extra memory for the stack which is basically going to be the stack which is basically going to be the height of the binary tree which in the height of the binary tree which in the worst case could be Big O of n or if worst case could be Big O of n or if it's a balanced binary tree it could be it's a balanced binary tree it could be log n so now let's code this up so what log n so now let's code this up so what I'm going to do first is initialize our I'm going to do first is initialize our current pointer and initialize our stack current pointer and initialize our stack the current pointer is initially just the current pointer is initially just going to be pointing at the root pretty going to be pointing at the root pretty simple and the stack is going to simple and the stack is going to initially be an empty array we're also initially be an empty array we're also going to have our result which is also going to have our result which is also initially going to be an empty array and initially going to be an empty array and as we talked about we're going to as we talked about we're going to iterate until our current pointer is iterate until our current pointer is non-null or our stack is non-null so non-null or our stack is non-null so then we have two choices either our then we have two choices either our current node is null or it's non-null if current node is null or it's non-null if it's non-null then that's kind of the it's non-null then that's kind of the case where we're going to take the value case where we're going to take the value and append it to the the results so and append it to the the results so current dot value append it to the current dot value append it to the result we also then want to move left we result we also then want to move left we want to say current is going to be equal want to say current is going to be equal to current dot left but before we do to current dot left but before we do this we know we have to save the right this we know we have to save the right child on the stack because we need to child on the stack because we need to get back to it so here I'm going to say get back to it so here I'm going to say stack dot append current dot right the stack dot append current dot right the right node actually not the value but right node actually not the value but this could be null and that's not a this could be null and that's not a problem as I kind of showed in the problem as I kind of showed in the drawing explanation but the other case drawing explanation but the other case is if our current node yes is null then is if our current node yes is null then what do we want to do well first we want what do we want to do well first we want to pop from the stack and then assign to pop from the stack and then assign that to be current and then what would that to be current and then what would we want to do well we would basically we want to do well we would basically want to check again is that node want to check again is that node non-null if it isn't then we're going to non-null if it isn't then we're going to move left and add it to the result and move left and add it to the result and also add Its Right child to the stack so also add Its Right child to the stack so basically we don't need to take this basically we don't need to take this code and copy and paste it down here code and copy and paste it down here because this Loop is going to run again because this Loop is going to run again as long as this node is non or our stack as long as this node is non or our stack is non-empty that means there's still is non-empty that means there's still nodes to visit so we don't need to copy nodes to visit so we don't need to copy and paste this we know the next and paste this we know the next iteration of the loop is going to handle iteration of the loop is going to handle that for us but if the what we popped is that for us but if the what we popped is null then we're just gonna have to pop null then we're just gonna have to pop again nothing wrong with that so after again nothing wrong with that so after all that's done we're going to go ahead all that's done we're going to go ahead and return our result so now let's run and return our result so now let's run this to make sure that it works and as this to make sure that it works and as you can see yes it does it's pretty you can see yes it does it's pretty efficient if this was helpful please efficient if this was helpful please like And subscribe if you're preparing like And subscribe if you're preparing for coding interviews check out for coding interviews check out neatco.io it has a ton of free resources neatco.io it has a ton of free resources to help you prepare thanks for watching to help you prepare thanks for watching and hopefully I'll see you pretty soon
2024-03-21 12:43:31
144
https://i.ytimg.com/vi_w…xresdefault.webp
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
MJp_5rReEnU
hello friends I hope you and all your near and dear ones are safe and Hildy near and dear ones are safe and Hildy these are difficult and unprecedented these are difficult and unprecedented times and among all the talks times and among all the talks discussions and panic around Cove in discussions and panic around Cove in nineteen I think the best I can do for nineteen I think the best I can do for you right now is to create a peaceful you right now is to create a peaceful state of mind through distraction via state of mind through distraction via education so over the next eight to ten education so over the next eight to ten minutes let's zero in on another lead minutes let's zero in on another lead code problem called Ilario cash this is code problem called Ilario cash this is a frequently asked question by Amazon a frequently asked question by Amazon Google Facebook Microsoft and quite a Google Facebook Microsoft and quite a few other companies I'm sure most of you few other companies I'm sure most of you who are watching this video would be who are watching this video would be familiar with how elodie cash works but familiar with how elodie cash works but let's quickly spend a couple of moments let's quickly spend a couple of moments to understand about it so to start with to understand about it so to start with a cash is a small amount of memory it a cash is a small amount of memory it can either be hardware or software can either be hardware or software component that stores data so that component that stores data so that future requests for the data can be future requests for the data can be processed faster now due to the limited processed faster now due to the limited size of the cache when this memory is size of the cache when this memory is fully utilized we need efficient fully utilized we need efficient eviction techniques so as to accommodate eviction techniques so as to accommodate new data new data one such cache eviction technique is LRU one such cache eviction technique is LRU which stands for least recently used as which stands for least recently used as the name suggests in this policy the the name suggests in this policy the least recently used items are evicted least recently used items are evicted from the cache when the cache is fully from the cache when the cache is fully let's go through the problem description let's go through the problem description design and implement a data structure design and implement a data structure for least recently used cache it should for least recently used cache it should support the following operations get support the following operations get input gate key will return the value of input gate key will return the value of the key of the key exists in the cache the key of the key exists in the cache otherwise it will return -1 what key otherwise it will return -1 what key value will set or insert the value of value will set or insert the value of the key is already not present when the the key is already not present when the cache has reached its maximum capacity cache has reached its maximum capacity it should invalidate the least recently it should invalidate the least recently used item before inserting a new item used item before inserting a new item now let's go through this example so we now let's go through this example so we are - with the given capacity of 2 and are - with the given capacity of 2 and then we have a set of instructions let's then we have a set of instructions let's you know what try to understand it more you know what try to understand it more pictorially pictorially our first instruction as cash got put 1 our first instruction as cash got put 1 comma 1 so since the cache is empty we comma 1 so since the cache is empty we can just insert this element next we do can just insert this element next we do a cache got put 2 comma 2 since there is a cache got put 2 comma 2 since there is still room for one item in the cache we still room for one item in the cache we can simply insert it and update the can simply insert it and update the position so now 2 comma 2 is the most position so now 2 comma 2 is the most recently used and 1 comma 1 is the least recently used and 1 comma 1 is the least recently used next we try to fetch one recently used next we try to fetch one from the cache so we do a cache not get from the cache so we do a cache not get one now we return the value 1 and also one now we return the value 1 and also update the position of 1 comma 1 in the update the position of 1 comma 1 in the cache cache since now 1 comma 1 is most recently since now 1 comma 1 is most recently used so 2 comma 2 now becomes the least used so 2 comma 2 now becomes the least recently used item next we get 3 comma 3 recently used item next we get 3 comma 3 now we will have to edit now we will have to edit 2 since the cache is already at its 2 since the cache is already at its capacity and 2 comma 2 is the least capacity and 2 comma 2 is the least recently used item will evict 2 comma 2 recently used item will evict 2 comma 2 and also update the position of 3 comma and also update the position of 3 comma 3 next we do a cash market - since the 3 next we do a cash market - since the item is not present in the cache we item is not present in the cache we simply return a minus 1 then we have to simply return a minus 1 then we have to insert the element 4 again we find that insert the element 4 again we find that the cache is at its full capacity so the cache is at its full capacity so we'll have to remove an item which is we'll have to remove an item which is least recently used least recently used in this case it is 1 comma 1 so we in this case it is 1 comma 1 so we remove it and also update the position remove it and also update the position so that 4 comma 4 is the most recently so that 4 comma 4 is the most recently used and 3 comma 3 is the least recently used and 3 comma 3 is the least recently used next we do a cache dot get 1 and used next we do a cache dot get 1 and return -1 since item is not found next return -1 since item is not found next we do a cache not get 3 again if you see we do a cache not get 3 again if you see we have updated the position of 3 comma we have updated the position of 3 comma 3 now since 3 comma 3 is the most 3 now since 3 comma 3 is the most recently used and foe come of or becomes recently used and foe come of or becomes the least recently used here next we do the least recently used here next we do a cache target 4 so again we'll have to a cache target 4 so again we'll have to update the position of 4 comma 4 and update the position of 4 comma 4 and make it the most recently used and make it the most recently used and similarly make 3 comma 3 the least similarly make 3 comma 3 the least recently used and return the item 4 recently used and return the item 4 comma 4 so let's think about our data comma 4 so let's think about our data structured first before moving on to the structured first before moving on to the code so since we have seen that we have code so since we have seen that we have key value pairs in the cache we'll need key value pairs in the cache we'll need some sort of a hash map which can some sort of a hash map which can retrieve the values pretty quickly given retrieve the values pretty quickly given a key but the only problem with the hash a key but the only problem with the hash map is it is unordered but here we need map is it is unordered but here we need to form some sort of ordering so that we to form some sort of ordering so that we can always get the least recently used can always get the least recently used item from the cache in constant time so item from the cache in constant time so for that we can use a linked hash map for that we can use a linked hash map which will solve both the purpose of a which will solve both the purpose of a hash map and a list which will give us hash map and a list which will give us ordered elements so let's try to write ordered elements so let's try to write the code now so we'll have to define two the code now so we'll have to define two variables when that holds the capacity variables when that holds the capacity of the cache so it is in the capacity of the cache so it is in the capacity next we'll define a linked hash map next we'll define a linked hash map and it will hold integer command issued and it will hold integer command issued since both the key and values are since both the key and values are integers integers now let's initialize the constructor so now let's initialize the constructor so this dot capacity is equal to capacity this dot capacity is equal to capacity and we'll initialize the map to a new and we'll initialize the map to a new length hash map here and we provide capacity which will determine the size of the harsh map now let's try to implement the gate key function so as we have seen if the key already exists in them hash map so it is map got contains key then what all we have to do is first get the object from the cache update its order in the cache and then return the value so for that we can write int value is equal to map dot gate key will do I put key comma value this will update the position of the item in the cache and finally once this is done we just may put return this value now let's say if the item is not found in the cache then we just need to return a minus 1 let's try to implement the put function so if the item is already present in the map we'll have to update the position so as to make it the most recently used so then let's remove this key from the map then let's remove this key from the map and again will be inserted so as to and again will be inserted so as to update the position else if the map has update the position else if the map has already reached its capacity then we'll already reached its capacity then we'll write a check for that write a check for that so if map dot size is equal to equal to so if map dot size is equal to equal to capacity then we will just iterate over capacity then we will just iterate over the map and remove the least recently the map and remove the least recently used item so how do we do that let's used item so how do we do that let's define an iterator of integers SMAP not define an iterator of integers SMAP not is it not iterator is it not iterator now if you haven't used the iterator now if you haven't used the iterator before I provided a link in the before I provided a link in the description you can read more about it description you can read more about it so whenever we have to remove an item so whenever we have to remove an item from the iterator we need to call from the iterator we need to call iterator dot next and only after that we iterator dot next and only after that we can call iterators remove method so we can call iterators remove method so we write IT dot next then then we call I T write IT dot next then then we call I T dot remove so this will remove the dot remove so this will remove the current element which is also the least current element which is also the least frequently used element once we are all frequently used element once we are all done with this the only thing remaining done with this the only thing remaining right now is to actually insert the right now is to actually insert the element into the linked hash map so when element into the linked hash map so when I eat mom dot put e comma value and we I eat mom dot put e comma value and we are done let's try to run it are done let's try to run it it works let's submit it it works let's submit it great so it's accepted hope you continue great so it's accepted hope you continue watching my videos please subscribe to watching my videos please subscribe to the channel like this video and leave the channel like this video and leave your feedback thank you
2024-03-21 12:52:55
146
https://i.ytimg.com/vi/M…axresdefault.jpg
Leetcode 146: LRU Cache
_bGRNR3D92s
welcome back to algojs today's question is leak code79 word search is leak code79 word search so given an m by n grid of characters so given an m by n grid of characters board and a string word return true if board and a string word return true if word exists in the grid word exists in the grid the word can be constructed from letters the word can be constructed from letters of sequentially adjacent cells where of sequentially adjacent cells where adjacent cells are horizontally or adjacent cells are horizontally or vertically neighboring the same letter vertically neighboring the same letter cell may not be used more than once so cell may not be used more than once so in example one we have this board in example one we have this board we are looking for the word abc ced we are looking for the word abc ced as you can see this can be found within as you can see this can be found within the board so we need to return true in the board so we need to return true in the second example we have c as the word the second example we have c as the word which is in the board and lastly in which is in the board and lastly in example three we have the word abcb example three we have the word abcb which is not in the board so we return which is not in the board so we return false so with this question uh we are false so with this question uh we are going to be utilizing a dfs recursive going to be utilizing a dfs recursive solution because we need to check all solution because we need to check all possible solutions within this board possible solutions within this board to find if it potentially holds the word to find if it potentially holds the word so how would we do that well we'd start so how would we do that well we'd start off at the first position we'd loop off at the first position we'd loop through this entire board and we checked through this entire board and we checked to see whether we have this letter at to see whether we have this letter at the position we're on if we do then we the position we're on if we do then we can start a search so we can start the can start a search so we can start the dfs recursive call and check the next dfs recursive call and check the next letter in word and also traverse through letter in word and also traverse through this board so we need to check all this board so we need to check all positions so we need to go positions so we need to go right down right down left and up and this would be a good left and up and this would be a good idea to suggest that we need to have idea to suggest that we need to have some kind of inbound function or just an some kind of inbound function or just an if statement that says if columns is if statement that says if columns is less than zero less than zero or rows is less than zero or rows is or rows is less than zero or rows is greater than greater than board dot length or columns is greater than board zero dot length then it's out of bounds right so this would be too far over this way row is less than zero will be up here column less than zero will be over here and rho is greater than board.length will be too far down this way so we've checked all directions to see if it's inbound so moving from a we can't go here because it's out of bound we can't go here because it's out of bound we can move either to s or b if we move to s s does not equal the next letter within the word that we're looking for so we can't go down that path we have b here so we can start the dfs function on this and then we repeat the process so we check all our potential solutions check whether they're inbound so here we have an issue right because we're going to be going back to the previous value which we've already checked so this has been checked we don't need to go back to it so in this case we could use something like a set to store all the letters we visited or we could simply change this to a value like a hash okay so we exclude it from the board now by adding this hash so there's no point in going back that way so we can't go this way we don't go this way because the next value in the word is not equal to f so we go to c which is the next value b has now been seen okay so we can update b with hash we do the same with c we check all directions we move to the next position which is we move to e repeat the process and we move to d now at d so we've checked checked checked now at d so we've reached the end of word so the position we're on say the index which we could keep track of is equal to word dot length minus one and if that is the case we can return true so we'll return true at the stack all the way up until we get back to the original position so true will be returned from here here here here here and lastly here so this will hop out of the dfs recursive call stack we'll have true as our answer and then we can just return that boolean so time complexity is o we have to traverse the board so we're using a recursive call stack so that's going to be of n operations the difficult part is in the first iteration we can go in four different directions right but moving along we can only choose three other possible directions right so we've got these three we can't go back to the previous one because we've already looked at that so we have three potential solutions so that would be 3 to the power of l where l is the length of this word so it is going to be of exponential time complexity so to begin with we can start off by creating the loop through the board and check to see whether we have the initial letter that's in word so that i equals zero r is less than board dot length r plus plus so we're looking through the rows here and then we're going to loop through the columns as well so c is less and if board at rc and if board at rc is equal to word zero then run this dfs function which we're going to create and pass in the row the column and 0 for the index now if this returns true then we can return true from this else we need to return false okay so now we can create the dfs function so dfs takes in row column and index if word dot length is equal to i we can return true because we've reached the end of the word and we found all of the letters within the board we need to carry out the inbound check so if rho is greater than or equal to all rows less than zero all rows less than zero or column is less than zero board zero dot length board zero dot length and finally we need to check if the and finally we need to check if the board at r board at r c c does not equal does not equal word i so when we start recursing word i so when we start recursing through we're going to check all four through we're going to check all four positions or after the initial we're positions or after the initial we're going to check all three positions and going to check all three positions and if the letter at the current position in if the letter at the current position in the board does not equal the board does not equal the letter in word the letter in word then we can return false so before we carry out the recursion we need to set border rc has visited and the way we'll do this is by setting border rc to a hash and now we can carry out the recursion so if dfs are plus one c i plus one so we need to increment row or so we need to traverse all four or so we need to traverse all four directions so directions so r minus one r minus one c plus one c minus one and if one of these positions returns true then we can return true finally within this dfs function we need to reset the border rc to equal word i and that's it for this code let's give it run and there you have it
2024-03-20 12:03:09
79
https://i.ytimg.com/vi/_…axresdefault.jpg
Word Search - LeetCode 79 - JavaScript
FnLiFGuoQkM
hey hey everybody this is larry this is day 16 of the february code daily day 16 of the february code daily challenge challenge uh hit the like button hit the subscribe uh hit the like button hit the subscribe button join me on discord let me know button join me on discord let me know what you think about today's prom what you think about today's prom ladder case permutation so i usually ladder case permutation so i usually solve these live or attempt to and solve these live or attempt to and i go for my thought process but i'm and i go for my thought process but i'm and i i just woke up so i may be a little i i just woke up so i may be a little bit slow so feel free to fast forward bit slow so feel free to fast forward skip ahead whatever you need skip ahead whatever you need so today's problem is ladder case so today's problem is ladder case permutation so given s permutation so given s we can transform every letter we can transform every letter individually or lowercase to create individually or lowercase to create another string another string um okay so yeah so i think the thing you need to are been given okay so you you so one are been given okay so you you so one thing that i notice in the thing that i notice in the test cases is that they don't give you test cases is that they don't give you the upper case characters the upper case characters but so if they give it to you you have but so if they give it to you you have to fix that case but to fix that case but in any case what you need for this in any case what you need for this problem is something called a power set problem is something called a power set put it here for now uh and the way you put it here for now uh and the way you use it use it is just that for every uh is just that for every uh every very lead every very lead letter um you just choose whether it's letter um you just choose whether it's uppercase or lowercase uppercase or lowercase and that's pretty much it um so the way and that's pretty much it um so the way that i that i often do it is that i i try to avoid often do it is that i i try to avoid recursion because recursion because i don't know i think it's just a force i don't know i think it's just a force of habit because python is a little bit of habit because python is a little bit slow slow uh but so i do uh but so i do you know because we just took take you know because we just took take advantage of power set we advantage of power set we we can use the bit mask way of doing we can use the bit mask way of doing power set but today power set but today because of that i want to try something because of that i want to try something new and then i'll just do it recursively new and then i'll just do it recursively um um and and that should be good and because and and that should be good and because we can return the up in any order we can return the up in any order uh though i think try to store it in uh though i think try to store it in in uh in alphabet order right in in uh in alphabet order right in lexographic lexographic order because why not so here so let's order because why not so here so let's get started this is just get started this is just um brute force and there's no better way um brute force and there's no better way to do it because you have to ch to do it because you have to ch because you have to output every because you have to output every possibility that means that you can only possibility that means that you can only generate them for proof first because generate them for proof first because that's the lower bandwidth of your um that's the lower bandwidth of your um complexity right complexity right so so because of that you know because so so because of that you know because it is good for us i don't worry about it is good for us i don't worry about um i don't worry about um i don't worry about complexity as much um i mean i worry complexity as much um i mean i worry about it but i know that about it but i know that if i do brute force in an intelligent if i do brute force in an intelligent enough way it's not enough way it's not going to be you know too slow um and going to be you know too slow um and also also n is 12 right so so 2 to the 12 n is 12 right so so 2 to the 12 times 12 it's going to be fast enough so times 12 it's going to be fast enough so yeah so let's kind of go yeah so let's kind of go do that let's see how do i so do that let's see how do i so depending on how you want to write the depending on how you want to write the recursion there are different ways and i recursion there are different ways and i think this is a good practice think this is a good practice for for um for like dynamic programming and stuff like that where you know maybe one way to do it is just take the pre uh the suffix of s right so that you know maybe you can have current string or something like that and then and then here in the in the body of the function you would write something like if the first character of string is you know if this is alphabet or something like that right um but and a good practice in general is to convert this into something that's takes less space and something that is you know because this is this s string isn't going to change and we don't want to change it um and actually we have to put another one for existing but what i'm saying is that you could use the index instead um but you also still need the ongoing uh string and here we're going to use the um let's just say current um and we we want the current to be in a way cone is an array and the reason why we want it to be array is so that it doesn't i think it's slightly more efficient um but given that s as you go to 12 maybe it doesn't matter that much in the sense that you know in a lot of languages if you do if you can candidate 10 times you create 10 strings for example um so i some so i try to avoid that um but maybe for now it doesn't matter so let's just keep it a string and then we need to optimize for optimize but i want to keep it you know keep it uh what's it going keep it stupid symbol symbol stupid something like that so just try to do it as as much as i can um that set n is equal to length of s i that set n is equal to length of s i always do this so that i don't have to always do this so that i don't have to write as much and also because it's a write as much and also because it's a function in python so function in python so uh if you do it a billion times it uh if you do it a billion times it actually does make a difference actually does make a difference but if index is equal to n then we just but if index is equal to n then we just return because we don't have any return because we don't have any characters left in the string characters left in the string otherwise we otherwise we [Music] [Music] um okay so if um okay so if also i want just to keep it off uh in also i want just to keep it off uh in lexographic order we can lower this to lexographic order we can lower this to lower lower something like that is it too low or low something like that is it too low or low to lower case to lower case i always forget the python does have i always forget the python does have this function this function so yeah okay so it doesn't complain so so yeah okay so it doesn't complain so that's that's a good sign and then a good sign and then if s of index i think this if s of index i think this call is alpha maybe i'm well let's call is alpha maybe i'm well let's return return let me run it again let me run it again i don't know so we will generate okay so it does okay i i forget the name okay so it does okay i i forget the name of these functions i would have to of these functions i would have to google it that's why i wanted just to google it that's why i wanted just to make sure yeah uh if this is alpha then we generate index plus one current plus sub index we also want to generate the uh what's we also want to generate the uh what's required required the uppercase version and in theory because we already did a lower this should already be lowered but i just want to keep it this way for symmetry so that i don't uh because sometimes you outsmart yourself and you get confused when you have to go debugging um and for now i'm going to keep it like this so that you know these two lines and when i say symmetry i mean that these two lines should look very similar and the same um and i keep it in there as long as i can pretty much um otherwise this is a number so let me just do this but i haven't yeah oh i forgot to actually put in the array oh i forgot to actually put in the array which is what we do at the very end which is what we do at the very end so yeah answer that append uh and that should be good uh i think we can test a couple more but i am confident ish oh and i think we want to add one more where the input is in uppercase because that's not one of the inputs as we talked about one two three four five and zero okay fine cool um this looks good it feels good so let's give it a submit again this is going to be you know before so it's n times n factorial which is um you know for n is equal to 12 is fast enough in terms of space is also 12 factorial or n factorial or at 12 factorial which is fast enough because that's the size of the output and you can really do better right um because yeah so time is equal to n times n factorial why is it end times yeah why is it end times yeah and the n comes from the fact that um and the n comes from the fact that um well the n factorial comes from the fact well the n factorial comes from the fact that when we that when we wait no i'm thinking of something else wait no i'm thinking of something else sorry i meant two to the end wow i am sorry i meant two to the end wow i am sorry i just woke up and i i sorry i just woke up and i i got a little bit confused about because got a little bit confused about because i i was talking about brute force i i was talking about brute force and i read permutation and i think i and i read permutation and i think i this is a way this is a way and when you think but when you see the and when you think but when you see the word permutation you always think about word permutation you always think about like n factorial as one of the things like n factorial as one of the things and i think i just got a little bit and i think i just got a little bit um i think i got a little bit mixed up um i think i got a little bit mixed up sorry about that sorry about that i don't mean to confuse anyone i really i don't mean to confuse anyone i really don't but it's two to the end because don't but it's two to the end because um you can imagine a word where there's um you can imagine a word where there's no numbers then we branch out no numbers then we branch out twice for every um every character and twice for every um every character and then at the very end then at the very end we have to append it to the answer we have to append it to the answer string which is string which is the number of characters like this this the number of characters like this this takes all of n times if you want to call takes all of n times if you want to call it that because it that because uh because copying this string into uh because copying this string into because the string is of n length and because the string is of n length and therefore therefore copying it into answer will be all of n copying it into answer will be all of n times right times right um and then the space is just over um and then the space is just over two to the n because two to the n because yeah because you that's the size of the yeah because you that's the size of the output you can't do any better output you can't do any better um because literally um because literally you have to return that many items right you have to return that many items right uh and also i guess uh and also i guess you want to be more precise given that you want to be more precise given that now we do it it's actually n times 2 to now we do it it's actually n times 2 to the n if you want to call it that as the n if you want to call it that as well well because um i guess yeah maybe that's a because um i guess yeah maybe that's a better position because better position because this two to the n strings each string is this two to the n strings each string is length n so it's n times 2 to the n length n so it's n times 2 to the n i just want to be really clear because i just want to be really clear because sometimes i i would say sometimes i i would say um i definitely mix these up sometimes um i definitely mix these up sometimes um where i'm um where i'm inconsistent from time to time but inconsistent from time to time but that's my bad uh thanks for commenters that's my bad uh thanks for commenters for catching me when i do do that for catching me when i do do that so um so now i'm trying to be a little so um so now i'm trying to be a little bit better so you know i'm learning a bit better so you know i'm learning a little bit as well little bit as well okay but yeah um that's all i have this okay but yeah um that's all i have this is you know i'm trying to keep is you know i'm trying to keep uh i think this code is about you know uh i think this code is about you know without some comments and spaces about without some comments and spaces about like 15 lines of code and i think like 15 lines of code and i think you know this is as simple as i could you know this is as simple as i could want it to be want it to be so yeah i think one time i i don't know so yeah i think one time i i don't know if it's this particular problem if it's this particular problem but it was a similar problem during a but it was a similar problem during a contest where i forgot about the contest where i forgot about the lowercase lowercase um i forgot about the uppercase um i forgot about the uppercase and i i changed it to here and i i changed it to here and it doesn't change the assign to and it doesn't change the assign to submit it again for another five minute submit it again for another five minute penalty that was kind of sad penalty that was kind of sad uh i do remember that though um it was a uh i do remember that though um it was a similar as i did this problem with similar as i did this problem with similar problem but yeah similar problem but yeah uh that's all i have for this farm uh that's all i have for this farm though let me know what you think hit though let me know what you think hit the like button hit the subscriber and the like button hit the subscriber and drum and discord drum and discord and but if you don't that's fine but you and but if you don't that's fine but you know know you take care take care of others if you you take care take care of others if you can can stay good stay well um stay healthy stay good stay well um stay healthy and to good mental health i'll see you and to good mental health i'll see you next time bye
2024-03-21 16:45:26
784
https://i.ytimg.com/vi/F…axresdefault.jpg
784. Letter Case Permutation - Day 16/28 Leetcode February Challenge
wR09VzzvwcU
so we need to check whether sentence is pan gram or not this is an easy level pan gram or not this is an easy level problem and we will understand step by problem and we will understand step by step how we can solve this question also step how we can solve this question also uh before moving forward if you haven't uh before moving forward if you haven't subscribed to this channel make sure to subscribed to this channel make sure to subscribe to learn about Pro for regular subscribe to learn about Pro for regular liquid videos like this liquid videos like this [Music] [Music] the question uh first discussed about the question uh first discussed about the panchrom is the pan grum is the panchrom is the pan grum is basically a sentence of where every basically a sentence of where every letter of the English alphabet appears letter of the English alphabet appears at least once fine so uh it's like uh at least once fine so uh it's like uh it's it's compulsory that every letter it's it's compulsory that every letter should appear at least one so that's should appear at least one so that's what necessary now uh if we just look what necessary now uh if we just look carefully this is a sentence given to us carefully this is a sentence given to us fine fine this is the one you know that the quick this is the one you know that the quick brown frogs jumps over the let's talk so brown frogs jumps over the let's talk so this is a sentence and this sentence you this is a sentence and this sentence you will find it true because you'll find will find it true because you'll find every letter of our English alphabet every letter of our English alphabet from a till z everyone is there at least from a till z everyone is there at least once like there's one time we will find once like there's one time we will find it here fine it here fine so the sentence like this at least one so the sentence like this at least one of the every letters so uh the other of the every letters so uh the other case is like lead code if we are given case is like lead code if we are given this is the false because it's not uh to this is the false because it's not uh to that point okay it's not there whether that point okay it's not there whether everyone is there or not fine so uh our everyone is there or not fine so uh our main target is to find out if uh there's main target is to find out if uh there's like a uh if related is there at least like a uh if related is there at least once right the question for this is like once right the question for this is like we are given the string sentence we are given the string sentence containing only in lowercase English containing only in lowercase English letters so everything is lowercase letters so everything is lowercase written true if the sentence is a written true if the sentence is a paragraph or other response so is a paragraph or other response so is a pretty simple question so you need to pretty simple question so you need to check for that now what should your check for that now what should your approach to this question the first approach to this question the first approach that must come to your mind as approach that must come to your mind as a uh array based approach what is that a uh array based approach what is that you create an array of size 26 fine and you create an array of size 26 fine and initially you know the array uh default initially you know the array uh default values are zero uh make it an entire and values are zero uh make it an entire and then for each of the characters users do then for each of the characters users do like uh or the character minus um this a like uh or the character minus um this a okay so whenever you do something like okay so whenever you do something like this okay so you do something like this this okay so you do something like this this returns your index or a number so this returns your index or a number so how to work say this is the character of how to work say this is the character of that um a sentence how to find out it's that um a sentence how to find out it's like uh B fine so what is happening so B like uh B fine so what is happening so B uh minus a so this happens and with that uh minus a so this happens and with that case we will return it uh so B is uh 90 case we will return it uh so B is uh 90 uh 98 okay p is 98 and uh in terms of uh 98 okay p is 98 and uh in terms of that a is 97 so you will find one as the that a is 97 so you will find one as the answer fine so that's what you will find answer fine so that's what you will find out of it now out of it now uh this is the first thing this uh that uh this is the first thing this uh that it was and that's one big the index of it was and that's one big the index of that make it a 26 uh letter uh array and that make it a 26 uh letter uh array and then you find the index out of it and then you find the index out of it and then put the index and uh just keep then put the index and uh just keep adding to the particular index like adding to the particular index like incrementing the index so at the end incrementing the index so at the end once the sentence is over you just once the sentence is over you just Traverse through that whole uh array and Traverse through that whole uh array and find out if any character remains 0 find out if any character remains 0 there is not a paragram as if the whole there is not a paragram as if the whole array gets over and all characters have array gets over and all characters have some other at least one value so it's a some other at least one value so it's a pattern so that's our basic idea you can pattern so that's our basic idea you can do now to improve that what you can do do now to improve that what you can do you can actually shift this like uh not you can actually shift this like uh not using array rather use a map or set in using array rather use a map or set in that uh you just uh like keep on adding that uh you just uh like keep on adding all the valves in the set fine so at the all the valves in the set fine so at the end you just check whether the state end you just check whether the state size is 26 or not fine so that's a size is 26 or not fine so that's a pretty much easy but the exact size is pretty much easy but the exact size is simply return as that so these are like simply return as that so these are like two ways that you can do but there is two ways that you can do but there is another way uh which you should learn another way uh which you should learn okay uh these are the ways you uh can okay uh these are the ways you uh can come up easily but maybe if the come up easily but maybe if the interface is not looking for these are interface is not looking for these are the ways to can you improve it further the ways to can you improve it further so what you can do is like use a bit so what you can do is like use a bit wise uh approach okay like uh in bits wise uh approach okay like uh in bits use this and that approach will be use this and that approach will be helpful for us so how uh we'll go ahead helpful for us so how uh we'll go ahead with that the first thing we will do is with that the first thing we will do is like uh this particular concept that I like uh this particular concept that I explained it to here that this will be explained it to here that this will be helpful okay this will use that so what helpful okay this will use that so what we'll actually do we'll actually do we will uh we keep a like a in type uh we will uh we keep a like a in type uh okay in type uh screen variable or a okay in type uh screen variable or a variable that will help us to know variable that will help us to know whether we have seen a particular number whether we have seen a particular number or not fine uh fine that will do and or not fine uh fine that will do and then we will continuously uh lab shift then we will continuously uh lab shift our uh value so whatever this uh value our uh value so whatever this uh value we are coming up like uh C minus a this we are coming up like uh C minus a this particular for each character we're particular for each character we're doing this so whatever this value we are doing this so whatever this value we are coming up we'll do a left shift of how coming up we'll do a left shift of how many times we'll do something like one many times we'll do something like one left shift uh this say say this value left shift uh this say say this value being uh C1 or something like the CI so being uh C1 or something like the CI so we'll continuously do a left shift of we'll continuously do a left shift of this so what will happen this so what will happen say there's uh uh B like the character say there's uh uh B like the character is B so it comes a one so the value will is B so it comes a one so the value will ultimately come up to something uh like ultimately come up to something uh like it will be one zero okay so that that's it will be one zero okay so that that's a value we'll be looking for because a value we'll be looking for because that's a b uh like if it is B so that n that's a b uh like if it is B so that n value will be something like one zero value will be something like one zero fine because that's one shift being fine because that's one shift being moved if it was a so it is being 0 1 moved if it was a so it is being 0 1 okay for C it will be 100 one zero zero okay for C it will be 100 one zero zero so you can see that like the characters so you can see that like the characters are like uh not at the same place so at are like uh not at the same place so at the end like at the end of the the end like at the end of the traversing the whole sentence you should traversing the whole sentence you should have 26 once okay you should have 26 have 26 once okay you should have 26 once 26 times fine that should be there once 26 times fine that should be there in your uh like after doing that after in your uh like after doing that after doing each of the left shift fine now doing each of the left shift fine now what exactly we are doing at the last we what exactly we are doing at the last we will simply do uh we'll simply check if will simply do uh we'll simply check if uh if uh we do a one left shift 26 fine uh if uh we do a one left shift 26 fine we'll do a one left shift 26 we'll do a one left shift 26 and we'll check whether this one lap and we'll check whether this one lap shift 26 is equal to this particular shift 26 is equal to this particular value that will come up okay this value that will come up okay this particular value that will come up it particular value that will come up it should be 26 once so if this particular should be 26 once so if this particular Value Plus 1 okay what will happen uh Value Plus 1 okay what will happen uh everything is one and when you plus one everything is one and when you plus one to it it will be like 27 bit will be one to it it will be like 27 bit will be one and then 26 zeros will be there okay so and then 26 zeros will be there okay so that will become so we'll take one left that will become so we'll take one left ship 26 will again be that exact thing ship 26 will again be that exact thing for 27th bit will be one and there is for 27th bit will be one and there is like 26 zeros how why is it so remember like 26 zeros how why is it so remember when you had to be that is one over here when you had to be that is one over here okay when you left shift uh like uh one okay when you left shift uh like uh one left shift this B that comes up to be left shift this B that comes up to be something like this that is uh second something like this that is uh second bit is one and the first there are like bit is one and the first there are like one zeros are there fine one zeros are there fine that's what it is so how whatever the that's what it is so how whatever the left shift is like how my baseball left shift is like how my baseball laptop it basically means there will be laptop it basically means there will be that much zeros at the end fine so this that much zeros at the end fine so this is the idea so it should to be like 26 is the idea so it should to be like 26 zeros at the end and also 26 bit zeros at the end and also 26 bit characters plus one like all the 26 ones characters plus one like all the 26 ones and rate of one like if you add a 1 to and rate of one like if you add a 1 to it it should result in again the same it it should result in again the same thing so that's the pretty much check we thing so that's the pretty much check we can do so what's the Improvement we come can do so what's the Improvement we come up over here why up over here why now firstly when we are using arrays as now firstly when we are using arrays as a example in that case we didn't have a example in that case we didn't have like uh we have to Traverse the whole like uh we have to Traverse the whole sentence and then we have to Traverse sentence and then we have to Traverse again 26 letters array to find out if again 26 letters array to find out if there's a Mystic or not so it's like there's a Mystic or not so it's like going into like order of n uh in being going into like order of n uh in being the length of the array to twice or the length of the array to twice or Thrive like at least twice you are going Thrive like at least twice you are going but like overall order is not changing but like overall order is not changing for the overall time it will take it for the overall time it will take it will change because first you are will change because first you are traversing to the sentence one each of traversing to the sentence one each of the characters and this and they are the characters and this and they are then you are traveling through this then you are traveling through this whole array fine whole array fine so that's the uh what you need to do so that's the uh what you need to do there but when you improve to uh say you there but when you improve to uh say you will find out like you keep adding them will find out like you keep adding them all again you Traverse the whole all again you Traverse the whole sentence that order of n is there and sentence that order of n is there and add it to that you need to find the size add it to that you need to find the size of the like calculate the size of the of the like calculate the size of the set okay so set size you know you can set okay so set size you know you can use directly uh the function but that use directly uh the function but that function also takes an order right it function also takes an order right it calculates that in internally so uh that calculates that in internally so uh that is the text step but what is the is the text step but what is the Improvement you come up over here yeah Improvement you come up over here yeah first of all that traversing to the first of all that traversing to the whole sentence academic actor is same whole sentence academic actor is same for all approaches but over here you are for all approaches but over here you are not using much of the additional space not using much of the additional space additional space as if you are just additional space as if you are just doing additional space to store this one doing additional space to store this one uh okay that 26 character uh letters or uh okay that 26 character uh letters or the same variable it's just an entire the same variable it's just an entire variable now variable now using this you can simply find a using this you can simply find a solution to this solution to this but remember there is a small catch in but remember there is a small catch in this question the small catch is uh here this question the small catch is uh here you are looking for like a 27 bit is one you are looking for like a 27 bit is one at last and then 26 zeros are there that at last and then 26 zeros are there that should be the ultimate result they were should be the ultimate result they were looking for for returning true right but looking for for returning true right but how is this holds true so this holds how is this holds true so this holds true simply because the entire variable true simply because the entire variable wherever you take it is a 32 bit fine so wherever you take it is a 32 bit fine so it has 32 bits so that's why we can it has 32 bits so that's why we can easily go ahead and uh use it there but easily go ahead and uh use it there but say in other programs they gave you say in other programs they gave you something but there isn't like 26 something but there isn't like 26 characters of the English alphabet only characters of the English alphabet only that there are more characters there that there are more characters there they have added some characters so if they have added some characters so if that is the case you need to check that is the case you need to check whether it comes up in the 32-bit or not whether it comes up in the 32-bit or not if not we have to go with the set fine if not we have to go with the set fine now this whole stroke because of that now this whole stroke because of that because we have only 26 characters and because we have only 26 characters and in that case in that case it is less than or 32 bits so we can it is less than or 32 bits so we can easily uh use this bitmus operation to easily uh use this bitmus operation to do that so uh quickly let me quickly go do that so uh quickly let me quickly go ahead and write this code and then show ahead and write this code and then show it to you how fast or slow it works uh it to you how fast or slow it works uh with our respective file let's quickly with our respective file let's quickly go ahead with that and there is come up with a one minute sensation obviously it's a zero medicine solution but at times liquid is there what is madness but it doesn't matter let's look at the solution again um understand it again what we did so first of all as I said we took a interior variable see and this variable we are like doing a character uh by character we are traversing character character in our sentence okay and then we are doing this operation like you do uh in C1 is equal to C minus a so as I say whenever you have this C minus a is basically finding out the index of the value okay so so let's understand this uh centers so we have this uh take a case like we have this variable ABC well that's only given to us right uh now what's happening exactly is like we've come up with a first so C minus a is like zero fine so that C1 initially becomes zero and then we're doing C is zero itself so scene is zero so C or we're doing all operation of one left shift equals zero so once left shift zero is so this zero because one left shift zero is like one itself okay that is like uh zero zero zero zero zero then one fine that's happening and then uh we are doing an or operation this thing what is the scene was initially zero zero zero like all all characters are zero right so we're doing the all operations so after all operation it simply becomes zero zero one right uh that's what it becomes now uh filter what will happen we'll come up to the next character next character is B fine next state is B so B is like B minus that a but it happens it simply becomes one okay y because 90 uh 98 minus ninety seven uh that's their uh values okay so 19 minus 97 you will find out to be one then uh you need to do a left shift one so one left shift one is like one zero fine so there's one left shift one so I'm setting additional zero before it because like giving it three bits and then uh we are doing all operation with uh scene so what is seen previously zero zero one so what if we just do an all operation over here see over if we do an all operation over here x simply becomes 0 1 1 right that means that simply means we just found this uh characters or we just found this bits uh or the characters are there then what do you come up we come up with uh c c over c will find uh the character C is they're fine so then uh this C minus a will give us two so it's two main so one zero zero why we're left shifting one two bits so that's one zero zero that is two zero so then how many places where left shifting is like adding to that much zero at the end fine then we are doing all operation with the c so C inverse one zero one uh sorry zero one one and we are doing all operation of one zero zero in fact we're doing this so what comes up as a result so it's constantly one one one right and further like you may think like what comes up next say father if there's another one like another age another a will be like zero zero one right so that will be there so we'll do a uh like after two we'll do our operation so it's like zero zero one so what is what is the order operation of one and one like two and true is true itself right so that's what if it will result in one step so once you have found this character it will remain one continuous there's no problem with that but if if any character so at the end at the end it will be at least it will go ahead with 26 item we need to find the or every letter right so it will go up to 26 seconds so you and then we should be having a number that is 26 times 1 right that's 26 times 1 should be there fine that should be there over here now uh what's going on next is like we just found out say we just found out there's 26 S1 now what if we got this training system one in our scene variable fine in our scene wherever if we add one to it see we just didn't add it here we have to subtracted it on the other side it's just same to just take it make it add over here so what is it what if we add 1 at the end so if we just do some binary addition then you'll find it will become like 27 bit as one and then 26 zeros will end up having fine so this will end up having and then again one left sheet 26 is the same thing if this happens exactly right if this is exactly what we come up to as an answer then it is something we will say okay we found our answer like this is a true but in case there's any weight which is not uh one say there's a bit over here that is 0 then what will happen or subtracting one or addition like adding one to this won't result in like uh or all bits being like this fine it will just add up one over there like after this zero all the updates will be zero and up for before this all episode we want and this bit will also change one after adding one so this will happen right and plus we can say whether it's in uh whether it's an uh particular value like a paragraph or not so I hope this is understandable how you can go ahead with the solution over here so thank you for watching this video uh make if you have any doubts with this make sure to comment them down I'll be happy to help you out in the comments as well and also like this video And subscribe to the channel for regular liquid videos like this thank you for watching this video
2024-03-22 18:18:43
1,832
https://i.ytimg.com/vi_w…xresdefault.webp
Check if the Sentence Is Pangram | LeetCode 1832 | Java | Without Array or Set | @LearnOverflow
1-EzW3oyJ-s
hey what is up it is thursday april 14th 2022 2022 and i am here again this morning for a and i am here again this morning for a new problem new problem closest binary search tree value 2. uh closest binary search tree value 2. uh welcome to coding with chef and thanks welcome to coding with chef and thanks for joining and watching and if you like for joining and watching and if you like this video remember to like subscribe this video remember to like subscribe and um and um comment on the link below comment on the link below let me know how i'm doing and uh let me know how i'm doing and uh yeah um yeah um just uh give me some feedback um so yeah just uh give me some feedback um so yeah today another tree problem i'm today another tree problem i'm doing this a little late later than i doing this a little late later than i wanted to wanted to uh i got um uh i got um kind of again this mornings are rough kind of again this mornings are rough right what can you do but anyway let's right what can you do but anyway let's let's get to it um right so this is let's get to it um right so this is labeled as a hard okay it doesn't look labeled as a hard okay it doesn't look like a heart from first read but like a heart from first read but uh let's go through the details uh given uh let's go through the details uh given the root of a binary search tree a the root of a binary search tree a target value and integer k return the k target value and integer k return the k values and the bst that are closest to values and the bst that are closest to the target you may return the answer in the target you may return the answer in any order you are guaranteed to have any order you are guaranteed to have only one unique set of k values in the only one unique set of k values in the bst that are closest to the target okay bst that are closest to the target okay all right all right so all right all right so um this is the example four two five one um this is the example four two five one three this tree that's rooted at four three this tree that's rooted at four it's a binary search tree it's a binary search tree so so um that means that we could um um that means that we could um traverse through it pretty quickly uh traverse through it pretty quickly uh that means that an inorder traversal that means that an inorder traversal through the binary search tree through the binary search tree is uh is uh going to pretty much give us a sorted going to pretty much give us a sorted array so array so um um that's good that's uh one way of doing that's good that's uh one way of doing this i have a few ways of doing this i'm this i have a few ways of doing this i'm gonna actually gonna actually um do this um do this in probably a little bit of a less in probably a little bit of a less efficient way for now because i'm trying efficient way for now because i'm trying to get some practice with certain data to get some practice with certain data structures but structures but what you could do is what you could do is one thing is that you can iterate one thing is that you can iterate through through this binary search tree and efficient this binary search tree and efficient solution solution in order uh of traversal and you in order uh of traversal and you essentially could create some kind of essentially could create some kind of like um sliding window like um sliding window which which does this uh does this uh you know pretty fast i guess and it the you know pretty fast i guess and it the window is window is constrained to k values that's something constrained to k values that's something that i'll do in a that i'll do in a another solution so i'm going to label another solution so i'm going to label this as this as a solution one and have a a solution one and have a another video where i do a faster another video where i do a faster solution so in solution solution so in solution um um solution solution one what i'm going to do i'm not going one what i'm going to do i'm not going to take advantage of the binary search to take advantage of the binary search property because i want to property because i want to just do a plain uh iteration through the just do a plain uh iteration through the tree so first what i'm going to do tree so first what i'm going to do and just see if this works integer and just see if this works integer double i'm going to double i'm going to have a data structure that sorts a binary tree so basically um in i'm going to keep track of the values in the in the tree structure this way and i'll explain in a second what am i doing here um okay so i'm using a comparator you'll see why i'm using this in a and and this comparator so basically what i'm this comparator so basically what i'm thinking of doing let me before i go thinking of doing let me before i go into the comparator into the comparator uh uh if i iterate through this tree in like a if i iterate through this tree in like a pre-order traversal or some kind of pre-order traversal or some kind of traversal traversal uh i'll get values like one two one two uh i'll get values like one two one two three three four five and so just to get the values four five and so just to get the values the k closest values um pretty much this the k closest values um pretty much this difference if difference if the target is 3.7 the target is 3.7 right right 1 1 4 4 8 6. all i have to do is just subtract 8 6. all i have to do is just subtract value by value value by value from from this value right and see which ones are this value right and see which ones are the k closest okay the k closest okay so that's pretty intuitive right because so that's pretty intuitive right because in this we have 2.7 i'm gonna not round in this we have 2.7 i'm gonna not round it i'm gonna round it just for brevity i it i'm gonna round it just for brevity i have two seven have two seven one one seven uh uh one one seven okay so what are the k closest values okay so what are the k closest values okay so the k closest values are okay so the k closest values are basically going to be basically going to be and k is 2 so that's going to be these and k is 2 so that's going to be these two guys right or these two guys two guys right or these two guys whatever whatever um and there's actually the difference um and there's actually the difference is larger so um yeah is larger so um yeah so so how do we get the k closely oh and then how do we get the k closely oh and then i let's see one two three four five i let's see one two three four five let's let's from these values but there's there may from these values but there's there may be more values but anyway let's okay be more values but anyway let's okay let's um let's um look for the solution right look for the solution right uh let's see if we can determine uh let's see if we can determine uh what the k closest values are uh what the k closest values are um intuitively so if i use if i put um intuitively so if i use if i put those on a heap those on a heap as i iterate through the tree the k as i iterate through the tree the k closest values will closest values will automatically be sorted right and i automatically be sorted right and i don't have to increase the heap size uh don't have to increase the heap size uh indefinitely right i can do indefinitely right i can do something like i can always have something like i can always have for example if i have a max heap i can for example if i have a max heap i can have only the smallest values added to have only the smallest values added to this max heap at any time and i can pull this max heap at any time and i can pull off this max heap so that anything off this max heap so that anything larger than k whenever k larger than k whenever k is exceeded is exceeded the heap size k is exceeded the heap size k is exceeded i can pull off that heap and remember a i can pull off that heap and remember a heap of time extraction for the top heap of time extraction for the top level element in the max heap is level element in the max heap is one one of one so um of one so um the the the and the the and the reorganization so essentially the heap reorganization so essentially the heap will reorganize itself will reorganize itself every time i add an element to it and every time i add an element to it and take an element off of it and take an element off of it and i'm only going to have the smallest i'm only going to have the smallest elements in the end of the bit at the elements in the end of the bit at the end of the maxi we would ask why i'm not end of the maxi we would ask why i'm not using a min heap so using a min heap so because a min heap orders elements one because a min heap orders elements one two three four five well max he orders two three four five well max he orders elements five or three two one the elements five or three two one the reason why is because reason why is because at any time at any time um um the maxi will order elements right let's the maxi will order elements right let's just say these are just some other just say these are just some other elements uh then it'll put three in elements uh then it'll put three in front but let's say i want the cake front but let's say i want the cake largest value since k is equal to two largest value since k is equal to two equals two equals two remove three remove three and then and then two two and one will be left and i can two two and one will be left and i can just help i can always prevent the heap just help i can always prevent the heap from from uh putting elements that are larger than uh putting elements that are larger than the smallest elements on by just the smallest elements on by just maintaining the same heap size okay maintaining the same heap size okay so uh okay let's put a comparator for a so uh okay let's put a comparator for a max heap i'm writing this out because i can i'm writing this out because i can compress this notation that the point of compress this notation that the point of this is learning so this is learning so a comparator uh a comparator uh in a comparator since we're comparing in a comparator since we're comparing values of doubles right values of doubles right the double is the second the double is the second value of the pair i'm using a pair to value of the pair i'm using a pair to maintain why am i using a pair here maintain why am i using a pair here because the pair is going to because the pair is going to maintain both the value and the maintain both the value and the difference corresponding to that value i difference corresponding to that value i could have used an array i could use could have used an array i could use some other data structure but i also some other data structure but i also sometimes it's nice to work with sometimes it's nice to work with something semantically nice like a pair something semantically nice like a pair okay okay so so now this is what the comparator does and now this is what the comparator does and again max it's a maxi because b again max it's a maxi because b is larger than a right so is larger than a right so b is going to if b is larger than a then b is going to if b is larger than a then essentially the value is going to be uh essentially the value is going to be uh less than zero uh then less than zero uh then the larger value gets stuck on the heap the larger value gets stuck on the heap first first the ordering gets stuck on the heap the ordering gets stuck on the heap first and then the smaller value gets first and then the smaller value gets second second uh and uh and so on and so forth so if it was a min so on and so forth so if it was a min if this was a min heap then we just if this was a min heap then we just reverse these and then uh we can have reverse these and then uh we can have them in them in because then the order will have the because then the order will have the smallest elements in front of the heat smallest elements in front of the heat okay okay let's go integer integer double double and java is wordy i could obviously in and java is wordy i could obviously in kotlin or something like that i could kotlin or something like that i could have a much more semantically have a much more semantically cleaner cleaner uh uh piece of code piece of code but i'm just trying to get through this but i'm just trying to get through this here so the priority queue is the heap here so the priority queue is the heap that will organize and then okay so um that is the uh that is the priority queue um and now this now we're going to go through the iteration of the tree so i'm just going to do an in-order traversal i've never entered a pre-order traversal now because those are the easiest to write um but uh in the future i'm gonna do it um in order traversal in order traversal because because that takes advantage of the that takes advantage of the property of the the binary search tree property of the the binary search tree property property um um okay but this is also useful for any okay but this is also useful for any general stream not only a binary search general stream not only a binary search tree so that's a nice another nice thing tree so that's a nice another nice thing about this about this um um okay okay double so now this is just double so now this is just this is basically um this is basically um you should be familiar with in order you should be familiar with in order traversal iteration traversal iteration uh uh or pre-order traversal iteration to a or pre-order traversal iteration to a binary tree if not then i will binary tree if not then i will quickly go over it but it's not too bad minus target okay so here add to the priority queue add to the priority queue this is where the work of the tree is this is where the work of the tree is done done if pq dot size is greater than k if pq dot size is greater than k remember i'm using a max heap here so remember i'm using a max heap here so whenever i use a max heap to get the whenever i use a max heap to get the smallest elements i have to make sure smallest elements i have to make sure that our smallest k elements i have to that our smallest k elements i have to make sure that make sure that remove elements remove elements that are in front of the heap that are in front of the heap when the case size is exceeded okay when the case size is exceeded okay because at that point then because at that point then the the the heat the heat the heat the heat will will uh not allow us to get the values we uh not allow us to get the values we need need the minimum values we need the minimum values we need if we don't do that okay if we don't do that okay okay so okay so uh when we write this out you know uh when we write this out you know right right not equal to no okay so what's going on here so this is basically um the in pre-order traversal uh we could have uh also written this in a recursive fashion but the iterative fashion is more compact you have a stack here and in the recursive uh implementation of the pre-orders traversal the stack is implicit in the stack frames uh so that's basically um what it you know what the traversal looks like if you want to add if you want to emulate adding the values remember the stack is last in first out so first you add the first thing you add is the root right and then you add two i'm going by this example on the right here you add two right and uh then so if the left child is not equal to null then you add two but the right channels is not equal to no you add five right and then uh you essentially your for the next this stack that pop you pop off the top element so i popped off uh the top element which is four right and so and then i added two and five right because the first thing i did was add four okay okay let's make sure i do that because this is important you have to push the root so we have the root of the tree we push the root of onto the stack right so that would be four we pop the left shell in the we pushed our left shot we pop it off before we push two and five then on the next iteration we and five then on the next iteration we pop off pop off um um five right and then five doesn't have five right and then five doesn't have any children so all that's left is two any children so all that's left is two so so we pop off two we pop off two in the stack and in the stack and then we add then we add a one and three and then on the next a one and three and then on the next iteration we pop off um iteration we pop off um one and three one and three okay so basically okay so basically the the order of the stacks uh order of the stacks uh popping and execution popping and execution uh will uh will determine determine the value of the tree the traversal okay the value of the tree the traversal okay so that's in order because so that's in order because uh just compared to the recursive uh just compared to the recursive version when you get a chance of what version when you get a chance of what the value should be when you're i'm not the value should be when you're i'm not in order pre-order what pre-order in order pre-order what pre-order version should be so version should be so okay cool and so let's okay cool and so let's do the last thing the last thing is now do the last thing the last thing is now we have a priority queue empty don't get key and return and return so basically what's going on here is so basically what's going on here is that we have the priority queue that we have the priority queue filled with values filled with values up to k and these are guaranteed at this up to k and these are guaranteed at this point to be the smallest values even point to be the smallest values even though this is a maxi because all the though this is a maxi because all the larger elements have been in an online larger elements have been in an online fashion or an active fashion been popped fashion or an active fashion been popped off before the heat could come away so off before the heat could come away so whatever is left is still going to be whatever is left is still going to be ordered from largest to smallest but ordered from largest to smallest but it's going to be the smallest it's going to be the smallest elements of the explosive k elements of elements of the explosive k elements of the total uh differences that are the total uh differences that are computed throughout the entire tree okay computed throughout the entire tree okay so let's run this of course let's see so let's run this of course let's see what i'm missing here what i'm missing here there's always something missing new there's always something missing new comparator comparator uh uh no comparator let's check let's check if if double val double val less than zero less than zero oh oh yeah yeah but i decided to opt for the long route but i decided to opt for the long route for this so for this so public and public and compare okay okay um let's make sure i don't need this and then okay exception new pair exception new pair integer double cannot be cast to comparable cannot be cast to comparable okay so okay why is that the case uh pq that integral double is uh i need to pass the comparator and see these little things sketching okay cool and so yep there you go that's the solution uh yeah uh so that's basically it could be faster and we could in the future do a faster solution but this is what i'm uh doing for now um this is slower because essentially this is an k log n solution because you're adding two you're popping off the stack in you know each element you're visiting only once but since you're reordering the stack each time you're uh essentially doing okay uh log n operation on each iteration so uh since you're doing it most k of them right uh you're doing this ordering is going to be uh login our k log n and uh yeah and then this is another k uh removal in k log n right so uh yeah so that's it for now a little bit of a bumpy ride today but getting into the swing of things so i'll see you around next time and stay coding and we'll do another solution in the
2024-03-22 12:31:21
272
https://i.ytimg.com/vi/1…axresdefault.jpg
Closest Binary Search Tree Value II (Sub-optimal)
vn-Jol8SNsM
welcome to february's leeco challenge today's problem is shortest path in today's problem is shortest path in binary matrix in an n by n square grid binary matrix in an n by n square grid each cell is either empty zero or each cell is either empty zero or blocked one blocked one a clear path from top left to bottom a clear path from top left to bottom right has length k right has length k if and only if it is composed of cells if and only if it is composed of cells inside of our grid inside of our grid now we can move in eight directions now we can move in eight directions basically we can only move the cells basically we can only move the cells that have a zero that have a zero not one so this is a straightforward not one so this is a straightforward path finding algorithm they tell you path finding algorithm they tell you straight out in the hint do a breath straight out in the hint do a breath first search first search so we're gonna do that we're gonna start so we're gonna do that we're gonna start at the top left and do a breath first at the top left and do a breath first search search in all eight directions we just need to in all eight directions we just need to make sure that the cell is in bounds make sure that the cell is in bounds that we haven't visited and it also is a that we haven't visited and it also is a zero zero not a one and then we can just continue not a one and then we can just continue to see if we can get to the bottom to see if we can get to the bottom right and as soon as we do that would be right and as soon as we do that would be the the shortest number of steps that we take shortest number of steps that we take could take to get there could take to get there since we're doing a breadth first search since we're doing a breadth first search so let's start by initializing a couple so let's start by initializing a couple variables variables let's start with the mnn which should let's start with the mnn which should just be the length of the grid just be the length of the grid as well as the length of grade zero we also want to have a visited set to keep track of the cells that we've already visited because if we've already visited in our breath first search we know that this is the quickest path to get there so we don't need to recalculate that and i'm also going to make a list and i'm also going to make a list of all the directions that we can go of all the directions that we can go into to make it a little bit easier into to make it a little bit easier there are going to be eight directions now starting with let's say zero one and give me a minute to do this left right one and we can also go negative one one one and we can also go negative one one we can also go we can also go one negative one one negative one so great these are all eight directions so great these are all eight directions we can go in so let's begin and write we can go in so let's begin and write our algorithm our algorithm now before that we got to make sure that now before that we got to make sure that the first cell that we start at the first cell that we start at is actually a zero because if it's a one is actually a zero because if it's a one we can't even begin this algorithm right we can't even begin this algorithm right so if so if grid zero zero 0 is grid zero zero 0 is equal to 0 then we could add to our q equal to 0 then we could add to our q and what i'm going to do is add a tuple and what i'm going to do is add a tuple with the number of steps that we've with the number of steps that we've taken to get here start with one taken to get here start with one as well as the another tuple indicating as well as the another tuple indicating to us to us the the cell number that we're at the the cell number that we're at i will also say visited dot add here i will also say visited dot add here zero zero and all right let's begin algorithm so while q first thing we'll do is pop off our pop off this whatever's on the queue and what will it be here we'll have the number of steps as well as i'm going to call it temporary for now and this would be q pop left rc would be the temp 0 rc would be the temp 0 and temp 1. okay so we have all the information we need now we're going to move in some directions we'll say 4ij in directions let's calculate our new r and new c so new r and new c is going to be equal to r plus i and c plus j so if this is in bounds and the column is in bounds and it's a zero not a one new our new c not and visited oops okay then we can append to our cue a tuple with the number of steps plus one and a tuple of the new r and new c make sure to add to our visited as so that we don't revisit places we've so that we don't revisit places we've already been now i guess i should add our base r c is equal to r c is equal to m minus one and n minus one m minus one and n minus one whoops then we know whoops then we know that we've gone into the bottom right so that we've gone into the bottom right so we can just return the number of steps we can just return the number of steps otherwise if we follow this fall out of otherwise if we follow this fall out of this this while loop then we can turn a negative while loop then we can turn a negative one because there is no path that exists one because there is no path that exists to get to the bottom right all right so to get to the bottom right all right so let's see if this works not enough values to unpack expected two not enough values to unpack expected two but got one all right let's see here what did i mess all right let's see here what did i mess up my fault made a typo there my fault made a typo there okay so looks like it's working let's go okay so looks like it's working let's go ahead and submit that and there we go accepted so this is a n times n time complexity because we won't be revisiting ones that we visited we do use extra space one way you could avoid doing that is you could just update the grid itself to equal one each time we visited so instead of this we could say grid you know zero zero plus one and similarly we can do and this will allow us to not visited places that we've already said so this depends on whether we're allowed to update the original grid or not if we are then we can save some memory and do it this way so that would work too alright so thanks for watching my channel remember do not trust me i know
2024-03-25 17:10:07
1,091
https://i.ytimg.com/vi/v…sM/sddefault.jpg
Leetcode - Shortest Path in Binary Matrix (Python)
h-2UzObAO5I
hello guys welcome back to another video today we'll be talking about 498 today we'll be talking about 498 diagonal traverse so it says given a diagonal traverse so it says given a matrix of M times and elements M rows matrix of M times and elements M rows and columns returned all elements of the and columns returned all elements of the matrix in diagonal order as shown in the matrix in diagonal order as shown in the image and the below image so I actually image and the below image so I actually put this into this white board so it put this into this white board so it could be better visualized so I put the could be better visualized so I put the eye index here and then the J index here eye index here and then the J index here so from this what you should realize is so from this what you should realize is that each element on the same line has that each element on the same line has the same I plus J value so let's take the same I plus J value so let's take this line for example so for has a I this line for example so for has a I plus J of one and then two also has an I plus J of one and then two also has an I plus J of one and if you take this line plus J of one and if you take this line for example eight has the I plus J of for example eight has the I plus J of three while six has the I plus J of three while six has the I plus J of three as well so this is actually the three as well so this is actually the pattern that we're gonna use to identify pattern that we're gonna use to identify the elements that are on the same line the elements that are on the same line and you can realize here that when I and you can realize here that when I plus J is odd then the diagonal is going plus J is odd then the diagonal is going down so here I for one I plus J is at down so here I for one I plus J is at zero which is even and it's going up zero which is even and it's going up when we're here on this line that I plus when we're here on this line that I plus J is 1 so it's going down and this is J is 1 so it's going down and this is even so it's going up and this is odd so even so it's going up and this is odd so it's going down so when I plus J is odd it's going down so when I plus J is odd the diagonal reverses and another thing the diagonal reverses and another thing to notice in this question is that the J to notice in this question is that the J index this is actually a very important index this is actually a very important part because it wants you to go by order part because it wants you to go by order so which means you can't just go one for so which means you can't just go one for two so the J index actually organizes to two so the J index actually organizes to order say when the when the diagonals order say when the when the diagonals going down the smaller J index gets put going down the smaller J index gets put first in the inter a that we're gonna first in the inter a that we're gonna have when the array is going up the have when the array is going up the bigger J index is gonna go last bigger J index is gonna go last so basically there's a pattern here and so basically there's a pattern here and the solution here is what I wrote here the solution here is what I wrote here so you want to use a 2d array to store so you want to use a 2d array to store each element along with the column index each element along with the column index and the I plus J index with the element and the I plus J index with the element element value then you can use a element value then you can use a comparator to sort this 2d array and comparator to sort this 2d array and then once it's sorted you just Traverse then once it's sorted you just Traverse the 2d array and take the element values the 2d array and take the element values and plug it in to the intr a so that's and plug it in to the intr a so that's how we're gonna approach this problem how we're gonna approach this problem and I hope it makes sense to you guys and I hope it makes sense to you guys so let's get code in here alright so so let's get code in here alright so right here first things first what you right here first things first what you always want to do with these matrix always want to do with these matrix problem is that if matrix that length problem is that if matrix that length there's equal equal to zero you want to there's equal equal to zero you want to return turn a new in array with nothing return turn a new in array with nothing in it okay so now we can get the coding in it okay so now we can get the coding part so here what you want to do first part so here what you want to do first is call your could be array I'll just is call your could be array I'll just call it 2d right now actually I'll give call it 2d right now actually I'll give it a better name I'll call it array me it a better name I'll call it array me okay so we could equal the commute and okay so we could equal the commute and matrix rain times matrix 0 dot length matrix rain times matrix 0 dot length and this is because we wanted to hold and this is because we wanted to hold every single value in the 2d array every single value in the 2d array matrix and then we make it 3 cuz I matrix and then we make it 3 cuz I stated here we need to need to store stated here we need to need to store that I plus J index and just store the that I plus J index and just store the column index and we need to store the column index and we need to store the element value so it's actually going to element value so it's actually going to be a width of 3 and then for our array be a width of 3 and then for our array we'll call it rez and it's equal to new we'll call it rez and it's equal to new int RV but right okay so now that we int RV but right okay so now that we have this we can start traversing have this we can start traversing through this array so for int I equals 0 through this array so for int I equals 0 I was less a matrix length I plus plus I was less a matrix length I plus plus or and J is equal to 0 or and J is equal to 0 J is less than matrix we can just say at J is less than matrix we can just say at zero but if you want to say I it's fine zero but if you want to say I it's fine because it's stated here that it's an M because it's stated here that it's an M times n so the width will not change and times n so the width will not change and then J plus plus okay so for here I'm then J plus plus okay so for here I'm gonna call a and that's variable to tell gonna call a and that's variable to tell us the index of our to do right here so us the index of our to do right here so I'm gonna go are that index plus plus so I'm gonna go are that index plus plus so what I did here is that because the plus what I did here is that because the plus plus is after the index it's gonna call plus is after the index it's gonna call this index and then it's gonna add 1 to this index and then it's gonna add 1 to the value so I don't have to put any the value so I don't have to put any index plus plus here all right so that's index plus plus here all right so that's what it does what it does but basically same thing alright so it's but basically same thing alright so it's equal to new in array index sorry I'm equal to new in array index sorry I'm making int array here so you want I plus making int array here so you want I plus J value and then you want the J value J value and then you want the J value and then you also want element value so and then you also want element value so matrix I and I J alright so now that matrix I and I J alright so now that you've stored this in you can go out of you've stored this in you can go out of this loop and there's the complex part this loop and there's the complex part of this problem so once you have all the of this problem so once you have all the information that you need in there in to information that you need in there in to sort the array and luckily in Java sort the array and luckily in Java there's actually a very easy function there's actually a very easy function using comparator to sort this 2d matrix using comparator to sort this 2d matrix so all we do here is we call arrays dot so all we do here is we call arrays dot sort and then you put the array you want sort and then you put the array you want to sort the name in here so ARR G they to sort the name in here so ARR G they are Rd and then comma new comparator are Rd and then comma new comparator your new you might be new to this but um your new you might be new to this but um the pretty interesting function and you the pretty interesting function and you should check it out so you have your should check it out so you have your comparator in here I'm just gonna put a comparator in here I'm just gonna put a semicolon here just in case I forget so semicolon here just in case I forget so inside here make sure inside here make sure this parameters and int array and so you this parameters and int array and so you have public and compare and beside this have public and compare and beside this you want and write a and then a rate B you want and write a and then a rate B for compared for comparing reasons and for compared for comparing reasons and then here you can say if a at zero which then here you can say if a at zero which is talking about this I plus J index I is talking about this I plus J index I say at 0 is not equal to ax B at 0 sorry say at 0 is not equal to ax B at 0 sorry so what this what this statement does is so what this what this statement does is that let me finish this for so you that let me finish this for so you there's a - a at zero - speedmaster at there's a - a at zero - speedmaster at zero so right here remember how we held zero so right here remember how we held the same I plus J values on the same the same I plus J values on the same line so therefore if it's not the same line so therefore if it's not the same it'll sort the I plus J value so this it'll sort the I plus J value so this will actually go in ascending order and will actually go in ascending order and then we can just get it so that's the then we can just get it so that's the first part however if you remember me first part however if you remember me saying here that when I plus J is odd saying here that when I plus J is odd the diagonal reverses so what this the diagonal reverses so what this basically means is the J index instead basically means is the J index instead of organizing the J index from the of organizing the J index from the smallest to biggest we're going to smallest to biggest we're going to organize it from the biggest to smallest organize it from the biggest to smallest so what we're gonna do here whoopsies so what we're gonna do here whoopsies ok so what we're gonna do here is that ok so what we're gonna do here is that if a at 0 mod - there's not equal to it if a at 0 mod - there's not equal to it well this is my bed there's not equal to well this is my bed there's not equal to 1 sorry 0 and then what we're gonna do 1 sorry 0 and then what we're gonna do here is return the opposite of a at 1 here is return the opposite of a at 1 minus B at 1 and remember that minus B at 1 and remember that yeah 1 is the J index and then else yeah 1 is the J index and then else we're just gonna return the same thing we're just gonna return the same thing but without the negative in front of it but without the negative in front of it so this flips the value of this which is so this flips the value of this which is why we do it so now that the sorest why we do it so now that the sorest finish the rest of the process is fairly finish the rest of the process is fairly easy easy now all you need to do is reverse now all you need to do is reverse through this 2d array and get your value through this 2d array and get your value so int I is equal to 0 is less than our so int I is equal to 0 is less than our length and remember here why there's a length and remember here why there's a so here I'm only going to use one for so here I'm only going to use one for loop and the reason is because these loop and the reason is because these three values this is for this part so three values this is for this part so the only value we actually need and here the only value we actually need and here is this matrix value which is at the is this matrix value which is at the second position so we only need to second position so we only need to traverse through the rows of the array traverse through the rows of the array and get the second position of each row and get the second position of each row so what I'm gonna do here is raz anti is so what I'm gonna do here is raz anti is equal to Rd at I and at 2 so this calls equal to Rd at I and at 2 so this calls this value which stores interests and this value which stores interests and then all you need to do next is just to then all you need to do next is just to return rest and then you'll be done with return rest and then you'll be done with the problem the problem so this check of we got the test cases so this check of we got the test cases right done looks like we had the right right done looks like we had the right um just check our one more test case um just check our one more test case make it a square and see how it does alright this looks good that's turn it in and looks like we passed so that's how you do this problem so the time complexity here this sort is and login and this is N squared so we'll just take an own skirt so this is actually an N squared algorithm and that's how you solve diagonal traverse all right guys I hope you've enjoyed this me solving this problem if you want to see more of these problems check out my channel page and
2024-03-22 15:53:34
498
https://i.ytimg.com/vi/h…axresdefault.jpg
Leetcode #498: Diagonal Traverse
X0L3VVNmpMM
Hello hi friends welcome back today we are going to solid hi friends welcome back today we are going to solid problem 1905 account sub violence this problem 1905 account sub violence this problem voice of pay Google Facebook problem voice of pay Google Facebook Amazon in the last interview sub let's go through this Amazon in the last interview sub let's go through this description of the problem you are you description of the problem you are you remember in binary matrices grade remember in binary matrices grade one and two containing only one and two containing only one and two containing only Water and Voice Land and Ireland Is Group of Bones Connected Directionally Horizontal or Vertical Sugar Sales Outside of the Great and Considered Water Sales and I Lending Rates Considered All Identification of Land in Grade One Day Decided and agreed to return Decided and agreed to return Decided and agreed to return number of violence in number of violence in great to that was considered sub violence great to that was considered sub violence 210 have given 30 to examples for has ndri 210 have given 30 to examples for has ndri knowledge dish constraints show length knowledge dish constraints show length of freedom in the and great you don't of freedom in the and great you don't drink there and equal and any equal to means drink there and equal and any equal to means the column patrons the column patrons the column patrons 132 Requested Same and the same column between 1250 and you will contain 0 800 This is a medium level problem a Facebook Google and Amazon So let's take this example over and we can discuss how we can unite for this problem so let's change colors Basically so the problem should be come that Jitni Distic 3100 This is the Great 153 Jitni Distic 3100 This is the Great 153 Doraemon and Shizuka grade too short to give its Doraemon and Shizuka grade too short to give its argument was right and preserve if you look at this argument was right and preserve if you look at this great too right citizen great too right citizen island in the great too basically are you can see island in the great too basically are you can see island in the great too basically are you can see human rights highlight one day high blood development ireland convid it connected 22 landfill sites and air connect vertically and horizontally side by side so as you can see delay all correspond engagement in the grade one with which maps year it's been hit max like this basically 512 basically Back to Year Highlighting Iss Pani Back to Year Highlighting Iss Pani Back to Year Highlighting Iss Pani Ko Respond Zinc Iodine Grade One Such Ko Respond Zinc Iodine Grade One Such Means the Best All the Sense of This Highly Learned Means the Best All the Sense of This Highly Learned in Great You're Late in Grade One in Great You're Late in Grade One Ulcerated Time Extra Celebrates It's Ulcerated Time Extra Celebrates It's Okay Mother Can Have More Schools But Every Saint Okay Mother Can Have More Schools But Every Saint That Shailendra Singh Every One That Shailendra Singh Every One That Shailendra Singh Every One foot where present in life right of great you should be present in screed one day when called violence 34 red is dynasty now high alert all ireland similar if you look at this one day is another Mapping Mapping Mapping Bright Like A Same Shell Ireland Celebration This Bright Like A Same Shell Ireland Celebration This Another Child And Soon S Another All Another Child And Soon S Another All Pilot Clear Light Bill Gets Another Mapping Pilot Clear Light Bill Gets Another Mapping Clear 500 1000 All Violence For This One S Clear 500 1000 All Violence For This One S U Can See Enemy There Is No Mapping Key U Can See Enemy There Is No Mapping Key Brightness Vande Resume App In English Of Brightness Vande Resume App In English Of Us Us Us Destroys Land ₹10 Note Account When Ireland Similar Tags Country Ireland 3096 Counted As A Pilot Why Because There Is No Corresponding Mapping Beg This 30 UPSC That Government According Sales Birthday Are Not Vikas This is Water Vikas This is Water Vikas This is Water ₹100 Note Account Dr to the Balance and ₹100 Note Account Dr to the Balance and Total Sub Pilot Skin This Great Spirit Total Sub Pilot Skin This Great Spirit Freezer Total White Dishonor Red Color 246 Freezer Total White Dishonor Red Color 246 Miles 123 KM To Have Written Number of Serenity Miles 123 KM To Have Written Number of Serenity Hui and Finding in Poor to Thought Hui and Finding in Poor to Thought Present in Every Day End Present in Every Day End Present in Every Day End Hair Definition And Decided That Destroyed Because We Find The Number Of Ordinary Women So Let's Reduce Highlighted Things Became Just Smiled And Use This Per Saket Hai To Aap Nau We Are Going To Solve This Problem And And And Deficit Reversionary Defense Morning And Deficit Reversionary Defense Morning And Defects Can Work In This Case Will Go And Will Defects Can Work In This Case Will Go And Will Approach Like You Will Read Through Approach Like You Will Read Through Grades Right From This And Top To The Bottom And Grades Right From This And Top To The Bottom And They Will Never See Any One Should Go Right They Will Never See Any One Should Go Right With Land Sale Will Start Doing With Land Sale Will Start Doing Defense Defense Defense In Hui Start Doing Anything For Direction Correct Pro For Directions Pimples Us And Vertical And Horizontal E Give This Is Still When You Can Take For Example Late Se Enemy Israel Ko Enjoy Celebrate Life Enjoy List Free Mode White Icon Reason Leader Cell Tax Icon Reason Leader Cell Tax Icon Reason Leader Cell Tax Barrier On To You Will Look Into Forests Barrier On To You Will Look Into Forests Of - 101 Is Deep Sandwich Upwards Yo Yo Of - 101 Is Deep Sandwich Upwards Yo Yo Pyaar Ko In Upward Koi Pyaar Ko In Upward Koi Download Din This Tel Will Be I Plus Download Din This Tel Will Be I Plus One J Correct Wicket Next Roll One J Correct Wicket Next Roll Andar Right Side It Will Be I Andar Right Side It Will Be I Andar Right Side It Will Be I Plus Subscribe An evolved saver of birth column on Plus One will increase clear 100 Z Plus One and you are going on in the left side and will be IJ - 08 2010 For directions to you you will go away I will Any cell with land right Any cell with land right Any cell with land right one and will give what do you trying to one and will give what do you trying to consume water and the silent for example if i have consume water and the silent for example if i have land cell in the given land cell in the given subscribe and will going on subscribe and will going on alarm hear yudhishthir right alarm hear yudhishthir right only will consider cell suvichar-1 there are any only will consider cell suvichar-1 there are any four land cells four land cells four land cells Return Chaumu Gaya Hai Yaar Tu Yaar Boeing Of Birth Download And Left Side UC Of Child's Affair Going Outside Of The Boundary Of The Matrix Relative Website The Matrix Villages Will Not Consider Dost Excise Vikas 2009 Valid Velvet Silk Velvet Silk Velvet Silk Luxury Luxury All Elements In One Like This Difficult To All Elements In One Like This Difficult To Validate Only And Decisions Were Valid Validate Only And Decisions Were Valid CSS Valid Inference Switzerland Also CSS Valid Inference Switzerland Also Want To Consider And You Will Want To Key Checking At Want To Consider And You Will Want To Key Checking At 10M Location Same Position In 10M Location Same Position In Jeevan Matrix Rack Every State Will Consider And Jeevan Matrix Rack Every State Will Consider And Secret In The Secret In The Secret In The Jeevan matrix with every metric and this will find all correspond which are right thinking but case will just account when all iodine profit account will be first t20 now you will increase your account on Time Hui Just Make Time Hui Just Make Time Hui Just Make Distance Like Mrs. Chocolate Distance Like Mrs. Chocolate Mixture Ko Yudh Khol Solve Will Give In Just Changes Tel Vansh Mixture Ko Yudh Khol Solve Will Give In Just Changes Tel Vansh Visit Will Change It's Visit Will Change It's To Sukhram Wave Market To Sukhram Wave Market 251 Maruti Salute Ooo All Sets Mitthu Right And Why They Are Doing But Because Hui 152 E Don't Want Ooo Again 152 E Don't Want Ooo Again 152 E Don't Want Ooo Again Flight So Good Behavior Change Into Two Solve Will Have To Do Calculator Sales From Wasteland Least One Life So Will Avoid 0.15 Inches Marketable To After Visiting Research On Devanagari And Nau After Which One Will Visit Enemy Right Facility Is Ireland Crush Ponting's Her Crush Ponting's Her Crush Ponting's Her Absolutely Clear Junior Science In Its Absolutely Clear Junior Science In Its Water And So Will Not Written Content Is Available Now Water And So Will Not Written Content Is Available Now Visit All This Data Is The Visit All This Data Is The Correspondingly One Here Right Will Correspondingly One Here Right Will Contest All This Ireland Right Contest All This Ireland Right Directions In This Direction Shrouded in Darkness Directions In This Direction Shrouded in Darkness Can Do Anything In This Right Can Do Anything In This Right Can Do Anything In This Right One Shall Ireland Basically In To-Do One And Will Do You Will Be Able To Hear What This One And Will Do You Will Be Able To Hear What This Point No Data Is Not Point No Data Is Not Responding To Here Right subscribe and subscribe the Channel Please subscribe and subscirbe 101 Land Sale 101 Land Sale 101 Land Sale In In Prevented 238 Basis Of Proper Prevented 238 Basis Of Proper Implementation And Solve This Problem Implementation And Solve This Problem Using Defense Using Defense Solitaire Look into the implementation of is so as you can see this is the function that is give great freedom and great two three one two three studio me 2800 will One now winters available conducts One now winters available conducts One now winters available conducts of violence and will create one set of bullion of violence and will create one set of bullion right time to explore new you have right time to explore new you have created and they will hold fun of which created and they will hold fun of which create one today I am here for details create one today I am here for details visit and because you don't want to one to visit and because you don't want to one to your visitors and vent your visitors and vent your visitors and vent again writes will just keep track of words you have visited using visited metrics and in this receiver we are now traveler lite travels and tours and grade to is great to basically and we first start live with clear set and Which Was Now Have Which Was Now Have Which Was Now Have Found One Island In Grade To Do You Want To Say Found One Island In Grade To Do You Want To Say Activities Say No Toe Tattoo Yer Activities Say No Toe Tattoo Yer Checking Using Facebook Given Porn Its Return Checking Using Facebook Given Porn Its Return Type Is What Toe Were Passing Two Type Is What Toe Were Passing Two Mattresses The Position Come Light Of The Sale Mattresses The Position Come Light Of The Sale Starting Sale And Will First Set Starting Sale And Will First Set Regulations And Will Power Visited Her Hair Regulations And Will Power Visited Her Hair Soft Things You Want To Check Is Accused Soft Things You Want To Check Is Accused Going Outside Of The Founder Of The Matrix Going Outside Of The Founder Of The Matrix Rate Sudesh What They Are Taking Care Been Rate Sudesh What They Are Taking Care Been Going Outside Of Boundary And Iss Aloo Going Outside Of Boundary And Iss Aloo Yaar Visiting 1507 Bin In That Case How I Just Want Yaar Visiting 1507 Bin In That Case How I Just Want To To To Valid Only And Only Have Already Written Updates And Right Clear Those Viewers Return From This Point To You Will Not Go Forward Bigg Boss That Is Not Valid For Visiting Not And Up To Date Vtu Check The Self That Were Visiting Correspondent in One Cell in Matrix Hundred Years to Correspond in One Cell in Matrix to Value Your Cigarette's Array in C a Beneficial and Corresponding Matrix Cell is So What is Mintu Se Whenever and Delicious and Rights and Delicious and Rights and Delicious and Rights and where taken for this and here right side effect is not one basically rectify this not one year since I did not match these days then forms will be our satellite and return basically reset is useful to get the Function Because Function Because Function Because Devise Function Will Not Written In Its Return Avoid Solve Understand Your Devise Function Will Not Written In Its Return Avoid Solve Understand Your Fit Before Fit Before Two Not Were Going Through Use This Two Not Were Going Through Use This Flexseed Basically Right Some Where Is There Is Flexseed Basically Right Some Where Is There Is No Match Matching Just Just Former Value No Match Matching Just Just Former Value Gift Size Zero-valued Right To You Will Gift Size Zero-valued Right To You Will Not Withdraw Not Withdraw Not Withdraw scenario where hui and finding matching se nuvvu great you have found matching fold nou how to find after remaining ireland celebrate so they have to be effective in all directions to here you will declare right like this saw all records To Have Doing Facebook That's What You Will Be To Have Doing Facebook That's What You Will Be To Have Doing Facebook That's What You Will Be Doing Fair Price Doing Fair Price Shops Which Will Mark The Celebs Visit Shops Which Will Mark The Celebs Visit Forest And You Will Have To Forest And You Will Have To Write In The Matrix Also So Why Don't You Write In The Matrix Also So Why Don't You Gift That One So I Just Want To Make That Gift That One So I Just Want To Make That Change Change Change Reviews And Visiting Don't For Directions In The Defense Right Today The Growth In All Four Directions And Clear To Dushmani Say J - Vriksh Your Hair Tweet Disawar Current Servi Tried To Go For All For Research On Do It Share It Share It Till Only In Do It Share It Share It Till Only In Do It Share It Share It Till Only In The Loop And Finally Vansh Will Get Out And Way Come Here The Loop And Finally Vansh Will Get Out And Way Come Here Three Wickets That Power Set Three Wickets That Power Set Contents For Its Value Gifts Where Is Contents For Its Value Gifts Where Is Not Dare Mist Powder White Tight Beach Only Not Dare Mist Powder White Tight Beach Only Panty Set Hui Ascending And They Are Getting Panty Set Hui Ascending And They Are Getting Anti Shatter High Means The Editor Then Iodine Ther Anti Shatter High Means The Editor Then Iodine Ther School Increment Account Clear Kar School Increment Account Clear Kar Acts Will Go Into This For Lower Rates Will Find All Acts Will Go Into This For Lower Rates Will Find All The Island Website Wherever I Find One The Island Website Wherever I Find One In Great To You Will Keep Doing A In Great To You Will Keep Doing A Sandwich Activities Surplus Of Wildlife Sandwich Activities Surplus Of Wildlife And Or Not And The And Or Not And The And Or Not And The return to 10 of violence at so this is the weather of implementation is and will take your first to you will take care of this first test case rights and issued to give 3 and you will yaar getting correct yaar getting correct yaar getting correct Innovative and Creative Is The Answer Sun Will Love You Know Who Will Check The Taste Case Ke Saudagar Discuss The Example Two Days Have Given Us To Induct Case You Always Have Output Correct Software Cutting Gents Hair Cutting Correct Caring Whose Pregnancy Festivals 116 116 116 Is The Way Can Solve Account White Is The Way Can Solve Account White Problem Subscribe Facebook Google Problem Subscribe Facebook Google Assistant Practice Problem Also Give Assistant Practice Problem Also Give You Have Violated My Play List Of List You Have Violated My Play List Of List To Decode Solutions Please Visit His Lord To Decode Solutions Please Visit His Lord Of Life And More Than Hundred Solved Of Life And More Than Hundred Solved Problems Explained With Problems Explained With Problems Explained With They Should Also Not Consist of Different Varieties of Problems That Verification Code in Interview for B Tech Companies Like Amazon Apple Google Facebook Microsoft and Many Others Believe Variety of Questions Asked His Dynamic Programming Directly Related Problems Related Interview Questions Here are some frequently asked some frequently asked interview questions for a limited company interview questions for a limited company please go through it if you find this video please go through it if you find this video health food if you like this solution health food if you like this solution health food if you like this solution hit like and subscribe your subscription this is really important for that because is the video can reach to more people the can also watch with solutions and get help during the interview preparation and java interview preparation for Please subscribe to the
2024-03-25 12:24:16
1,905
https://i.ytimg.com/vi/X…MM/sddefault.jpg
LeetCode 1905 Count Sub Islands - Google, Facebook, Amazon Interview Question
xAPYdvSkcF8
in this video we will look at lead code problem number one four problem number one four four seven and it's called simplified four seven and it's called simplified fractions fractions and you can see a glimpse of the problem and you can see a glimpse of the problem here here if we are given a number here here if we are given a number four then what we have to do we have to four then what we have to do we have to find find all the fractions between 0 and 1 all the fractions between 0 and 1 but not including 0 and 1. but not including 0 and 1. so you can see that i write 1 by 2 1 by so you can see that i write 1 by 2 1 by 3 3 1 by 4 2 by 3 3 by 4. so in 1 by 4 2 by 3 3 by 4. so in all these cases denominator will be more all these cases denominator will be more than numerator because it has to lie than numerator because it has to lie between between 0 and 1 and if i have written 4 0 and 1 and if i have written 4 these values should be less than or these values should be less than or equal to 4 equal to 4 so denominator is obviously larger so we so denominator is obviously larger so we have to check for denominator have to check for denominator so you see that none of the denominators so you see that none of the denominators are more than 4 are more than 4 and these has to be unique so let's see and these has to be unique so let's see a larger problem let's see if we want to a larger problem let's see if we want to write it for 5 write it for 5 so these are the unique possibilities so so these are the unique possibilities so clearly you can see that clearly you can see that we are starting with numerator 1 so we are starting with numerator 1 so write down all the possibilities with 1 write down all the possibilities with 1 so with 1 what can i write so with 1 what can i write i cannot write 1 by 1 since it will be 1 i cannot write 1 by 1 since it will be 1 and we have to write it between 0 and we have to write it between 0 and 1 so the value will be here value should be less than 1 greater than 0 so this is not valid next is 1 by 2 this denominator should be less than 5 so 1 by 2 is valid 1 by 3 is valid 1 by 4 is valid even 1 by 5 is valid so denominator can be equal to this only the value should not be equal to 0 or 1 it should be between them so we are done with 1 and you can see these are the 4 possibilities then we start with 2 so can we write 2 by 2 or 2 by 1 if we write 2 by 1 it's more than 1 2 by 1 not possible 2 by 2 2 by 1 not possible 2 by 2 not possible since it will be 1 it will not possible since it will be 1 it will be more than 1 be more than 1 next is 2 by 3 it's valid next is 2 by 3 it's valid next is 2 by 4 but you see that 2 by 4 next is 2 by 4 but you see that 2 by 4 is same as is same as 1 by 2 which we have already covered 1 by 2 which we have already covered so these should be unique so we will so these should be unique so we will discard it discard it so how can we check if it has already so how can we check if it has already occurred occurred uh either you take the gcd of numerator uh either you take the gcd of numerator and denominator and denominator and you divide them so you get one by and you divide them so you get one by two two or you store the decimal part like or you store the decimal part like in this case it will be 0.5 in this case it will be 0.5 and this is also 0.5 so you keep a set and this is also 0.5 so you keep a set and whenever you create a value insert and whenever you create a value insert there so 0.5 is there there so 0.5 is there 0.3334 is there 0.3334 is there 0.25 is there and so on so next time 2 0.25 is there and so on so next time 2 by 4 comes by 4 comes it's valid it's less than 1 it's more it's valid it's less than 1 it's more than 0 than 0 but we see that we have already stored but we see that we have already stored 0.5 so we will not store it 0.5 so we will not store it next is 2 by 5 next is 2 by 5 and next is 2 by 6 but that will be more and next is 2 by 6 but that will be more than 5 so we stop than 5 so we stop then we come to 3 so we are done with then we come to 3 so we are done with 2 so for 2 so for three by one is not possible three by three by one is not possible three by two is not possible three by three is two is not possible three by three is not possible so first will be not possible so first will be three by four then next is three by five three by four then next is three by five so we are done with three last one is so we are done with three last one is four four by five so how can we do that you see by five so how can we do that you see that that in numerator we have one two three four in numerator we have one two three four we will never have five we will never have five so we can have a loop for i equal to so we can have a loop for i equal to one 2 if this is one 2 if this is n 1 to n 1 to n minus 1 so it will never be n n minus 1 so it will never be n this is the outer loop and inner loop we this is the outer loop and inner loop we can have can have j equal to i plus 1 j equal to i plus 1 to n so denominator will be till 5 to n so denominator will be till 5 numerator will be till 4. so you see numerator will be till 4. so you see here n minus 1 here n minus 1 n and our denominator will be strictly n and our denominator will be strictly one larger than numerator at least one larger than numerator at least so it starts from i plus 1 and then we so it starts from i plus 1 and then we create create a fraction i divided by j a fraction i divided by j if it's not insert insert it in the if it's not insert insert it in the result we have to print all these result we have to print all these strings strings so create string out of that so we can so create string out of that so we can have have i plus then this fraction sign i plus then this fraction sign in the string and then append j so this in the string and then append j so this will be the string that we want to will be the string that we want to insert in the result insert in the result and either you take the gcd and cancel and either you take the gcd and cancel out the common terms out the common terms or you can store the fractional part in or you can store the fractional part in the set the set so let's take the eg root of storing the so let's take the eg root of storing the fractional part in the set fractional part in the set so let's first write it in c process so let's first write it in c process then we will modify it for then we will modify it for java and python so this is the result which we will then we have an unordered set not zero otherwise it will be zero it has to be more than zero so one i less than j equal to i plus 1 j equal to i plus 1 j less than equal to n j less than equal to n and plus plus j if i don't cast it to float it will we if i don't cast it to float it will we division will be done as integer then division will be done as integer then converted to float converted to float so since it's between 0 and 1 this will so since it's between 0 and 1 this will always hold the value 0.0 always hold the value 0.0 so we will convert one of these so we will convert one of these beforehand to float beforehand to float is set dot find fraction equal to set not and that is it's not found in the set so we insert it in both result as well set and this works for this simple case and this works for this simple case let's add a few more cases let's add a few more cases let's add one let's add three four five and this is that accepted that is output is same as expected and the solution is accepted in c plus and the solution is accepted in c plus now let's now let's write this exact same thing in java write this exact same thing in java so let's copy and here the result return type is string list and we can create an array list sorry set set float set let's try and this works for all the cases so and the solution is accepted in java as and the solution is accepted in java as well well finally we will do it for c plus plus finally we will do it for c plus plus python 3 sorry for ie in for j in range for j in range i plus 1 to n plus 1. and these two i plus 1 to n plus 1. and these two loops loops go away set not add so the solution works in python as well so the solution works in python as well so let's submit
2024-03-21 02:40:16
1,447
https://i.ytimg.com/vi/x…WigQhNMfXCO873lw
LeetCode 1447: Simplified Fractions
cveFizvVvQU
welcome to another one of my lead code videos in this one we will be doing videos in this one we will be doing lead code number 70 which is climbing lead code number 70 which is climbing stairs so the problem is you're climbing stairs so the problem is you're climbing a staircase it takes a staircase it takes there's a total of n steps to reach all there's a total of n steps to reach all the way to the top of the staircase the way to the top of the staircase and then there's two ways you can climb and then there's two ways you can climb if you're at a given spot you can either if you're at a given spot you can either take one step or two steps and so it's take one step or two steps and so it's asking how many ways are there that you asking how many ways are there that you can get to the top so for example if can get to the top so for example if there is a total of two steps there is a total of two steps you can either take one step and then you can either take one step and then another step or you can just take two another step or you can just take two steps so there's two ways steps so there's two ways that you can climb to the top that you can climb to the top similarly if there are three steps one similarly if there are three steps one way you can go is just do all three way you can go is just do all three steps steps another way is one and two or two and another way is one and two or two and one right so one right so in this case there are three ways where in this case there are three ways where we can climb to the top we can climb to the top so this is kind of like a recursive so this is kind of like a recursive slash dynamic programming slash dynamic programming um kind of problem and the way I um kind of problem and the way I approach this is I first come up with a approach this is I first come up with a method mathematical model right so let's method mathematical model right so let's say say if the number of ways I can climb a if the number of ways I can climb a staircase of n staircase of n is basically equal to the number of ways is basically equal to the number of ways I can climb to n minus 1 because from I can climb to n minus 1 because from there I can just take one step and get there I can just take one step and get to the top to the top plus the number of ways I can climb to n plus the number of ways I can climb to n minus two so minus two so you know the number of ways I can climb you know the number of ways I can climb to to the third step the third step is number of ways I can get to the is number of ways I can get to the second step second step plus the number of ways I can get to the plus the number of ways I can get to the first step right and if I add them first step right and if I add them together together then I'll get to the third step we know then I'll get to the third step we know our base cases right so our base cases right so let's say weighs at zero let's say weighs at zero or sorry ways at one if there's only one or sorry ways at one if there's only one step step we will we will have one way to climb that only one step have one way to climb that only one step right and if there are two steps right and if there are two steps we will have two ways of climbing it we will have two ways of climbing it because because you can either take one step and then you can either take one step and then another step or you can take two steps another step or you can take two steps at once so there's two ways so if we at once so there's two ways so if we know one and two know one and two we can compute n by just you know keep we can compute n by just you know keep we can compute three four so on up to n we can compute three four so on up to n and then we have our ways at n right so and then we have our ways at n right so let's see how this goes so let's see how this goes so uh for n i is equal to uh for n i is equal to so we'll check our base cases first so we'll check our base cases first right so if n is right so if n is equal to 1 equal to 1 or n is equal to two we just return n or n is equal to two we just return n right and then right and then for in I is equal to three so for in I is equal to three so we go up to I we go up to I less than equal to n i plus plus so we less than equal to n i plus plus so we go all the way to ways uh of n go all the way to ways uh of n so so here we can store ways n minus 2 here we can store ways n minus 2 to be equal to to be equal to 1 because that would be ways of one 1 because that would be ways of one and then ways of n minus 1 and then ways of n minus 1 which is this one will be equal to which is this one will be equal to 2 because n is 3 3 minus 1 2 so ways of 2 because n is 3 3 minus 1 2 so ways of 2 is 2. so here we've stored 2 is 2. so here we've stored ways ways -1 and ways minus two -1 and ways minus two and then we'll compute ways n and as we and then we'll compute ways n and as we compute n we'll kind of shift it so ways compute n we'll kind of shift it so ways n then becomes n minus 1 and then n n then becomes n minus 1 and then n minus 1 becomes n minus 2. so let's see minus 1 becomes n minus 2. so let's see ways n will be equal to weighs n minus 1 and then we'll have ways and then we'll have ways n minus 2 is now equal to ways n minus n minus 2 is now equal to ways n minus 1. 1. and weighs n minus 1 will be equal to and weighs n minus 1 will be equal to ways n ways n for the next iteration for the next iteration right so right so we compute base n and then we shift it we compute base n and then we shift it to the right to the right so at the end of this the and the ways so at the end of this the and the ways for n will be stored in N minus 1. for n will be stored in N minus 1. so that's what we return and yeah that's it so let's try to run accept it submit it yes accept it 100 solution so thank you so much for watching and
2024-03-20 11:24:34
70
https://i.ytimg.com/vi/c…axresdefault.jpg
Leetcode 70 Climbing Stairs (Java)
3tZAiUW0rJc
today i'm gonna show you how to solve legal question 143 reorder list it's legal question 143 reorder list it's another linked list issue you are giving another linked list issue you are giving the head of our singly linked list the head of our singly linked list basically like one two three four the basically like one two three four the list can be represented like this we list can be represented like this we order order this list to this list to l0 l0 ln basically the first one is the first ln basically the first one is the first value and the second one is the last value and the second one is the last value and then the third one is the value and then the third one is the second one from the beginning and then second one from the beginning and then the back basically you're gonna make the the back basically you're gonna make the list look like one and then take four list look like one and then take four and then two and then three so and then two and then three so the second example that they give is the second example that they give is one and then the second value will be one and then the second value will be the last value which is five and then the last value which is five and then the next value will be the second from the next value will be the second from the beginning of the list basically the beginning of the list basically which is 2 and then the next value will which is 2 and then the next value will be 4 which is the second value from the be 4 which is the second value from the end of the list end of the list and then the add the last value so the and then the add the last value so the return output will be 15243 there's constraints here and node value the question was asked by amazon adobe all these companies in the past six months so it sounds like a quite complex issue but if you think about it using divide and conquer it's not as difficult as you would expect it to be it's a medium problem and you can see that what basically it's trying to do is first it needs to divide this list into half right and then the second step once you divide this list into the half what you would need to do is the second value is started taking is from the end of the second half and then going backwards so that's why the second value is four and then it goes to three right so then you can think about it the next step will be reverse the second half of the list right and then once you do that and then the last one will be merge the to list basically you want to the last step you wanted to do is merge the first half and the second half and once you understand the concept the code is actually quite straightforward so i'm so the first step we wanna so the first step we wanna divide this list into half and this is a divide this list into half and this is a super classic linked list question and super classic linked list question and you should be able to code this even you should be able to code this even with your eyes closed so how you do this with your eyes closed so how you do this is that you want to have a slow and a is that you want to have a slow and a faster pointer and put both of them on faster pointer and put both of them on hat and while fast and fast on next hat and while fast and fast on next you want to be able to move faster you want to be able to move faster that's why you want to make sure fast or that's why you want to make sure fast or next is not no next is not no while while this this is true then you want to make sure slow is true then you want to make sure slow moves one basically slow equals to slow moves one basically slow equals to slow to to next and then fast equals to fast down next and then fast equals to fast down next dot next basically slow next dot next basically slow move one fast move two you don't need to move one fast move two you don't need to return anything while return anything while fast is at the end of the list slow is fast is at the end of the list slow is in the middle for an even list like this in the middle for an even list like this if you put your hat in if you put your hat in or if you put the fast on the head or if you put the fast on the head position position for an even list like this the slow will for an even list like this the slow will be at three instead of two this is what be at three instead of two this is what you need to know so we already divided you need to know so we already divided list into list into half first linked list is one two and half first linked list is one two and the second linked list is three to four the second linked list is three to four so then the second step what we would do so then the second step what we would do is we will reverse the second half of is we will reverse the second half of the list the list how do we reverse the the second half of how do we reverse the the second half of the list this is also a very classic the list this is also a very classic problem so i'm gonna do this uh problem so i'm gonna do this uh iterate uh i'm just gonna iterate iterate uh i'm just gonna iterate through the second half of the list and through the second half of the list and i'm gonna give a pre-value and give a i'm gonna give a pre-value and give a current pointer and the proof should be current pointer and the proof should be at no position imagine the 3 is pointing at no position imagine the 3 is pointing to a no before that and then the current to a no before that and then the current is pointing to the slow which is the hat is pointing to the slow which is the hat which is the head of the second which is the head of the second half of the list and then half of the list and then while current you want to go through the while current you want to go through the list and list and swap every single value so i'm going to swap every single value so i'm going to save a pointer as save a pointer as current.next to the temp value and then current.next to the temp value and then this is pretty standard the current.nx this is pretty standard the current.nx equals to brief basically reversed the equals to brief basically reversed the link to make the three point to the link to make the three point to the previous value and then the proof needs previous value and then the proof needs to move to current to move to current and then current will have to equal to and then current will have to equal to the temp that we previously saved the temp that we previously saved by doing this you already reversed the by doing this you already reversed the list and the hack head of the second list and the hack head of the second list will be at the brief position and list will be at the brief position and that the proof is pointing to that the proof is pointing to four right now four right now so once you so once you reverse the second half what you need to reverse the second half what you need to do as the last step you just merge these do as the last step you just merge these two lists so you have a first the list two lists so you have a first the list and the second list right and then the and the second list right and then the first list is pointing to the head right first list is pointing to the head right and then the second list that you and then the second list that you already already reversed it and reversed it and the head is pointing to the pre position the head is pointing to the pre position which is at 4 here so you want to make which is at 4 here so you want to make sure sure second dot next does not equal to zero second dot next does not equal to zero when you merge this list and then you when you merge this list and then you can see first dot next and our first can see first dot next and our first value value first dot next basically which is one first dot next basically which is one one is pointing to one is pointing to four four four is uh second in this case right so four is uh second in this case right so first on x equals to second and then you first on x equals to second and then you wanna move the pointer first move to wanna move the pointer first move to first the dot next first the dot next and then the next step you want to do is and then the next step you want to do is second dot next and the second second dot next and the second and then after you put four here the and then after you put four here the second dot next you want to make sure second dot next you want to make sure it's pointing back to first which is two it's pointing back to first which is two right so you want to make sure right so you want to make sure second dot next pointing to first and second dot next pointing to first and second pointing to second.next basically second pointing to second.next basically move the move the pointer pointer by doing this do not return anything by doing this do not return anything modify had in place instead by doing modify had in place instead by doing this you already successfully merged and this you already successfully merged and reorganized this list let's submit the reorganized this list let's submit the result here result here and we can see it went through and we can see it went through if you like the video please give it a if you like the video please give it a thumbs up and subscribe to my channel thumbs up and subscribe to my channel and i'll have more legal video come up and i'll have more legal video come up for you soon thank you bye
2024-03-21 12:41:09
143
https://i.ytimg.com/vi/3…axresdefault.jpg
LEETCODE 143 REORDER LIST PYTHON | Linked list medium leetcode question
_368LLBvbc8
hi there this side viewing so welcome again we are solving one more welcome again we are solving one more question and this is questions from lead question and this is questions from lead code daily practice question and the code daily practice question and the question name is uh minimum deletion to question name is uh minimum deletion to make the character frequency unique make the character frequency unique so the question name is already uh uh so the question name is already uh uh explaining what we are going to do we explaining what we are going to do we have to just uh have to just uh unique we have to make all the frequency unique we have to make all the frequency unique unique from the string of character let me go from the string of character let me go through the question statement so it through the question statement so it will give a clear idea what what i am will give a clear idea what what i am going to say going to say so here it is given like a string is so here it is given like a string is good if there are no two different good if there are no two different character in s have the same frequency character in s have the same frequency what just frequency refer here what just frequency refer here let me clarify that once what this let me clarify that once what this frequency means so so for example if so for example if the string is like a the string is like a b b c c a a b b like this if the string is this then like this if the string is this then then every particular like for example then every particular like for example say a is having two frequencies because say a is having two frequencies because it came two time in whole whole sequence it came two time in whole whole sequence so is having two frequency b is also so is having two frequency b is also having two frequency because it is also having two frequency because it is also coming to game two time in the coming to game two time in the whole line like if you notice that here whole line like if you notice that here it's b it's b and here also so it's having two and here also so it's having two frequency same as c frequency same as c c is having one frequency because it's c is having one frequency because it's game one time so what what is our goal game one time so what what is our goal we have to make all unique and we by we have to make all unique and we by deleting minimum number of character deleting minimum number of character it's having frequency one so let me go it's having frequency one so let me go through the statement again through the statement again so here it is given that given a string so here it is given that given a string as return the minimum number of as return the minimum number of character you need to delete character you need to delete minimum number of character you need to minimum number of character you need to delete to make s as good delete to make s as good so so here in in this example uh this is s for here in in this example uh this is s for let's say this is s s is equal to let's say this is s s is equal to a a a a so a b c a b right is having two b is so a b c a b right is having two b is having two c is having one frequency having two c is having one frequency it's not good because these two it's not good because these two character matches character matches have having the same frequency they have having the same frequency they match that frequency so anyhow we need match that frequency so anyhow we need to make it as good and we have to remove to make it as good and we have to remove minimum so what we can do we just remove minimum so what we can do we just remove one b right minus one b one b right minus one b minus one here minus one here so now what is the final frequency count so now what is the final frequency count we have now let me write here we have now let me write here oh it's not good color let me write here oh it's not good color let me write here like a is having two frequencies okay like a is having two frequencies okay b is also having one frequency now b is also having one frequency now and if you notice that c is also having and if you notice that c is also having one still it's not good so anyhow we one still it's not good so anyhow we need to remove one more character from need to remove one more character from this two so we are removing let's say c this two so we are removing let's say c or b we can remove any one or b we can remove any one so minus one here so minus one here minus one minus one minus one here right so now what is the minus one here right so now what is the final count now now the final count is a final count now now the final count is a is having two is having two b is having one b is having one and c is having zero frequency so c is and c is having zero frequency so c is not there in the whole not there in the whole sequence sequence so basically we removed two things one b so basically we removed two things one b and and one's this is the one's this is the this is what the minimization we can do this is what the minimization we can do we can't uh minimize like one we can't uh minimize like one one is one is minimum then two but uh if one is one is minimum then two but uh if we remove one character then we can't we remove one character then we can't achieve this uh this output like all is achieve this uh this output like all is having unique you can see that two one having unique you can see that two one and one nothing is repeated here and one nothing is repeated here so yeah this is what a question want to so yeah this is what a question want to say let me go through this test cases a say let me go through this test cases a b so here we have s is equal to b so here we have s is equal to a a b right a a b right a a a a b b so it's already good sequence so we so it's already good sequence so we don't need to remove any character for don't need to remove any character for example let's say frequency of a is 2 example let's say frequency of a is 2 right right frequency of b is 1 both are unique it's frequency of b is 1 both are unique it's not same frequency not same frequency so so answer is 0 in this case we can't remove answer is 0 in this case we can't remove anything anything so let me take through the logic what we so let me take through the logic what we are trying to build right now so are trying to build right now so let me take this sequence let me take this sequence three times a three times a three time b and two times c right three three time b and two times c right three time a time a three time b three time b and and 2 times c right 2 times c we have 2 times c right 2 times c we have so this is our s here so this is our s here so there is so there is map we are using map here because i map we are using map here because i already discussed in my last video like already discussed in my last video like map is very useful for counting map is very useful for counting frequency frequency so let me recall that what is the map so let me recall that what is the map map is nothing map is just a map is nothing map is just a collection of keys and value so here collection of keys and value so here character is our key and its frequency character is our key and its frequency is value for us so in simply we declare is value for us so in simply we declare one map for example let's say we declare one map for example let's say we declare this empty map right now in this map this empty map right now in this map we're storing that a is having three we're storing that a is having three frequency frequency like this like this a is having three frequency a is having three frequency p is also having three frequency p is also having three frequency and c is also having two frequency okay and c is also having two frequency okay we done our half half task we done our half half task map is very helpful for this uh this map is very helpful for this uh this type of frequency count things so we type of frequency count things so we just uh just uh count all this thing like the frequent count all this thing like the frequent character and its frequency here we did character and its frequency here we did okay okay so so now we check that now we check that now we try to now we try to uh this grab this type this frequency in uh this grab this type this frequency in separate things like for example let's separate things like for example let's say declare one empty vector say declare one empty vector vector say initially it's it's having vector say initially it's it's having maximum size let's say infinite it maximum size let's say infinite it infinites infinites long big so we just take 10 to the power long big so we just take 10 to the power 5 as empty vector initially all are 5 as empty vector initially all are having zeros in it having zeros in it right it's all having zero right it's all having zero and till and and till and we initialize it's zero now we just we initialize it's zero now we just store the uh this frequency count store the uh this frequency count at the place of three like for example at the place of three like for example say vector of three say vector of three is is there any element having uh is is there any element having uh frequency three so we check vector of 3 frequency three so we check vector of 3 is already 0 here if it's 0 it's mean is already 0 here if it's 0 it's mean not a character which is behind this a not a character which is behind this a behind this a no one is there so it's a behind this a no one is there so it's a first character so first character so vector of 3 is 0 yes this condition is vector of 3 is 0 yes this condition is fulfilled so it means that we don't have fulfilled so it means that we don't have anything having anything having three frequency right now at three frequency right now at first position at first position is only first position at first position is only having three frequency and it's not having three frequency and it's not matching frequency with other character matching frequency with other character so we simply erase this zero and you so we simply erase this zero and you simply update it to one right simply update it to one right we update it to one here okay done now we update it to one here okay done now we move ahead to b we move ahead to b now we check for b now we check for b and what is what we have and what is what we have now you do the same task for b now you do the same task for b we just check vector what is the we just check vector what is the frequency of b 3 so we check back v of 3 frequency of b 3 so we check back v of 3 is it 0 or 1 is it 0 or 1 so it's not 0 right so it's not 0 right it's not 0 so it means that it match it's not 0 so it means that it match with with someone's frequency so we just need to someone's frequency so we just need to check its back we just remove 1b so now check its back we just remove 1b so now the count of b is two here minus one so the count of b is two here minus one so count of b is two right count of b is two right so we check vector of two so we check vector of two it means that is there any character it means that is there any character having frequency two having frequency two so we check and it's 0 here it's 1 here so we check and it's 0 here it's 1 here it's 2 here i just i'm just writing it's 2 here i just i'm just writing index here so vector of 2 is 0 it means index here so vector of 2 is 0 it means that no character having frequency that no character having frequency 2 so we just simply 2 so we just simply update the value of update the value of v of 2 here with v of 2 here with 1 1 let me erase this 0 let me erase this 0 okay okay so here i just put one okay so here i just put one okay so here we remove one correct in in one so here we remove one correct in in one answer in answer variable we are just answer in answer variable we are just uh storing the removal of character so uh storing the removal of character so right now we remove one car one b right now we remove one car one b one let me write in bracket that is b one let me write in bracket that is b okay okay okay now we move to c okay now we move to c for c for c again we check v of again we check v of frequency of c so frequency of c so v of v of frequency of c is 2 right frequency of c is 2 right so we check v of so we check v of 2 is 0 2 is 0 so so v of 2 is 0 let me check v of 2 is 1 so v of 2 is 0 let me check v of 2 is 1 so it's not 0 right it's not 0 so what we it's not 0 right it's not 0 so what we can do we just remove 1 c so let's see can do we just remove 1 c so let's see because frequency of c is 1 now because frequency of c is 1 now now we check v of one is zero we remove now we check v of one is zero we remove one character so we need to add an one character so we need to add an answer variable that plus one answer variable that plus one c c okay okay plus one see i add here so now we check plus one see i add here so now we check v of frequency of c so is there any v of frequency of c so is there any character having frequency one character having frequency one previously we check if it's zero then no previously we check if it's zero then no character match with frequency of c and character match with frequency of c and yes it is zero if you cannot see yes it is zero if you cannot see it is zero right it is zero right so yeah we're done and we so yeah we're done and we and no character left here so our answer and no character left here so our answer is 1 plus 1 2 in this case is 1 plus 1 2 in this case so yeah our answer is 2 so yeah our answer is 2 so this is the basic logic uh it's so this is the basic logic uh it's messier it i hope you got understand the messier it i hope you got understand the logic what we are trying to build let me logic what we are trying to build let me take one more small example so you get a take one more small example so you get a clear idea what we are trying to do here clear idea what we are trying to do here let me take uh easy example like for let me take uh easy example like for example say example say is having two frequency is having two frequency b is having b is having three frequency three frequency and c is having one frequency so in this and c is having one frequency so in this case we are not having case we are not having we don't need to do anything because a we don't need to do anything because a is having two frequency is having two frequency right right now it's unique right right now it's unique b is also having three frequency it's b is also having three frequency it's also unique also unique right right c is also having c is also having one frequency so all are unique so we one frequency so all are unique so we don't need to remove any character don't need to remove any character simply print answer is equal to zero simply print answer is equal to zero answer its answer its answer is equal to zero right in this answer is equal to zero right in this case case so let me try to jump to the coding part so let me try to jump to the coding part so you might get clear idea what we are so you might get clear idea what we are trying to do here trying to do here so firstly let me declare map because we so firstly let me declare map because we count count because we count because we count character and its frequency so i write character and its frequency so i write character for in first place it's for character for in first place it's for example this is a map example this is a map this is whole it's map it's map this is whole it's map it's map right this is a map look like and first right this is a map look like and first character in first character in first in first place we in key we are simply i in first place we in key we are simply i can say in key we are storing character can say in key we are storing character in its value is integer type so i'm just in its value is integer type so i'm just declaring that character map having declaring that character map having character an integer name is m and i character an integer name is m and i simply traverse through simply traverse through this string this string and i just and i just i'm just counting its frequency right i'm just counting its frequency right so m of s of i so m of s of i plus plus okay plus plus okay so now so now from this stage i am having frequency from this stage i am having frequency for example let's say s for example let's say s for example let's say s is equal let me for example let's say s is equal let me take s s is equal to this one uh yeah we discussed this now okay let me take this only and we dry run while writing the code so s is equal to this right in map we get like in map we get like a a comma comma a a a comma 3 a comma 3 next element we get next element we get b comma 3 b comma 3 and third element and third element in map we get in map we get c comma two so this is what we have c comma two so this is what we have right now right now now simply now simply we go through the map every element like we go through the map every element like in first element in second element using in first element in second element using iterator because we traverse in map iterator because we traverse in map using iterator only using iterator only so auto let me say x has let me say i so auto let me say x has let me say i has iterator has iterator or m or m now we have access to first element now we have access to first element right now right now what we are checking what we are checking if we are at first element so what we if we are at first element so what we are checking we are checking are checking we are checking uh uh frequency of that frequency of that frequency of that uh character in vector frequency of that uh character in vector if it's zero so it's well and good we if it's zero so it's well and good we just move ahead if it's not zero so we just move ahead if it's not zero so we need to decrease so we need to decrease need to decrease so we need to decrease our answer and check previously views our answer and check previously views like that so let's code that part so for like that so let's code that part so for that we need to declare one empty way that we need to declare one empty way vector let me see it's in here and let me take one big size one zero one zero one zero it's it's enough for this question because ten to the power pi is the maximum range if you can notice here 10 to the power 5 is the maximum range so it's can't exit this limit so yeah so what we are doing we just check v of i dot second because in second as you can see here in second in in every element of map we are storing the frequency in integers i dot second if it's zero so we simply mark it one because no element matching its frequency so i dot second is it is equal to one so it's good yeah else what we are doing else it means that in vector for example let's say vector here in fact let me declare one small vector and let's say it's zero here it's zero here it's one here it's one near it's one here and zero and zero and let me write it index one two three four and five right so now let's say while so here we have so it's count uh it's mark as one it's mean that previous character having the same frequency as this character for example we are checking this b it means that previously there is lots of element here it's having someone having the same count as b so we just minus 1 and checking until we reach 0 it means we need we reach a unique character frequency count where the no one having the same frequency so for that's why we are running while loop here while we check that v of i dot is one it means it's one we can write is one it means it's one we can write here one by defaults take one here one by defaults take one so so until we reach to the zero until we reach to the zero when we have to stop that's why we are when we have to stop that's why we are using while until it's one we have to using while until it's one we have to run this loop run this loop so that time we just need what we are so that time we just need what we are doing we just increment one frequency i doing we just increment one frequency i mean seven character mean seven character and in answer variable let me declare and in answer variable let me declare one answer variable also here one answer variable also here where we are storing where we are storing in in answer variable we just increment in in answer variable we just increment the count of the count of that removal of character right that removal of character right and if we reach for example if we reach and if we reach for example if we reach that that i dot second i dot second is equal to 0 then we need to break is equal to 0 then we need to break because because we have 5 elements so we need we have we have 5 elements so we need we have like for example c is having 5 elements like for example c is having 5 elements so we maximum to maximum remaining 5 so we maximum to maximum remaining 5 from c and c is not no longer exist in from c and c is not no longer exist in map so that's why we need to map so that's why we need to include this and if simply right here include this and if simply right here i thought i thought second is greater than equal to zero and second is greater than equal to zero and so simply mark it out to one this one and coming out this following we have all the counts of removal of element in our answer variable and we simply run it out and it's got and it's got giving correct out let me submit out the giving correct out let me submit out the code code and and it got accepted so thank you for watching if you guys have any doubt related to this question you can simply comment down in comment box or you can reach to my telegram channel we can
2024-03-19 18:08:28
1,647
https://i.ytimg.com/vi/_…axresdefault.jpg
1647 Minimum Deletions to Make Character Frequencies Unique || LeetCode daily practice question
evUFsOb_iLY
hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve the problem push dominoes let's solve the problem push dominoes there are n dominoes in a line and there are n dominoes in a line and they're placed vertically they're placed vertically but some of them could be either leaning but some of them could be either leaning to the left or leaning to the right and to the left or leaning to the right and after each second passes each domino after each second passes each domino that is you know leaning i say the word that is you know leaning i say the word leaning but they say falling to the left leaning but they say falling to the left pushes the adjacent domino that's to the pushes the adjacent domino that's to the left of it and the same thing with left of it and the same thing with dominoes that are leaning towards the dominoes that are leaning towards the right if there were two adjacent right if there were two adjacent dominoes like this and this right like dominoes like this and this right like how this one is leaning to the right how this one is leaning to the right this one is leaning to the left uh you this one is leaning to the left uh you know if they were leaning like this then know if they were leaning like this then they would get stuck right one isn't they would get stuck right one isn't going to fall over because they're both going to fall over because they're both kind of pushing against each other kind of pushing against each other if there was a domino in the middle if there was a domino in the middle between these they would be leaning between these they would be leaning against the one in the middle and then against the one in the middle and then the one in the middle uh would stay the one in the middle uh would stay standing up so basically there are three standing up so basically there are three states that a domino can be in it can states that a domino can be in it can either be standing straight up which is either be standing straight up which is the simple case right and that is the simple case right and that is represented by a dot and then left is represented by a dot and then left is meaning that the domino was pushed to meaning that the domino was pushed to the left so this domino is pushed to the the left so this domino is pushed to the left now a domino that's pushed to the left now a domino that's pushed to the left could you know be falling it could left could you know be falling it could be stuck like this one over here right be stuck like this one over here right this one is stuck leaning in the left this one is stuck leaning in the left position or it could be like this one position or it could be like this one which is leaning to the left and then which is leaning to the left and then maybe it actually just completely falls maybe it actually just completely falls over over to the left side that is also considered to the left side that is also considered a status of l like that state is a status of l like that state is included in this so if it fell over to included in this so if it fell over to the left or it's just leaning to the the left or it's just leaning to the left it's still represented by a l and left it's still represented by a l and that's actually a very important point that's actually a very important point that we're going to use in this problem that we're going to use in this problem because it basically tells us that if a because it basically tells us that if a domino was initially leaning to the left domino was initially leaning to the left its state is always going to be left its state is always going to be left because it's either going to get stuck because it's either going to get stuck in this position or it's going to in this position or it's going to completely fall over in both cases it's completely fall over in both cases it's still left similarly with dominoes that still left similarly with dominoes that are leaning to the right if it's leaning are leaning to the right if it's leaning to the right or if it falls over it's to the right or if it falls over it's still considered r okay but enough still considered r okay but enough abstractions let's get into an example abstractions let's get into an example actually before we do that remember what actually before we do that remember what we're trying to do is uh get the final we're trying to do is uh get the final state of the dominoes i didn't mention state of the dominoes i didn't mention that yet but that's pretty much what that yet but that's pretty much what we're trying to do each second that we're trying to do each second that passes a domino could potentially you passes a domino could potentially you know get stuck like these ones or if know get stuck like these ones or if there was you know this dominoes leaning there was you know this dominoes leaning to the right and this domino maybe this to the right and this domino maybe this domino will push this one over but let's domino will push this one over but let's take a look at an example okay so now take a look at an example okay so now let's take a look at a couple examples let's take a look at a couple examples the first one is pretty simple so let's the first one is pretty simple so let's just start with it so we have r just start with it so we have r r r dot l so that means this domino is dot l so that means this domino is leaning to the right this is leaning to leaning to the right this is leaning to the right this is straight up this one the right this is straight up this one is leaning to the left so after each is leaning to the left so after each second passes each domino is going to second passes each domino is going to tip over well after one second what's tip over well after one second what's going to happen well not much is going going to happen well not much is going to happen with these three dominoes you to happen with these three dominoes you can see they're both going to push up can see they're both going to push up against this one at the same time so against this one at the same time so pretty much they're going to get stuck pretty much they're going to get stuck like this right these three dominoes are like this right these three dominoes are going to get stuck this one's not going going to get stuck this one's not going to move it's going to stay standing to move it's going to stay standing straight up but this one is just going straight up but this one is just going to fall over i guess i don't know if to fall over i guess i don't know if it's going to push against this one it's going to push against this one because this one should push up against because this one should push up against this one but they're both already this one but they're both already falling to the right so it doesn't falling to the right so it doesn't really change anything i mean maybe this really change anything i mean maybe this one will completely fall over but the one will completely fall over but the state is not going to change and that's state is not going to change and that's the important part the state here is the important part the state here is still r r dot l so nothing really still r r dot l so nothing really changed but the second example is a bit changed but the second example is a bit more interesting so the question is how more interesting so the question is how to even approach this problem in a to even approach this problem in a systematic way well one thing i systematic way well one thing i mentioned first was pretty important mentioned first was pretty important anything that starts out as left or anything that starts out as left or right is always going to stay in that right is always going to stay in that state so we're trying to look for the state so we're trying to look for the return state that we're going to you return state that we're going to you know return the dominoes in well we know know return the dominoes in well we know that these ones that i've highlighted that these ones that i've highlighted are not going to change at all what we are not going to change at all what we have to figure out is what about the have to figure out is what about the remaining ones how are they going to remaining ones how are they going to change and how can we do that well change and how can we do that well there's actually multiple solutions to there's actually multiple solutions to this problem and you can check out some this problem and you can check out some of them of them officially on leak code if you want one officially on leak code if you want one that they didn't mention though i think that they didn't mention though i think is the simplest it's actually pretty is the simplest it's actually pretty much the brute force not really brute much the brute force not really brute force but it's actually more of a force but it's actually more of a simulation right because this is the simulation right because this is the state that we're given right these are state that we're given right these are the dominoes that are leaning and so of the dominoes that are leaning and so of course the ones that are standing course the ones that are standing straight up they're not going to knock straight up they're not going to knock each other over only these dominoes that each other over only these dominoes that are left or right could knock other are left or right could knock other dominoes over so these are the ones we dominoes over so these are the ones we should pay attention to and by should pay attention to and by simulation what i mean is simulation what i mean is we should check on the first go-around we should check on the first go-around basically simulating a second right one basically simulating a second right one second what's going to happen after one second what's going to happen after one second to our dominoes to figure that second to our dominoes to figure that out we should probably look at these out we should probably look at these dominoes that are leaning over right now dominoes that are leaning over right now and maybe these dominoes are going to and maybe these dominoes are going to knock other ones over maybe this domino knock other ones over maybe this domino is going to change to being right then is going to change to being right then on the second second we should look at on the second second we should look at what that domino is going to do now so what that domino is going to do now so basically with each second we're going basically with each second we're going to have a queue of dominoes that we're to have a queue of dominoes that we're going to look at right now our queue is going to look at right now our queue is this these ones that i've highlighted this these ones that i've highlighted these are the ones we have to look at these are the ones we have to look at and see how they're going to affect the and see how they're going to affect the dominoes that they are dominoes that they are adjacent to so i'm not going to draw out adjacent to so i'm not going to draw out the entire thing in the interest of time the entire thing in the interest of time but we will code up the official but we will code up the official solution but what we're going to say now solution but what we're going to say now is that these ones left right and all is that these ones left right and all these have been added to a queue right these have been added to a queue right and we're now we're going to process and we're now we're going to process them in our queue we're just going to do them in our queue we're just going to do this from left to right because it's this from left to right because it's simple we could do right to left if we simple we could do right to left if we wanted as well but it is going to be wanted as well but it is going to be important for us to do them in order we important for us to do them in order we should either do left to right or right should either do left to right or right to left and you'll see why in a second to left and you'll see why in a second but now let's start at the left one okay but now let's start at the left one okay this one is leaning to the left it's this one is leaning to the left it's going to fall over to the left the first going to fall over to the left the first thing we should ask ourselves is there thing we should ask ourselves is there anything to the left of it yes there is anything to the left of it yes there is is that domino standing straight up yes is that domino standing straight up yes it is so what's going to happen now well it is so what's going to happen now well this domino is going to knock over this this domino is going to knock over this domino yeah so what we should do now domino yeah so what we should do now let's say this has been popped from our let's say this has been popped from our queue so we don't have to look at it queue so we don't have to look at it again and it'll obviously never knock again and it'll obviously never knock over any different dominoes but this one over any different dominoes but this one over here now is going to be a over here now is going to be a left domino but the question you might left domino but the question you might be wondering is if a domino is falling be wondering is if a domino is falling over to the left right this one left over to the left right this one left what if there was another domino to the what if there was another domino to the right that was falling over there so in right that was falling over there so in that case this one in the middle would that case this one in the middle would not be changed to a left domino it would not be changed to a left domino it would actually stay the exact same well that's actually stay the exact same well that's why the order comes into play we know why the order comes into play we know that since this is the first domino that that since this is the first domino that there weren't any dominoes to the left there weren't any dominoes to the left of it that could have knocked it over to of it that could have knocked it over to the right and we know that because we the right and we know that because we started all the way at the left but if started all the way at the left but if we do get any dominoes that are leaning we do get any dominoes that are leaning to the right we don't know for sure that to the right we don't know for sure that there aren't uh that there isn't a left there aren't uh that there isn't a left domino to the right of it that could domino to the right of it that could make the one in the middle stand make the one in the middle stand straight up and that's the example that straight up and that's the example that we're actually faced with next now we we're actually faced with next now we have a right domino and so it's leaning have a right domino and so it's leaning to the right what is to the right of it to the right what is to the right of it a domino's standing straight up so of a domino's standing straight up so of course this one should be changed to course this one should be changed to right but before we confirm that it right but before we confirm that it should be changed or right we should should be changed or right we should look at the domino actually one space look at the domino actually one space over and confirm that this is not a left over and confirm that this is not a left domino in this case it's not a left domino in this case it's not a left domino so domino so we were correct this domino in the we were correct this domino in the middle is going to be to the right but middle is going to be to the right but if there was a left domino over here if there was a left domino over here then we would not have changed this one then we would not have changed this one in the middle but for now let's cross in the middle but for now let's cross this out and then let's go to the next this out and then let's go to the next domino in our queue which is going to be domino in our queue which is going to be this one that is leaning to the left and this one that is leaning to the left and we look at the value to the left of it we look at the value to the left of it it's a domino standing straight up so it's a domino standing straight up so it's going to be changed to a left it's going to be changed to a left domino again we didn't have to check the domino again we didn't have to check the value to the left of it to check that it value to the left of it to check that it was a right domino because we only have was a right domino because we only have to do that with right dominoes anyway to do that with right dominoes anyway and that will probably make a bit more and that will probably make a bit more sense when we actually get into the code sense when we actually get into the code because it's kind of hard to kind of because it's kind of hard to kind of explain in words exactly what i mean but explain in words exactly what i mean but basically what i'm saying is if there basically what i'm saying is if there was a right domino over here then we was a right domino over here then we would have detected okay there's a left would have detected okay there's a left domino over here and then we would have domino over here and then we would have said okay then the one in the middle is said okay then the one in the middle is standing straight up so then on the next standing straight up so then on the next iteration when we pop from our queue iteration when we pop from our queue we'd actually just skip this domino we'd actually just skip this domino because we already know that these two because we already know that these two dominoes counteracted each other and dominoes counteracted each other and then we'd go to the next domino but that then we'd go to the next domino but that wasn't the case so we don't have to do wasn't the case so we don't have to do that but that's why anytime we have a that but that's why anytime we have a left domino we don't actually have to left domino we don't actually have to check check what came before it okay now to this what came before it okay now to this domino oh by the way we're done with domino oh by the way we're done with this one so let's cross it out now to this one so let's cross it out now to this right domino uh let's kind of fast this right domino uh let's kind of fast forward okay there's uh sanding straight forward okay there's uh sanding straight up domino what about what comes after it up domino what about what comes after it is there a left dominant here nope so in is there a left dominant here nope so in that case uh this dominant is actually that case uh this dominant is actually going to be changed to a right domino going to be changed to a right domino because this one tipped this one over uh because this one tipped this one over uh and then we're done with this one and then we're done with this one and then we get to our last domino over and then we get to our last domino over here and this domino knocks over the one here and this domino knocks over the one that's to the left of it so that one that's to the left of it so that one becomes a left domino and then we're becomes a left domino and then we're done with that now notice how all of done with that now notice how all of that happened within one second that was that happened within one second that was our first iteration through our queue our first iteration through our queue and in one second we updated the state and in one second we updated the state of all the dominoes but remember we're of all the dominoes but remember we're not looking for one second we're looking not looking for one second we're looking for the final state of the dominoes how for the final state of the dominoes how do we even know if we reach the final do we even know if we reach the final state well basically after our q is state well basically after our q is empty because right now we have a bunch empty because right now we have a bunch of new dominoes that were just tipped of new dominoes that were just tipped over either these dominoes are going to over either these dominoes are going to be standing you know going to basically be standing you know going to basically be caught together basically stuck or be caught together basically stuck or they have been knocked over they have been knocked over to being flat but basically to figure to being flat but basically to figure that out we will have to continue that out we will have to continue through this queue okay first domino through this queue okay first domino over here it's leaning to the left over here it's leaning to the left there's nothing to the left of it though there's nothing to the left of it though so i guess this domino didn't really do so i guess this domino didn't really do anything obviously it's state didn't anything obviously it's state didn't change it's still a left domino but we change it's still a left domino but we don't have to look at it in our queue don't have to look at it in our queue anymore okay next domino is a right anymore okay next domino is a right domino okay so we look at what's to the domino okay so we look at what's to the right of it it's a domino standing right of it it's a domino standing straight up but now is there another straight up but now is there another domino that's leaning to the left the domino that's leaning to the left the reason we're checking that is because in reason we're checking that is because in this case that would mean that two this case that would mean that two dominoes are causing the one in the dominoes are causing the one in the middle to be stuck and that's exactly middle to be stuck and that's exactly the case here so in this case this right the case here so in this case this right domino over here is not going to knock domino over here is not going to knock this one over because there's a left this one over because there's a left domino over here so it's going to be domino over here so it's going to be standing straight up so in this case we standing straight up so in this case we do pop this from our queue but this one do pop this from our queue but this one does not change and since we already saw does not change and since we already saw that this one this domino is leaning to that this one this domino is leaning to the left and it's causing this one to be the left and it's causing this one to be stuck we don't even have to look at this stuck we don't even have to look at this one we actually skip this domino so we one we actually skip this domino so we pop this one even though we didn't do pop this one even though we didn't do anything with it because we know that anything with it because we know that these two caused each other to be stuck these two caused each other to be stuck you'll have to pay attention to how i you'll have to pay attention to how i handle this in the code it's actually handle this in the code it's actually pretty simple in the code but it's kind pretty simple in the code but it's kind of hard to understand the intuition of of hard to understand the intuition of why we're doing this okay next we have a why we're doing this okay next we have a right domino so we look at the one that right domino so we look at the one that comes after it it's not a domino that's comes after it it's not a domino that's standing straight up it's a left domino standing straight up it's a left domino so we don't do anything so what we would so we don't do anything so what we would say with this right dominoes okay it's say with this right dominoes okay it's not a we can't knock it over so we don't not a we can't knock it over so we don't do anything so we just pop this from our do anything so we just pop this from our queue then we check this left domino is queue then we check this left domino is this standing straight up nope the one this standing straight up nope the one that came before is not standing that came before is not standing straight up so we can't do anything straight up so we can't do anything either in this case right so we don't do either in this case right so we don't do anything with either of these now in the anything with either of these now in the context of this problem that means that context of this problem that means that two dominoes were standing straight up two dominoes were standing straight up and they were just kind of counteracting and they were just kind of counteracting each other well not straight up but they each other well not straight up but they were just leaning against each other were just leaning against each other right okay but now you can see that we right okay but now you can see that we have no more dominoes that are leaning have no more dominoes that are leaning over i really hope i did this correctly over i really hope i did this correctly so so correct me if i'm wrong but i so so correct me if i'm wrong but i think this is kind of what our state think this is kind of what our state would be ll you know a bunch of would be ll you know a bunch of characters and i think that does match characters and i think that does match pretty much exactly with what they had pretty much exactly with what they had in the output so i think we're good to in the output so i think we're good to go by the way this uh the time go by the way this uh the time complexity of the solution is going to complexity of the solution is going to be big o of n because in the worst case be big o of n because in the worst case every single domino could be added to every single domino could be added to the queue and then popped from the queue the queue and then popped from the queue so basically big o of n time complexity so basically big o of n time complexity and also big o of n memory complexity and also big o of n memory complexity because our q is going to potentially because our q is going to potentially contain every single domino that was contain every single domino that was given to us in the input believe it or given to us in the input believe it or not this is actually the simplest not this is actually the simplest solution in my opinion it's the most solution in my opinion it's the most intuitive there's actually a few more intuitive there's actually a few more complicated solutions but they're also complicated solutions but they're also just as efficient as this one so i think just as efficient as this one so i think this one is the preferred solution in my this one is the preferred solution in my opinion so now let's code it up okay so opinion so now let's code it up okay so now let's cut it up first thing you're now let's cut it up first thing you're going to notice is the dominoes are going to notice is the dominoes are actually given to us in a string it actually given to us in a string it would probably be helpful for us to would probably be helpful for us to convert that into a list the main convert that into a list the main reasoning is because as we're going to reasoning is because as we're going to be updating the dominoes you can't be updating the dominoes you can't really update a character in a string in really update a character in a string in python so if we convert it to a list we python so if we convert it to a list we can update the character at any index of can update the character at any index of that list also don't forget we're going that list also don't forget we're going to be using a q so let's do that in to be using a q so let's do that in python a double ended queue you can do python a double ended queue you can do like that and then the way we want to like that and then the way we want to initialize our q initialize our q is basically uh first of all i'm going is basically uh first of all i'm going gonna enumerate through all the dominoes gonna enumerate through all the dominoes so our list of dominoes we're gonna get so our list of dominoes we're gonna get the index and the domino that's what the index and the domino that's what we're doing in python here is the index we're doing in python here is the index d is the domino we want to add all the d is the domino we want to add all the dominoes that are not standing straight dominoes that are not standing straight up to our cue initially right just like up to our cue initially right just like we did in the drawing we want to we did in the drawing we want to queue.append each domino if it's not queue.append each domino if it's not standing straight up and actually uh standing straight up and actually uh we're going to be adding a pair of we're going to be adding a pair of values to our queue so we're going to values to our queue so we're going to actually include the index because actually include the index because you're going to see that the index is you're going to see that the index is actually going to come in handy actually going to come in handy because you know after we pop a domino because you know after we pop a domino from our queue we want to know the index from our queue we want to know the index of it so that we can check the neighbors of it so that we can check the neighbors of that domino okay now of that domino okay now the code is going to be pretty much the code is going to be pretty much similar to any uh q problems where you similar to any uh q problems where you continue the loop until your cue is continue the loop until your cue is completely empty and each iteration of completely empty and each iteration of the loop we just pop the element from the loop we just pop the element from the queue in this case we're going to the queue in this case we're going to pop the leftmost but from that we're pop the leftmost but from that we're going to get an index and a domino so going to get an index and a domino so there's two cases remember the domino there's two cases remember the domino could be a left domino or it could be a could be a left domino or it could be a right domino we know it's not going to right domino we know it's not going to be standing straight up because if it be standing straight up because if it was then we wouldn't have even added it was then we wouldn't have even added it to our cue so if it's left or right we to our cue so if it's left or right we know that the simple case the more know that the simple case the more simple case is the left one because in simple case is the left one because in that case all we really have to do is that case all we really have to do is check that its left neighbor is standing check that its left neighbor is standing straight up because that means we just straight up because that means we just tipped our left neighbor over how do we tipped our left neighbor over how do we know that our left neighbor exists and know that our left neighbor exists and is standing straight up well first of is standing straight up well first of all i has to be greater than zero all i has to be greater than zero because if it's zero that means we don't because if it's zero that means we don't have any left neighbors so if i is have any left neighbors so if i is greater than zero and if the left greater than zero and if the left neighbor which we can get from dom index neighbor which we can get from dom index i minus 1. you can see that the index is i minus 1. you can see that the index is helpful here if i minus 1 is equal to a helpful here if i minus 1 is equal to a dot that means our left neighbor is dot that means our left neighbor is standing straight up what does that mean standing straight up what does that mean well we're going to first of all add our well we're going to first of all add our left neighbor to the queue its index is left neighbor to the queue its index is i minus one and its value is now going i minus one and its value is now going to be left because we just tipped it to be left because we just tipped it over uh and don't forget to actually over uh and don't forget to actually update it in the dominoes list itself update it in the dominoes list itself because remember that's what we're because remember that's what we're actually going to return in the end i actually going to return in the end i minus 1 is now going to be minus 1 is now going to be left and that's pretty much all there is left and that's pretty much all there is for the left case the right case is a for the left case the right case is a bit more complicated because as we're bit more complicated because as we're going to the right there could be more going to the right there could be more dominoes to the right that we haven't dominoes to the right that we haven't seen yet one thing you might notice seen yet one thing you might notice though from this code is we have two though from this code is we have two nested if statements we could actually nested if statements we could actually get rid of the second one get rid of the second one and combine it with the first one but i and combine it with the first one but i think it's a little bit less intuitive think it's a little bit less intuitive if i just wrote that straight off the if i just wrote that straight off the bat so bat so let's do that and now the opposite case let's do that and now the opposite case first we want to check that we do have a first we want to check that we do have a right neighbor how do we know if we have right neighbor how do we know if we have a right neighbor well i has to be less a right neighbor well i has to be less than the length of dominoes minus one than the length of dominoes minus one there has to be at least one domino to there has to be at least one domino to the right of it and that domino has to the right of it and that domino has to be standing straight up so i plus one be standing straight up so i plus one actually to make this a bit more clearer actually to make this a bit more clearer let's just say that i plus one is less let's just say that i plus one is less than the length of domino right so that than the length of domino right so that basically says that i plus 1 is a valid basically says that i plus 1 is a valid index so then we use that index and then index so then we use that index and then check if it's standing straight up that check if it's standing straight up that means we could potentially knock it over means we could potentially knock it over but we can't knock it over if there but we can't knock it over if there exists an i plus 2 index basically that exists an i plus 2 index basically that means there's a there's actually another means there's a there's actually another domino to the right of this one that's domino to the right of this one that's standing straight up and that domino standing straight up and that domino happens to be a domino that's leaning to happens to be a domino that's leaning to the left so if that's the case which we the left so if that's the case which we can check pretty easily like this can check pretty easily like this uh that means we can't knock this domino uh that means we can't knock this domino over that means this domino is stuck but over that means this domino is stuck but what should we do now well we should pop what should we do now well we should pop from the queue one more time from the queue one more time the reason we're doing this is if we the reason we're doing this is if we don't pop this domino right here that's don't pop this domino right here that's leaning to the left that means on the leaning to the left that means on the next iteration of the loop we're going next iteration of the loop we're going to visit that domino again and then to visit that domino again and then our code is going to run and then this our code is going to run and then this first if statement is gonna run and first if statement is gonna run and what's gonna happen is this left domino what's gonna happen is this left domino is gonna knock over this one even though is gonna knock over this one even though it shouldn't because this one is in it shouldn't because this one is in between two dominoes a right domino and between two dominoes a right domino and a left domino so this one should not be a left domino so this one should not be knocked over that's why we're popping knocked over that's why we're popping this left domino to make sure that that this left domino to make sure that that doesn't happen so we're basically doesn't happen so we're basically skipping this domino but that's only if skipping this domino but that's only if that left domino exists to the right of that left domino exists to the right of this one if that's not the case though this one if that's not the case though then it's the slightly more simple case then it's the slightly more simple case where we just do the generic thing where we just do the generic thing basically tip this domino over and then basically tip this domino over and then append it to the queue just like we kind append it to the queue just like we kind of did up above so i'm actually just of did up above so i'm actually just going to copy and paste these two lines going to copy and paste these two lines copy paste and then say okay domino in copy paste and then say okay domino in this case not i minus one but i plus one this case not i minus one but i plus one is going to be set to a right domino is going to be set to a right domino because it just got knocked over uh and because it just got knocked over uh and also we append it to the queue i plus also we append it to the queue i plus one and it's a right domino not a left one and it's a right domino not a left domino okay and believe it or not that's domino okay and believe it or not that's the entire code i know it kind of
2024-03-22 15:12:29
838
https://i.ytimg.com/vi/e…axresdefault.jpg
Push Dominoes - Leetcode 838 - Python
9Y1jWGkqTKc
welcome to october's leco challenge today's problem is bag of tokens today's problem is bag of tokens you have an initial power p an initial you have an initial power p an initial score of zero score of zero and a bag of tokens where tokens i is and a bag of tokens where tokens i is the value the value of the i token so we have these tokens of the i token so we have these tokens and they have some sort of value and they have some sort of value now our goal is to maximize our total now our goal is to maximize our total score score by potentially playing each token in one by potentially playing each token in one of two ways of two ways if your current power that we have is at if your current power that we have is at least the value of token's i least the value of token's i you may play that token so i guess you may play that token so i guess pop it off or use it somehow and you pop it off or use it somehow and you would lose would lose that amount of token value from your that amount of token value from your power but you would gain one score power but you would gain one score now if your current score is at least now if your current score is at least one but i suppose if you can't play any one but i suppose if you can't play any tokens then you may tokens then you may play the token um gaining that token's play the token um gaining that token's power power into your power source but losing one into your power source but losing one score score now the goal is to maximize our score now the goal is to maximize our score right so you'd only do that right so you'd only do that if you don't have any other option if you don't have any other option so you can play any token at most once so you can play any token at most once and in any and in any order so that's kind of big there if we order so that's kind of big there if we had this example if we had power 150 had this example if we had power 150 100 200 then we would obviously 100 200 then we would obviously we only have one option to eat this we only have one option to eat this token token we would lose so we only have 50 power we would lose so we only have 50 power left and that would be it left and that would be it we can only eat that token we couldn't we can only eat that token we couldn't gain this gain this power if we wanted having us 250 but power if we wanted having us 250 but then there's no other tokens to play so then there's no other tokens to play so our output will be zero here what we our output will be zero here what we would do would do is first play our 100 we'd have a power is first play our 100 we'd have a power of 100 left of 100 left then since we only have 100 what we then since we only have 100 what we would do would do is gain the power of 400 giving us power is gain the power of 400 giving us power 500 and then eat these two tokens 2 and 500 and then eat these two tokens 2 and 3 3 ending up with a score of 2. so there's ending up with a score of 2. so there's this temptation again this temptation again to try to go recursively all right all to try to go recursively all right all we need to do is find every path and we need to do is find every path and every every possible combination that can happen but possible combination that can happen but you got to resist that because you got to resist that because the optimal algorithm is already here the optimal algorithm is already here all we need to do is if we could use a all we need to do is if we could use a token token and gain a score do that can we would do and gain a score do that can we would do that if that if we have power right and we should we have power right and we should probably look at the smallest amount probably look at the smallest amount first because that's going to be the first because that's going to be the least penalty to gain that least penalty to gain that score it's only when we can't do that score it's only when we can't do that anymore that we would look to the anymore that we would look to the maximum maximum token that we have to lose one score but token that we have to lose one score but to gain that power to gain that power and hopefully be able to score more and hopefully be able to score more points points um yeah in this path so um yeah in this path so we would have to store a max score in we would have to store a max score in case we go um case we go um positive and then we lose some score and positive and then we lose some score and we lose that value we lose that value um but that makes it important since we um but that makes it important since we could use this in could use this in any order to sort our tokens right so any order to sort our tokens right so that's the very first thing we want to that's the very first thing we want to do do let's sort our tokens in fact i'm going let's sort our tokens in fact i'm going to actually use to actually use a queue here sorted tokens and i'm going to make this a decube okay so now that we have this q and it's all sorted we have our power and we want to store our score and i guess i can call this current think of that as current score and we'll have also the max score and we can start off with zero so while there's a q what do we want to do well if we have enough power and the power is greater or equal to the very first item on our q which is going to be the smallest we want to use it right so we want to pop that off from the left and we would have to subtract from our power whatever this t value of t is but we would increase our score by one and we would also store the max score in case we ever went lower here let's say max score was max score and max score now otherwise if we can't do this say that um we don't have enough power to pop off the smallest one we know that we want to try to gain some power right but we need to have a condition that score has to be greater than zero so that's something to keep note of and if it is then hey pop off that one on the very right and add this but we have to decrease our score here but we have to decrease our score here but we don't need to touch our max score but we don't need to touch our max score because that's going to be because that's going to be stored there now otherwise if we aren't stored there now otherwise if we aren't able to do any of this able to do any of this we actually just need to break this loop we actually just need to break this loop because say that because say that there's one left but we don't have there's one left but we don't have enough power for it enough power for it well we don't want to get into this well we don't want to get into this infinite loop right so we have to break infinite loop right so we have to break out somehow out somehow finally we just return that max score finally we just return that max score not the score but the max score not the score but the max score so let's go and submit that probably so let's go and submit that probably should have tested it at first but should have tested it at first but i was pretty confident that would work i was pretty confident that would work so there you go it's accepted so there you go it's accepted so there's variations of this you could so there's variations of this you could use two pointers you don't have to have use two pointers you don't have to have a queue like i did a queue like i did i just kind of felt like doing it and i just kind of felt like doing it and really yeah i think that's going to be really yeah i think that's going to be an o of n solution right yep definitely all then but we do use some extra space with our cue here so i suppose having the two pointers will be less space all right so i'm gonna end it there thanks for watching my channel and remember
2024-03-25 12:06:25
948
https://i.ytimg.com/vi/9…Kc/sddefault.jpg
Leetcode - Bag of Tokens (Python)
ah8fThyfjaI
Hi Everyone Welcome Back to a New Video Today Lead Code Daily Challenge Seat Reservation Today Lead Code Daily Challenge Seat Reservation Manager This is a medium level question so Manager This is a medium level question so in this question we will be assigned n seeds in this question we will be assigned n seeds and two seeds will be numbered starting from and two seeds will be numbered starting from one and it will one and it will continue till a Now we continue till a Now we continue till a Now we class in that class we will have two functions named as reserve and un reserved This seat manager will have an object in which we will be initial with an example what will be happening in this question here we happening in this question here we happening in this question here we provided with seat manager so a will be equal to 5 now we will be reserving the seat so we will have to start from one and it will go till five Starting from the Starting from the Starting from the minimum value so the first reserved seat will be minimum value so the first reserved seat will be numbered as numbered as one now we have reserved the number with one now we have reserved the number with one the other number again we have been assigned as one the other number again we have been assigned as reserved so after one has already been taken reserved so after one has already been taken so the other number which comes in the lowest so the other number which comes in the lowest value value value un reserve the sheet so for un reserved we will be taking of the two again and adding it to the data structure which ever data structure we are using and again we see that We have reserved so since in our data structure two is the lowest value again so we will be assigning the seat number as two again now we see that we have reserved so we will be adding three here now again we have reserved so it will be S for S for S for after that we see that reserve is used again so we will be adding after that we see that reserve is used again so we will be adding five here now for un five here now for un reserving this five will be added back to the reserving this five will be added back to the data data structure and here non null will be dead where ever we are un structure and here non null will be dead where ever we are un reserving null will be returned now reserving null will be returned now If we are using any data If we are using any data structure to store the values ​​from one to structure to store the values ​​from one to another that every time we reserve a another that every time we reserve a value we remove it from the data to solve the I will be sharing to structure Now in this question what we will be doing using array data structure we will be using the array with one so we will have an length array that will B inila is inila is with na now t will do when ever we are reserving the seat we will change the value from position so what I mean here is if we have given position so what I mean here is if we have given series of questions Inish ie with five then we're Inish ie with five then we're Inish ie with five then we're reserving if we have this series of measurements values ​​like this we're calling so now we have five seats so from one to n we're increasing the value by one so now we have Is as one Is as one Is as one right this is one index 2 3 4 and fa ok now what we are doing when we have been told that we have to reserve seat right so what we need to do is reserve seat right so what we need to do is this first for one we will be this first for one we will be turning this zero turning this zero ok now next again we see that we have reserved right so what we will be doing is we will move here and we will turn this to zero Now we have an array like this right so what we will be doing now is we are moving from one index What we will do So what is we will go back is we will go back by one step and we will turn this value to by one step and we will turn this value to one again so now we will have 0 1 1 1 and one again so now we will have 0 1 1 1 and one this will show that the second seat is one this will show that the second seat is unreserved complicated space complexity will be complicated space complexity will be Of n because here we are using n error to Of n because here we are using n error to store the store the values ​​which is the size of n Now let's see the other values ​​which is the size of n Now let's see the other approach storing the entire In the In the In the heap and every time we're reserving the seat we'll be popping the value out and when we're unreserving we'll be adding the value back adding the value back to the will Complicated The Space The Difference Between The Array And Heap Now One We Are Seat Then The Array Can Take Ss In Worst Case Seat Then The Array Can Take Ss In Worst Case Scenario Time Complexity Of O A Of A But Scenario Time Complexity Of O A Of A But In The Heap It Will Be Of Lg A Now Let's See The Code So Whatever Little Doubts We Have Will Be Cleared Let's See The Code Now We'll Be Using The First Approach Now To Solve The Question Were We're Using The Array Now We'll Inilla Is The Array Let's Was ina with Was ina with Was ina with one thing that all the seats are unreserved now and now we will one thing that all the seats are unreserved now and now we will be it be it on the array so for I in range alien of seat itself don't sit now we have started it in order to see that if Reserve and Reserve and Reserve and Unreserve at given position using one and Unreserve at given position using one and zero so if the value at the given position is zero so if the value at the given position is one that means seat is not reserved and we can reserve seat now so we one that means seat is not reserved and we can reserve seat now so we will check if seat dot if seat if self dot seat if self dot seat seat seat change that value to zero that means that seat is reserved now self dot seat at i is equals 0 and we will return from there and we will i is equals 0 and we will return from there and we will carry that index value so we have carry that index value so we have taken that index value taken that index value In order to un reserve the seat we will have to In order to un reserve the seat we will have to change back the value from 1 to 1 right change back the value from 1 to 1 right so what we will do is so what we will do is sell seat at seat at seat number minus not let's submit it we see That we're getting time accelerated now so let's try using heap and since it is a little optimized version so we may not face that problem again so we will import heap queue here so porting now we will ina list from And sell don't shut the list of in range not to a psw because here even if we are using a psw it will go till a only now and will prove the value [Music] Duff self don't seat now every time we are We'll be We'll be We'll be popping the value out so if sell dot see then return dot sell [music] dot and no we're reserving the value then dot we'll be adding the push self dot seat seat Value i not existing then will be returning your Value i not existing then will be returning your Value i not existing then will be returning your minus now let's run and see minus now let's run and see the code works and the code works and not let's try to submit it now the code has been accepted so that's it for today guys thank you for watching if you like the video please With your friends also With your friends also With your friends also subscribe to the
2024-03-25 10:24:51
1,845
https://i.ytimg.com/vi/a…axresdefault.jpg
1845. Seat Reservation Manager | Medium | Python | Live Coding | Easy Explanation | Array | Min-heap
hN30kTwEa5o
Loot ke guys welcome back to my channel in this video we are going to solve copy list with video we are going to solve copy list with random point so what is given random point so what is given statement year erring list of plant statement year erring list of plant and is given subsidize food content additional random and is given subsidize food content additional random point meaning which put point to point meaning which put point to android hindi list and tap android hindi list and tap android hindi list and tap copy of delete deep copy should consist of exactly a brand new not valid you must not have its value set to the value of its corresponding to include both within that and appointed of the new note suit point to new notes hindi copied list start Original list and copy Original list and copy Original list and copy list represent this cream list represent this cream in distant sources problem camp list of designer in distant sources problem camp list of designer pendant and here cricket what to do is to construct pendant and here cricket what to do is to construct a deep copy of the list to a deep copy of the list to vote whom to speak vote whom to speak a copy of any object in which you can a copy of any object in which you can change anything change anything change anything no change in it. Okay, and what is given here? A Next 9 Enter given a Turangam note point, which is the random note point of Ginger, it can assign any note to the Can also appoint. Okay, Can also appoint. Okay, Can also appoint. Okay, for example, you are seeing that the for example, you are seeing that the next point of the seven is guest, so their next point of the seven is guest, so their next point is next point is blind, what does it fold, do any note, the blind, what does it fold, do any note, the address night of this note, what to do dumb here, address night of this note, what to do dumb here, random, any note here. random, any note here. Okay, so Okay, so what to do in this problem is to create a cup play list, it will have what to do in this problem is to create a cup play list, it will have N notes, there will be SIM values, N notes, there will be SIM values, but whatever it is, it will not be my original, but whatever it is, it will not be my original, okay, it will have to be copied, so okay, it will have to be copied, so how to solve this problem? how to solve this problem? What will we do, here we will What will we do, here we will take an I, okay, what I do is that the take an I, okay, what I do is that the value is a tree, a value is a tree, a torch light, so what we will do is a worm, and we will add the torch light, so what we will do is a worm, and we will add the value of this note, and we will cut this note, value of this note, and we will cut this note, and what we will do in the value, we will note down the We will create a new note with the We will create a new note with the We will create a new note with the same value. Okay, here in the first note, same value. Okay, here in the first note, my eye is youth, so we will keep this note here my eye is youth, so we will keep this note here that I know that I know this is your original one and what we will this is your original one and what we will do is create a note with this time value. do is create a note with this time value. Note create. Note create. Note create. put it in its value, it should be complete, the copy one is fine, then we will add the additional original one to the team that I, then we will create another node of the space SIM value and put it in the value, okay, What will we do What will we do What will we do 1111 deposit note will be I and what will 1111 deposit note will be I and what will be the value same same value will cut a note of eleven you want from be the value same same value will cut a note of eleven you want from 10th will go 10th will go tan is here we will put the original here present here tan is here we will put the original here present here what will we do after that what will we do We will We will We will grate the chord note, we will keep the element here, grate the chord note, we will keep the element here, it will be the descendant of one it will be the descendant of one and its a chord same way, you can not and its a chord same way, you can not create it here, okay, create it here, okay, what will we do after cutting this, so I know what will we do after cutting this, so I know that all the next point advisor that all the next point advisor is connected with each other. is connected with each other. is connected with each other. not connected to each other, what should we do if we connect it, then it is good, it will be connected to the next point, from 3411 to 1110, 108 more points of the tank are being assigned to the seventh point at For is For is For is jointing the internal. Okay so we are jointing the internal. Okay so we are jointing the seven current point aviral. jointing the seven current point aviral. Know a is part of the team is doing the seventh and youth is doing whom who is doing the alarm's one and youth is doing whom who is doing the alarm's one is doing the Eleven is appointing Dr. Whom is One appointing? I am appointing you and Seven will be appointed. Okay, Given. Now what is the team doing in this, then point here. Okay, How to do this, see How to do this, see How to do this, see what we will do, before I you will what we will do, before I you will create create and and road map, ho na Jhala benefit, this award, type your word name nodal, what should we do and we will find the what should we do and we will find the current current city, we will sign that the boy is city, we will sign that the boy is satisfied. satisfied. satisfied. prepare a copy unilaterally tight here we will new note that here we will new note that one of its value is in ukraine its one of its value is in ukraine its personality or stomach and now personality or stomach and now miscurrent miscurrent that chicken became vicky is this current of its value that chicken became vicky is this current of its value I have created a copy of the SIM value, I will put I have created a copy of the SIM value, I will put it here, I have it here, I have put Night in the value, put Night in the value, then end it and remove it and remove the then end it and remove it and remove the paint. Next, paint. Next, okay, we have talked about it, we have done all this in the state map, okay, we have talked about it, we have done all this in the state map, after this we will again after this we will again after this we will again do, this will be signed viral what will we do after making it red, what will we do after making it red, now the current of my MP is serial, its value is the current now the current of my MP is serial, its value is the current of MP, the current of MP, the current found will be on the wiki, its value will be on this, it will be the seventh. found will be on the wiki, its value will be on this, it will be the seventh. Next week, this is Next week, this is what we have to put in Velvet Thirteen's Gelu, what we have to put in Velvet Thirteen's Gelu, this is what we have to put in 30min, this is the value of this, if we have to this is what we have to put in 30min, this is the value of this, if we have to put this, then what will we do, then the put this, then what will we do, then the additional next thing additional next thing is 11:00 in connect, so in this next, this is the level- is 11:00 in connect, so in this next, this is the level- fit one. fit one. fit one. note. Okay, so what will it do exactly? What will it do exactly? It will assign whatever value it has. So, how do we code here, here the value of friend is the value of next. What will be the value of the MP I connect to? Same thing for the random cant, what will be the value of the original one of this person's arm hole, value of the original one of this person's arm hole, what will be his next alarm, what will be his next alarm, according to according to Random aa ki Random aa ki kuch tu independent panel of kuch tu independent panel of his which London's closed it his which London's closed it became became that what will the national return do that the that what will the national return do that the head of MP this special what will happen to me head of MP this special what will happen to me here here yes yes this will happen and if this is this then the yes yes this will happen and if this is this then the value will be this 72 from here value will be this 72 from here value will be this 72 from here idea, money, here I am not in the mood, I also have to do it for the canter, I also have to do it, I submit joint worked for first test case to One Step Up thank you too
2024-03-21 12:20:49
138
https://i.ytimg.com/vi/h…axresdefault.jpg
Copy List with Random Pointer | Leetcode 138
PNv-3LkfMWo
Hello guys welcome to our interesting video in this series according to interesting video in this series according to this call to cities safe during this time and let's get this call to cities safe during this time and let's get started 21 A company started 21 A company planning to interview two and people give and planning to interview two and people give and request and school staff is equal request and school staff is equal to two vectors sized together for its to two vectors sized together for its elements representing the elements representing the elements representing the Flying Upstairs to Cities and the Cost of Flying You Centricity 20 Represented by the Second Element Inspector Aged Minimum Cost for Every Person Varsity Sweater Jacqueline and People Want to Right to Cities 100 Years of 21000 Don't Get and Distribute Decoration Half Minded Fan of them into cities pet so let's get Fan of them into cities pet so let's get Fan of them into cities pet so let's get started logic use code and will move to actress recording 800 they consider this case also in this case which have move to actress recording 800 they consider this case also in this case which have people who are willing to apply to cities people who are willing to apply to cities and cities pay that and cities pay that and cost flying officer to cities and and cost flying officer to cities and its its its Intercity 200 And Considering Us Control First Time 2830 Quite Different Cities Permits For Thought Processes Respectively And Further 14% 3128 That's A 200 What Will We Have To Which We Can Opt De Boy Der City Ye And City Because In This Will not be able to get the correct answer fennel examples and thought and by the cost of light in city vs concealer bed the worst position is absolutely minimum cost applicable to city wear look and only the cost of white city also in this person definitely go to City Ye Rights And Displaced Adapter Cost For Its Plus Thirty Plus One Plus 2 And It's Going To Give S For Thirty Plus 2450 Places For 750 Challan Services Minimum Cost For All Of Them Were Not Divided While Shopping Them To City Will Have To City Will Have To City Will Have To Consider Something College Relative Cost So Let Consider Something College Relative Cost So Let 's See What Rate Relative Cost Is Suggested 's See What Rate Relative Cost Is Suggested Relative Cost Means The Profit Will Get A Relative Cost Means The Profit Will Get A Young Person To City Ye Over City Also Okay So Let Young Person To City Ye Over City Also Okay So Let Me Write RCF And Relative Cost Me Write RCF And Relative Cost Relative Clock Of Flying On Cultural The Relative Clock Of Flying On Cultural The First person to city this over city after First person to city this over city after bus what is side profit and domni battery bus what is side profit and domni battery saving mode of flying intercity saving mode of flying intercity adversity bhi seedhi silai to 14% city we are going to spain adversity bhi seedhi silai to 14% city we are going to spain twenty rupees placid twenty rupees placid in the city have in its pancholi tent morning in the city have in its pancholi tent morning 127 0 flying intercity 127 0 flying intercity 127 0 flying intercity Soane This Is A Relative Ko 50% And Second Person Similarly Flying Intercity More Than 200 Ko 67 Miles - 80 Seven Se On Zee TV Third Person Relative Ko Se Pati - Forces - Difficult To Be Quite Different 4% 4% 4% Similar Twenty - 28 - 0 Sofia Ko * Similar Twenty - 28 - 0 Sofia Ko * Have to that Have to that a you know who spend 30th deficit and a you know who spend 30th deficit and sure different cities in this is relative Ko sure different cities in this is relative Ko Safed City University 20 - 10th so now they can solve this Safed City University 20 - 10th so now they can solve this relative cost each thing and this relative cost each thing and this relative relative relative Citizen Home to Light in City B.Com First for the Second Centricity Ye Divya Ko * Saver Mode of Money Vaikunth Se 117 10 Capsules Definitely Prime City Next Chapter 10 Verses Eliminated Vinod Now Maximum Amount of Money Can Save the Evening People is 22 language first person also to cities us gas limited to where is the god of war and remaining to guys vinod it will have to medium to cities pay member logic and can us for over to coding 800000 dam bay related to add to cart the Cost Sharif From Within That Ooo And And I Will Have To Use Ka Disrespect And Functions Let Me Scheduled For Them Using Relative To Swap To Declare 200 Relative Cost Swayam Gurudev Plastic Mistake And Relative Cost Function Medical Tell Me How To Short And Moods Sudesh Isko * Sudesh Isko * Sudesh Isko * Accept to vectors Sorry for example The Accept to vectors Sorry for example The first tractors Electronic and first tractors Electronic and First and Dum First and Dum now Contractor now Contractor is the platters Toilet Second semester print is the platters Toilet Second semester print and second show Vestige to vectors Positive and second show Vestige to vectors Positive Episode Number Relative cost Surya Stone Episode Number Relative cost Surya Stone Twitter To go for slow is the first Twitter To go for slow is the first tractors Related tractors Related tractors Related Secret Facts Related To Swiss Roll This To Sand Art 14% City This Varsity Blues In The Morning How To Give Him Friends Pet 127 More Money Than Him Okay Otherwise Will Have To Send To The Second Half Inch Width Most And Will Have To Go For And Will Have To Go For And Will Have To Go For R And What We Can Give What The R And What We Can Give What The Sorted Factor Know This Entry For The Sorted Factor Know This Entry For The Director Know What We Can Do It Is Director Know What We Can Do It Is Winters Hydrate Over The Course Business Difference Between Winters Hydrate Over The Course Business Difference Between Subscribe To Get Subscribe To Get Started Properly In Illegal Lottery Started Properly In Illegal Lottery Don't Know You Can Just Don't Know You Can Just Happened Happened 108 Increase Twitter And Protest Edifice Point 108 Increase Twitter And Protest Edifice Point Is Equal To Zero Start Size Is Equal To Zero Start Size Back To IA Kepler Difficult Elements Back To IA Kepler Difficult Elements Inventor Of Cost David To Sum Up And Have To Go Inventor Of Cost David To Sum Up And Have To Go To Cities Pain Just The First Element To Cities Pain Just The First Element From The Best All The Meaning Of Elements From The Best All The Meaning Of Elements Vinod now to two cities pain just give the Vinod now to two cities pain just give the point is equal to cost of science point is equal to cost of science by two is equal to cash digest plus plus all the by two is equal to cash digest plus plus all the meaning of element have to go to meaning of element have to go to city chief and own this tweet but not let someone will city chief and own this tweet but not let someone will declare time will 720 adventures declare time will 720 adventures Return Dasham 388 Swapt Under Total Sampitt Sud Return Dasham 388 Swapt Under Total Sampitt Sud User Protest Fully Shuv Work Pic User Protest Fully Shuv Work Pic Ek Ansh Working For The First Test Case Ek Ansh Working For The First Test Case Will Submit It Is Working For All The Will Submit It Is Working For All The Testis This Swelling Accept Solution Testis This Swelling Accept Solution Thank You For Listening And Information Like You Like The Thank You For Listening And Information Like You Like The Video Please Like And Subscribe To Video Please Like And Subscribe To my channel thank you
2024-03-25 15:18:00
1,029
https://i.ytimg.com/vi/P…axresdefault.jpg
Two city Scheduling Solution | Leetcode #1029 | C++ | Code + Explanation
UQRbJz7ahZQ
hey hey everybody this is Larry this is day 25th day 25th of the weekly of the weekly what month is this September daily what month is this September daily challenge uh hit the like button hit the challenge uh hit the like button hit the Subscribe button drop me on Discord let Subscribe button drop me on Discord let me know what you think about today's me know what you think about today's farm so I just finished oh excuse me I farm so I just finished oh excuse me I just finished a 48 hour fast just a just finished a 48 hour fast just a quick one uh and during that I just quick one uh and during that I just spent like three hours in the gym and spent like three hours in the gym and like another like another I don't know 20 minutes running or I don't know 20 minutes running or something so I'm very tired uh I get something so I'm very tired uh I get that a lot or I'm just like very I don't that a lot or I'm just like very I don't know ready to take a nap anyway so okay know ready to take a nap anyway so okay so let's take a look at today's Farm so let's take a look at today's Farm we'll see how that goes uh today's five we'll see how that goes uh today's five is 389 find the difference is 389 find the difference we're given two string SNT T is we're given two string SNT T is generated by randomly permutating and we generated by randomly permutating and we turn the letter that is added to T turn the letter that is added to T uh okay that's a I mean that seems uh okay that's a I mean that seems pretty straightforward um hmm hmm okay I'm trying to figure out if I could okay I'm trying to figure out if I could go off it to me to be honest uh let's go off it to me to be honest uh let's see right so maybe I could do something see right so maybe I could do something like calendar of s but um minus corrections.counter of T I think this gives us kind of the answer but not not really in the uh in the sufficient way I'm just going to see how that returns right uh oh the other way whoops T has more than S um I'm wondering if I can do but I don't um I'm wondering if I can do but I don't think you could do better than linear think you could do better than linear yeah because you have to kind of look at yeah because you have to kind of look at everything anyway so I think this everything anyway so I think this should be good right so then we could should be good right so then we could just return this just return this uh uh something like that maybe it'd be kind something like that maybe it'd be kind of of you know constrained with the thing that you know constrained with the thing that this is one uh dictionary oh hmm I this is one uh dictionary oh hmm I didn't know that nope I mean yes but also another thing nope I mean yes but also another thing uh uh [Music] the kiss is not an elevator what is it then it's not elevator I cannot index it what are you doing all right fine uh yeah let's give it a quick submit and there you go 1273 day streak uh pretty pretty straightforward this one um I mean obviously you could have also done in any any other way I was just trying to see play around with a little bit uh this is just returning the hashtag uh the difference in lookup table is this one as well uh and uh this oh I guess last time I actually just did it the same way but and this time I just did in one lie all right uh yeah this is gonna be linear time linear uh well actually space is Alpha space Alpha being uh the size of the alphabet which is 26 because that's the size of the calendar but linear time you can really avoid it I don't think because you can always just and there's no structure if they were sorted then maybe you could do a binary search or something like this um but yeah uh yeah am I is this blocking I just realized that this may I mean it's not but it is ready to close to the top of the screen maybe I gotta be more mindful about this but uh hopefully this is I don't know I hope you enjoy me doing this forum review how about you're not too alone uh you'll never be alone when you know I'll keep doing it I have a 12 73 Day Street going down and fight and one day but not today so yeah uh that's what I have for this one let me know what you think have a great week everybody stay good stay healthy to get mental health I'll see
2024-03-24 12:05:27
389
https://i.ytimg.com/vi/U…axresdefault.jpg
389. Find the Difference - Day 25/30 Leetcode September Challenge
vioZzYV2MXY
hey everyone welcome back to our late code study plan code study plan let's tackle next problem 374 guess let's tackle next problem 374 guess number higher or lower consider we have number higher or lower consider we have two players player one and player two two players player one and player two player two hides a number called pick player two hides a number called pick and we need to guess as a player one in and we need to guess as a player one in certain number of attempts what the pick certain number of attempts what the pick is is in this example n is equal to 10 meaning in this example n is equal to 10 meaning from 1 to 10 this player 1 can kiss a from 1 to 10 this player 1 can kiss a certain number and as soon as this certain number and as soon as this player cases 6 that would be the right player cases 6 that would be the right answer so let's take a look how that answer so let's take a look how that works this player 1 will guess from 1 to works this player 1 will guess from 1 to 10. 10. so in this example let's say n is equal so in this example let's say n is equal to 10 and we can do this problem to 10 and we can do this problem linearly meaning we can keep guessing linearly meaning we can keep guessing from 1 to 10 in a linear fashion like 1 from 1 to 10 in a linear fashion like 1 2 three until we get the pick so at some 2 three until we get the pick so at some point we get this pick in this case in point we get this pick in this case in seventh attempt we get the pick but we seventh attempt we get the pick but we know that if the elements are sorted know that if the elements are sorted then binary search would be the best bit then binary search would be the best bit so let's see how that works here instead so let's see how that works here instead of guessing some number randomly let's of guessing some number randomly let's take a low point of 1 because the take a low point of 1 because the problem says i pick a number from 1 to n problem says i pick a number from 1 to n low would be 1 and high would be 10 in low would be 1 and high would be 10 in that case and high would be n which is that case and high would be n which is 10. so what's the way to guess we need 10. so what's the way to guess we need to ask player 2 if whether the number i to ask player 2 if whether the number i guessed is right by calling guess guessed is right by calling guess of some number of some number and now this player 2 will respond with and now this player 2 will respond with either of one if the number we chose either of one if the number we chose is higher than the pick then he says is higher than the pick then he says it's minus one on the other hand if we it's minus one on the other hand if we pick a lower number then the pick then pick a lower number then the pick then he says it's one and if we guess it he says it's one and if we guess it right he would respond with a zero so right he would respond with a zero so that's the idea so instead of tackling that's the idea so instead of tackling this problem linearly let's look at the this problem linearly let's look at the binary search we guess binary search we guess a midpoint low plus high by 2 a midpoint low plus high by 2 and that would provide 1 plus 10 by 2 and that would provide 1 plus 10 by 2 which is 5 if we take the floor value so which is 5 if we take the floor value so we guess the 5 and the way we guess is we guess the 5 and the way we guess is by calling guess of five so i'm asking by calling guess of five so i'm asking is phi the number to player two and now is phi the number to player two and now player two will compare seven with five player two will compare seven with five so he sees five is less than seven so he so he sees five is less than seven so he would respond with one saying the pick would respond with one saying the pick is greater than the number we chose so is greater than the number we chose so we get to know that 5 is less than the we get to know that 5 is less than the click so we need to update our low click so we need to update our low pointer to eliminate the numbers less pointer to eliminate the numbers less than 5 so since we know 1 through 5 than 5 so since we know 1 through 5 there is no number which matches pick so there is no number which matches pick so we can make our low pointer point to the we can make our low pointer point to the sixth number so let's do that so first sixth number so let's do that so first time the mid was here we guessed five time the mid was here we guessed five and we got a response of one saying the and we got a response of one saying the peak is higher so we'll update low peak is higher so we'll update low pointer to 6 and now we calculate the pointer to 6 and now we calculate the mid again mid again 6 plus 10 6 plus 10 by 2 which is 8 and that cross the pick by 2 which is 8 and that cross the pick so let's guess that first so let's guess that first and he would respond with a minus 1 and he would respond with a minus 1 saying your guess is higher than the saying your guess is higher than the number so in that case we reduce the number so in that case we reduce the high pointer to point to the element high pointer to point to the element less than the mid so we point to one less than the mid so we point to one less than the mid the high becomes seven less than the mid the high becomes seven this was ten initially now we calculate this was ten initially now we calculate the mid six plus seven the mid six plus seven by 2 which would be 6 so we'll bring our by 2 which would be 6 so we'll bring our mid here now we get 6 mid here now we get 6 and player 2 responds with the 1 saying and player 2 responds with the 1 saying your guess is lower than the number your guess is lower than the number because peak is 7 and we guessed it 6. because peak is 7 and we guessed it 6. so in that case we update so in that case we update the low pointer to point to the next the low pointer to point to the next element like this and now both high and element like this and now both high and low are equal and we recalculate the mid low are equal and we recalculate the mid now that would be now that would be 7 plus 7 by 2 which is 7 so mid comes to 7 plus 7 by 2 which is 7 so mid comes to 7 as well now we guess 7 and this 7 is equal to the pick so he responds with 0 and that would be our number so we return the mint in this case 7 that's the strategy of the game and when do we exit a while loop we exit a while loop if high cross is low as usual so we can update our low and high pointers until low is less than or equal to high if high crosses low then it means the number doesn't exist but in this case that doesn't happen because he hides some number and by updating low and high properly we at some point reach to that proper pick so let's code this out i take a low pointer pointing to 1 and high is equal to n so until then i need to update my pointers then low less than or equal to high i can keep finding the mid and update my pointers once low and high crosses each other i stop there so mid is equal to floor value of low plus high by two now calling the api we get back one of the three responses so if guess of mid is equal to one we update our low pointer pointing to the element next to it else if case of mid is equal to minus one then the number we chose is very much high than the pick so we reduce the high pointer to mid minus 1 else finally we found the number and guess of mid will be equal to 0 so we just write else here we return the midpoint meaning we found the mid element we guessed the pick at this point and we closed the loop and we don't need any condition outside because within this the peak will be available and at some point we reach this condition and we guess the number right let's code this all the code okay so we are back on lead code let's take low is equal to 1 and high is equal to n while low less than or equal to high we find the mid math dot floor high plus low by 2 and if is equal to 1 is equal to 1 we update our low we update our low to mid plus 1 guess to mid plus 1 guess of mid is equal to minus 1 of mid is equal to minus 1 then we update the high pointer to mid then we update the high pointer to mid minus one and doing this if and else if minus one and doing this if and else if condition we narrow down and find the condition we narrow down and find the pick so at that point we return the mid pick so at that point we return the mid and that would be our let's run the code and that would be our let's run the code let's accept it we'll try submitting it let's accept it we'll try submitting it and it got submitted so this was the and it got submitted so this was the hi-lo guest game see you in the next hi-lo guest game see you in the next video thanks for watching
2024-03-24 11:40:19
374
https://i.ytimg.com/vi/v…axresdefault.jpg
5. Guess Number Higher or Lower - Leetcode 374 Javascript solution
k3kexth1C-k
[Music] foreign level question and it's a very popular question as you can see from the likes so let's read the problem statement a try pronoun just try or a prefix tree is a tree data structure used to efficiently store and retrieve keys in a data set of strings so there are various applications of this data structure such as autocomplete and spell checker so we have to implement a try class with a constructed try with a methods insert that takes the word and inserts the word into the try there is a search method that takes the string as word and returns true if the string word is in the try or IE was method is starts with it takes the method is starts with it takes the string as prefix and returns true if string as prefix and returns true if there is a previously inserted string there is a previously inserted string word that has the prefix prefix or and word that has the prefix prefix or and false otherwise false otherwise let's see some let's see some properties of the try so properties of the try so try as stated is a rooted tree try as stated is a rooted tree and with each node of the tree has two and with each node of the tree has two properties first each node has properties first each node has R links you can say right as R links where R is equal to 26 which represent which corresponds to the 26th character of the string data set or the string alphabets and also ah there is a is end Boolean variable associated with the node that represents whether this node represents the end of the key or not right so there are some operations that we can see first the two main operations is insert insert and search prefix the three main operations and these three main operations are also need some auxiliary uh operations that is put so put so put is to create a link is to create a link is to create a link is to create a link uh between the parent and the child node uh between the parent and the child node get is to get the link between the child get is to get the link between the child and the parent node for a particular and the parent node for a particular character and contains key character and contains key that Returns the Boolean whether there that Returns the Boolean whether there is a link for a particular alphabet or is a link for a particular alphabet or not right so let's see if I do put CH in the it will add a link it will add a link for a particular character for a particular character suppose a suppose a it it will add the link for a particular it it will add the link for a particular character and it will link character and it will link that node with the parent that node with the parent for that corresponding link for that corresponding link right and get CH will return the link or right and get CH will return the link or the node try node for that particular the node try node for that particular character and contains key character and contains key will return will return will check whether there is a will check whether there is a try node present for that character or try node present for that character or not see the first operation that is not see the first operation that is insert so let's insert two words that is insert so let's insert two words that is lead and code lead and code so we'll start so these are our two keys so we'll start so these are our two keys so we'll go character by character so so we'll go character by character so first we'll start with the root note so first we'll start with the root note so root node has 26 links right root node has 26 links right corresponding to each character so corresponding to each character so at the start there is no node for the No at the start there is no node for the No Child node for the character l Child node for the character l right so we will add a link for the right so we will add a link for the character L and we'll add a child node character L and we'll add a child node to the parent node to the parent node then again we'll check the letter e so then again we'll check the letter e so for this from this child node there is for this from this child node there is no link present for the character e so no link present for the character e so we'll add a link e and we'll add a child we'll add a link e and we'll add a child node from this node node from this node again we will add then for the again we will add then for the corresponding or for the next letter e corresponding or for the next letter e We'll add a child node and again for the We'll add a child node and again for the next letter T we'll add a child node and next letter T we'll add a child node and we will mark this child node or the leaf we will mark this child node or the leaf node as is end equal to true so this node as is end equal to true so this represents that this is the last represents that this is the last character of the key lead right this is character of the key lead right this is the last character of the key lead right the last character of the key lead right now we will add code so starting with now we will add code so starting with the nodes root node there is no link the nodes root node there is no link present for the present for the character C so we'll add a new child character C so we'll add a new child node and we'll link it with the parent node and we'll link it with the parent for the character C for the character C right now again from the C there is no right now again from the C there is no link for the character o so we will add link for the character o so we will add a new node and we'll link it to the a new node and we'll link it to the parents link matching the character o parents link matching the character o right again we'll add a newly node that right again we'll add a newly node that matches the parents link corresponding matches the parents link corresponding to character D and from the D as there to character D and from the D as there is no link present for the character e is no link present for the character e so we'll add a node so we'll add a node and we'll add the link corresponding the and we'll add the link corresponding the parents link matching character e right parents link matching character e right and we'll mark this node as is and equal and we'll mark this node as is and equal to true that represent this is the last to true that represent this is the last character of the key code in this try character of the key code in this try data sector we'll search now the word data sector we'll search now the word lead so we'll check from the starting lead so we'll check from the starting from the root node is there in any link from the root node is there in any link corresponding to the letter L yes there corresponding to the letter L yes there is a letter so we'll move down to the is a letter so we'll move down to the child node or the next node and then child node or the next node and then we'll search a link for the character e we'll search a link for the character e so there is a link for the character e so there is a link for the character e so we'll move down to the next node then so we'll move down to the next node then again in the at the next node we'll again in the at the next node we'll search the link for the character e so search the link for the character e so there is a node for the character e there is a node for the character e right so we'll move down to the next right so we'll move down to the next node we'll search for the character T node we'll search for the character T the is there any link yes there is a the is there any link yes there is a link for the directory so we'll move link for the directory so we'll move down to the next node now we are we have down to the next node now we are we have done we have out of the keys right so done we have out of the keys right so we'll check whether this node is end is we'll check whether this node is end is equal equal to true so yes is that equal equal equal to true so yes is that equal equal to true so this whole word is equal to true so this whole word is present in the try present in the try right so it will it's present in the uh right so it will it's present in the uh try data structure right so we'll try data structure right so we'll iterate and we have to check is end iterate and we have to check is end equal equal to 2 right both now we will equal equal to 2 right both now we will check for the prefix check for the prefix right right whether so now let's suppose we uh c l e whether so now let's suppose we uh c l e whether Le is whether Le is present right we'll search Le not search present right we'll search Le not search prefix but we'll search Ali whether le prefix but we'll search Ali whether le as a word is present in this data as a word is present in this data structure or not so we'll start from the structure or not so we'll start from the root node we'll see the link root node we'll see the link corresponding we'll check the link corresponding we'll check the link corresponding to the letter L so yes corresponding to the letter L so yes there is a link present from the node so there is a link present from the node so we'll move down to the next node we'll we'll move down to the next node we'll search for E yes the from this node we search for E yes the from this node we have a link present for uh corresponding have a link present for uh corresponding to character e so we'll move down to the to character e so we'll move down to the next node but at this node next node but at this node at this node because we are out of the at this node because we are out of the characters so but at this node is end is characters so but at this node is end is end is equal equal to false so this end is equal equal to false so this means that l e is not present as a word means that l e is not present as a word but if we want to search le as a prefix but if we want to search le as a prefix right so if we perform right so if we perform search search prefix prefix Le Le then it will be then it will be returned true because at this node we will not check is and equal equal to true right so because for this at this node is end is equal to equal to false then it means that LE is a prefix for a word already stored in the data structure that is lead right so if we want if we do Search Le then it will return false but if we do search prefix Le then it will return true depending upon this is end flag so because is end is false at this node so it means this is not a word stored in the data structure but it is a prefix let's see the Java code for it so we have created a public class try which has a inner class that is try node so each node this represents the node of the tree which with each node as R links and a Boolean variable is n that represents that this is the last character of the key and we have uh initialized links with the r sized try node array now three main auxiliary functions that is contains key which tells us that there is a link for a corresponding character ch in that node or not get method that Returns the link for that particular character CH and put that adds a link for that character CH into the node into the parent node set ends marks this marks the node as a end character for a key and is end gives us the Boolean value of whether that node is the end character of the key or not so in the Constructor we will initialized our Tri node try node and in the insert method we'll start from the root node we'll iterate each character of the word we'll check we'll first fetch the character into the curve car variable and we'll check whether there is a link present for that current character in that in the root node or not or in the current node or not if that is not present we'll add a node corresponding to that character will add a link corresponding to that character in the node and or we'll get the node that we added for that current character and will do will perform this operation till we are done with the each character of the word and finally we'll mark the last node as the end for the search search and starts with will call this one main uh same function that is search prefix so what search prefix does is we'll start with from the root and we'll again iterate each character of the word we'll take each character of the word and we'll check whether the node contains a link for that character if yes will move down from that node to the child node right so we'll else will return null and if we have iterated over the complete word length we'll return the last node so in the search method we'll perform the search prefix and we'll get the last node so either it node can be null or not null so if the node is not null so it means the complete word is already inserted before in the try and if node is end is true right so for search the for search the complete word has to be inserted the complete word has to be present so that is specified by the is end variable is end Boolean variable so if the node is not equal to null and the node dot is end is equal to true it means that the complete word that the complete word is present in the try now for the starts with it means that we have to only search for the prefix so when we perform search prefix and we get the node the we only checked node not equal to null we don't check node is end because it it doesn't matter whether it's the is end for that node is true or false because we only want to search as a prefix now let's run the solution so yeah test cases are accepted so means if the solution is working fine so let's see the time complexity of largely two main function that is insert for the insert we are creating the nodes which is equal to the length of the key right the length of the word so the time complexity will be go of n where n is the length of the word is the length of the word that we want to insert right and for the space complexity for the space complexity as we are maintaining uh we are creating m n nodes where n is the length of the word so the space complexity of B will be Big O of n and for the search prefix right the first prefix again the time complexity will be Big O of n because we are searching nodes where n is the length of the word so we are so we have to iterate n times so n nodes right so search for the complete word and the space complexity will be uh order for the big of one because there is no node we are creating so that's why it will be big offer so I hope you like this video If you like this video please share and
2024-03-22 10:06:55
208
https://i.ytimg.com/vi/k…axresdefault.jpg
Leetcode 208 | Implement Trie | Prefix Tree | Trie
NcSKlLGLRdE
hey hello there uh let's talk about this liquidity challenge question liquidity challenge question find minimum in a rotated sorted array find minimum in a rotated sorted array too too suppose that we have an array that's suppose that we have an array that's sorted in the ascending order sorted in the ascending order and now this array has been rotated and now this array has been rotated around some pivot point around some pivot point that's unknown to us uh looking at the that's unknown to us uh looking at the concrete concrete example array this is the original array example array this is the original array that's sorted in the ascending order that's sorted in the ascending order zero one two four five six seven this zero one two four five six seven this array has been pivoted uh array has been pivoted uh i rotated around this pivot point the i rotated around this pivot point the position in between two and four so position in between two and four so we're cutting the array into two halves we're cutting the array into two halves the first half is zero one two and move the first half is zero one two and move that part with and that part with and so the rotated solder already become so the rotated solder already become four five six seven four five six seven zero one two so in terms of the ordering zero one two so in terms of the ordering of the elements inside this rotated of the elements inside this rotated sorted array is ascending a sudden job sorted array is ascending a sudden job and then and then going back to ascending order as well going back to ascending order as well again again now the question asks us to find the now the question asks us to find the minimum elements inside this array minimum elements inside this array and one notice that there are and one notice that there are may potentially be duplicates inside may potentially be duplicates inside this array this is the only thing that this array this is the only thing that set this question apart from the prior set this question apart from the prior question five minimum in a rotating question five minimum in a rotating distorted array distorted array so in that question uh there is no so in that question uh there is no duplicate that the case is duplicate that the case is relatively simpler relatively simpler so let's talk about how we find minimum so let's talk about how we find minimum element inside any element inside any any kind of array let's not assume any any kind of array let's not assume any kind of assorted order about the array kind of assorted order about the array and we want to find the minimum elements and we want to find the minimum elements we have to look at we have to look at all the element at least of once and all the element at least of once and remember remember what is the smallest one that we see so what is the smallest one that we see so it's going to be a linear it's going to be a linear time algorithm just pass through all the time algorithm just pass through all the elements inside a elements inside a array where we don't assume any kind of array where we don't assume any kind of a sorted order a sorted order so that's linear time if the array is so that's linear time if the array is perfectly sorted perfectly sorted in this case this is the original array in this case this is the original array then the minimum number then the minimum number is going to be the first element inside is going to be the first element inside this array so it's going to just be a this array so it's going to just be a constant time constant time looking up looking after the value now looking up looking after the value now this array is this array is rotated sorted so it's not fully sorted rotated sorted so it's not fully sorted but it's but it's not totally unordered so this is in not totally unordered so this is in between between unsorted and sorted so the uh unsorted and sorted so the uh algorithm that we are looking at should algorithm that we are looking at should be have a runtime that's in between be have a runtime that's in between constant time and linear time so that's constant time and linear time so that's leave us to a logarithmic time leave us to a logarithmic time so find a value inside array in so find a value inside array in logarithmic time logarithmic time it's a pretty clear we're looking at it's a pretty clear we're looking at binary search binary search so the big idea behind binary search is so the big idea behind binary search is that we're looking at the three numbers that we're looking at the three numbers the lower bond the upper bond and some the lower bond the upper bond and some middle middle median pivot number and based on those median pivot number and based on those three pieces of information three pieces of information we want to decide which half of the we want to decide which half of the problem problem we can safely disregard and zoom into we can safely disregard and zoom into the other half of the problem to find the other half of the problem to find the answer the answer so here we're looking at how we compare so here we're looking at how we compare the arrays number the arrays number elements indicated by those three pivots elements indicated by those three pivots lower bound upper bound and medium lower bound upper bound and medium points to figure out points to figure out where should the minimum number reside where should the minimum number reside and and use that to iteratively or recursively use that to iteratively or recursively whatever whatever repeatedly reduce the size of problem repeatedly reduce the size of problem until we find the minimum until we find the minimum so that we can leads to logarithmic time so that we can leads to logarithmic time so let's look at the let's just look at so let's look at the let's just look at this one by one this one by one the first case is that let's just talk the first case is that let's just talk about this graph a little bit about this graph a little bit now assuming that we have an array and now assuming that we have an array and using the x-axis to indicating the using the x-axis to indicating the arrays index and the y-axis to indicate arrays index and the y-axis to indicate the element's value the element's value so because this rotator sorted it's so because this rotator sorted it's increasing increasing a certain job and then going back to a certain job and then going back to increasing again increasing again note that the upper bond should never be note that the upper bond should never be higher than the higher than the uh lifter point because if this is uh lifter point because if this is higher than the left point higher than the left point it's not really a cut off and move over it's not really a cut off and move over that will violate the prior property of that will violate the prior property of a sorted array so it has to be in this a sorted array so it has to be in this kind of shape kind of shape now the first case is that when we use now the first case is that when we use the three number the three number to partition the array basically rotate to partition the array basically rotate the sorted the sorted into two halves by uh the lower bound into two halves by uh the lower bound upper bond and the medium upper bond and the medium pivot position in if it's the first the pivot position in if it's the first the case here we can see that case here we can see that the left part the part the part that's the left part the part the part that's between between this two line here it's a strictly this two line here it's a strictly sorted in the ascending order sorted in the ascending order and there's no way that the minimum is and there's no way that the minimum is in this part in this part because the job the minimum number is because the job the minimum number is always the starting point always the starting point after this job here so just based on the after this job here so just based on the the relatively relationship between the relatively relationship between this three number or this two number in this three number or this two number in particular particular we can identify that we want to we can identify that we want to resume continue looking into this resume continue looking into this portion this is half of the portion this is half of the routine sorted rate to find this minimum routine sorted rate to find this minimum so just in summary so just in summary if we find the median value is larger if we find the median value is larger than the upper bound than the upper bound positions value that means the right positions value that means the right hand side partition of the rotative hand side partition of the rotative solid array contains the minimum solid array contains the minimum and we want to basically and we want to basically only considering that part so we can only considering that part so we can update this by moving the median value update this by moving the median value to be to be actually one larger than the median actually one larger than the median because to have this sorry because to have this sorry they are rotated to have this medium they are rotated to have this medium value to be strictly larger than value to be strictly larger than the upper bound position value that the upper bound position value that means the job hasn't happened yet means the job hasn't happened yet so we can safely move it to be one more so we can safely move it to be one more than that than that so so this is the update rule for the so so this is the update rule for the first case in the binary search first case in the binary search okay let's go back to that that so this is the second case when we have so this is the second case when we have this kind of partition with this three this kind of partition with this three number partition lower lower bound upper number partition lower lower bound upper bound and medium bound and medium part we can see that the left hand side part we can see that the left hand side is a rotated sortedness is a rotated sortedness array that's why the median and the array that's why the median and the minimum number has to be in that part so minimum number has to be in that part so we can just safely disregard we can just safely disregard the upper bound part um the upper bound part um so this condition this this kind of so this condition this this kind of partition is indicated by that partition is indicated by that the median value median position value the median value median position value is is smaller strictly smaller than the upper smaller strictly smaller than the upper bound value bound value but that doesn't exclude the case where but that doesn't exclude the case where this median value is pointing at this median value is pointing at the true minimum so that we don't want the true minimum so that we don't want to overshoot so the to overshoot so the update rule for the upper bound in this update rule for the upper bound in this particular case particular case we just set it to be me medium position we just set it to be me medium position because because that one has the potential to be the that one has the potential to be the true true true minimum so that's the second case true minimum so that's the second case the very last case sorry the very last case sorry the rare last case is the the rare last case is the [Music] [Music] is the tie that will never happen if is the tie that will never happen if there is no duplicates there is no duplicates if we find that the median value if we find that the median value median position value and the upper median position value and the upper bound position value has the same value bound position value has the same value that's only possible when there are that's only possible when there are duplicates and actually there are two case possible scenarios one is that the duplicates extending from some prior part in the left-hand side and just lift the left the left portion between low and median if if that go extending through that then the we want to really zoom into this part the other case is the same value is extending through median towards upper bond then uh the the part that we would want to zoom in is this left-hand side part so just based on this two uh values relationship there's no way that we can determine which part of the array we want to disregard so the only thing we can safely do is to just decrease the upper bound by one so that moves the also move the medium value towards left by a little bit and hopefully after a few updates we can as in this case we can see that it's already in the dropping part so doing a few updates we can resume this cutting half and cutting half operation like here if we drop it here then we're pretty sure that the right hand side is the part we want to keep and we can resume the binary search so yeah so just in short when there is the tie we can no longer do binary search all we can do is to do a linear update of the upper bond by decreasing that by one so that's the three cases um yeah so let's go back to the code editor and the code up the solution it's relatively simple once we can have those three scenarios in our mind the code is pretty simple so the lower bond and upper bond are the first position and the last position in the array and the termination criteria is that the two bonds haven't converged into one point so we haven't successfully identified the single minimum number inside this array we want to repeatedly finding the minimum a median position which is just this two add together and divide by two and now is the three cases we want to test whether this position is less than or what's what's my first case it's larger if it's larger than the upper bond then if it's larger than the upper bond then what i would do is to reduce to increase what i would do is to reduce to increase the lower bond to be the lower bond to be m plus one the other case is that m plus one the other case is that it's strictly less than the upper bound it's strictly less than the upper bound positions value positions value that means the median position have a that means the median position have a potential to be potential to be the true minimum if it's not then the the true minimum if it's not then the left partition of the array has to be left partition of the array has to be rotated sorted rotated sorted so we want to keep searching that part the only last case is that it's a tie if it's a tie then we are not sure which part we can safely cut off so we just reduce the upper bound by uh by by one in the end the two bonds low upon the upper bond will be the same value so we can either return the number at high or low they are the same position so that's the code for this problem and uh so the in the worst case when the array is just a sam number repeating itself over and over and over and over again this will converge after we decrease h from the last number towards zero so that's the only case when this will break so in that case the time complexity will be linear time because we from the right hand side and move that one at a time to be the left side so linear linear so when uh so when uh when there is no duplicate and uh order of end [Music] every every elements uh when we just have so that's the time complexity for this so that's the time complexity for this problem problem and because it's binary search all we and because it's binary search all we have is the have is the three positions so it's a constant space three positions so it's a constant space problem problem uh for the prior question um because uh for the prior question um because it's just a half it's just a half it's basically just getting rid of this it's basically just getting rid of this case so the case so the code is just just that so we have two code is just just that so we have two positions positions two uh two branches inside this code two uh two branches inside this code binary search code binary search code uh for this uh 153 uh for this uh 153 in the rotated sorted array in the case in the rotated sorted array in the case there's no duplicate it's guaranteed to there's no duplicate it's guaranteed to be in be in log log time yeah log log time yeah all right so that's uh that's this all right so that's uh that's this question and it's a prior question today question and it's a prior question today binary search
2024-03-21 13:17:35
153
https://i.ytimg.com/vi/N…axresdefault.jpg
Leetcode 153/154 Find Minimum in Rotated Sorted Array I/II
N5MUtk_NRIw
hey what's up guys babybear4812 coming at you one more time at you one more time today we're doing another cool problem today we're doing another cool problem well i think it's cool uh i think most well i think it's cool uh i think most of them are cool not all of them but of them are cool not all of them but most of them uh problem 430 flatten a most of them uh problem 430 flatten a multi-level multi-level doubly linked list so in this problem doubly linked list so in this problem we're given a doubly linked list we're given a doubly linked list which says in addition to the the which says in addition to the the typical next and previous pointers typical next and previous pointers it could also have a child pointer which it could also have a child pointer which may or may not may or may not point to a separate doubly linked list point to a separate doubly linked list says these child lists says these child lists may have one or more children of their may have one or more children of their own own excuse me and so on to produce a excuse me and so on to produce a multi-level data structure multi-level data structure and we need to flatten it so what does and we need to flatten it so what does that look like in an example that look like in an example uh imagine this is a standard linked uh imagine this is a standard linked list kind of from from one to six list kind of from from one to six but once we get to node three we kind of but once we get to node three we kind of hop along hop along we notice that it has a child node and we notice that it has a child node and in that pointer in that pointer excuse me the child pointer the child excuse me the child pointer the child pointer points to another node which is pointer points to another node which is node seven this one down here and that node seven this one down here and that one's got a linked list in and of itself one's got a linked list in and of itself and then we've got eight so sorry if you and then we've got eight so sorry if you kind of traverse kind of traverse through through that when you get to through through that when you get to eight you notice that one has a child eight you notice that one has a child with notes 11 and 12 which are their own with notes 11 and 12 which are their own linked list linked list after flattening this thing although you after flattening this thing although you can't really see it we get this can't really see it we get this order one two three seven eight eleven order one two three seven eight eleven twelve nine ten twelve nine ten four five six so what do these numbers four five six so what do these numbers mean to us well imagine doing this mean to us well imagine doing this imagine taking uh so the order becomes imagine taking uh so the order becomes one two three one two three and then we jump down and it goes 7 8 11 and then we jump down and it goes 7 8 11 12. 12. and then imagine this this kind of this and then imagine this this kind of this 11 12 over here is now 11 12 over here is now so we go 7 8 11 12 and now on to the end so we go 7 8 11 12 and now on to the end of the 12 we put on this 9 and this 10. of the 12 we put on this 9 and this 10. so we'd have 1 2 3 7 8 11 12 so we'd have 1 2 3 7 8 11 12 then the 9 and the 10 go here so we have then the 9 and the 10 go here so we have one two three seven eight eleven twelve one two three seven eight eleven twelve nine nine ten and now this all kind of propagates ten and now this all kind of propagates upwards and so this four which got cut upwards and so this four which got cut off originally off originally goes out at the end of the the ten so we goes out at the end of the the ten so we get four five six get four five six um so we go from from this pattern we um so we go from from this pattern we kind of go kind of go one two three seven eight uh eleven one two three seven eight uh eleven sorry seven eight eleven twelve nine ten sorry seven eight eleven twelve nine ten four five six four five six all right i hope that makes sense i all right i hope that makes sense i think it makes sense it it's think it makes sense it it's under like the name suggests we want we under like the name suggests we want we want to flatten it into want to flatten it into into one list we're given the the node into one list we're given the the node definition here where we've got the definition here where we've got the standard standard val pre and next properties and again val pre and next properties and again we've got child which we've got child which will either point to none or it will will either point to none or it will point to another another node which is point to another another node which is the kind of the starting node of another the kind of the starting node of another list so i'll i'll clear that up just to list so i'll i'll clear that up just to give us a bit more space give us a bit more space um that's about it that's all that there um that's about it that's all that there is to it so they give us a few more is to it so they give us a few more details here on on serialization but details here on on serialization but it's nothing it's nothing nothing to write home about we're told nothing to write home about we're told that we won't have more than a thousand that we won't have more than a thousand and their their values will go up to ten and their their values will go up to ten thousand thousand i don't think that changes much for us i don't think that changes much for us but regardless it's there but regardless it's there we're actually i know it doesn't change we're actually i know it doesn't change much for us because we're going to go much for us because we're going to go through it the standard way through it the standard way and and we're going to think about how and and we're going to think about how we can how we can do this in the most we can how we can do this in the most efficient efficient possible manner so what i've done is possible manner so what i've done is i've come up with this i've come up with this fine drawing right over here this is fine drawing right over here this is some of my best to work it really made some of my best to work it really made me question why i me question why i always did so poorly in art class maybe always did so poorly in art class maybe if i drew linked lists i would have if i drew linked lists i would have gotten a better mark gotten a better mark nonetheless we this is a visual nonetheless we this is a visual representation of the example we just representation of the example we just walked through and so what i wanted to walked through and so what i wanted to do was to do was to to kind of walk through the logic on how to kind of walk through the logic on how we can think about approaching this we can think about approaching this problem problem let me start off actually by saying that let me start off actually by saying that that when i first did it the on my that when i first did it the on my my first time around i had this one in my first time around i had this one in in linear time but i did it in a two in linear time but i did it in a two pass pass solution and i did this uh recursively solution and i did this uh recursively and and what i did was i said let me let me walk through this list and as i once i find a node that's got a child let me make a recursive call and i'll make that recursive call and say you know i'll set this child to next now and um i'm gonna walk through i'm going to keep doing this until i find the the next node with the child and then i'll attach that file or sorry that that node not the file and so what my list would look like was that i'd have something like 1 2 3 7 8 11 12 but then what i do is i'd go back and and walk through from eight up until ten so find this ten so then i'd add the the nine and the ten and then i'd start from the beginning here one two three seven eight eleven 8 9 10 and then go on to 4 5 6 meaning that if i kind of did this recursively i would have to be searching through every element twice to get to the tail of every single list in order to then connect it to the next list so walk through this whole list to connect it to here then kind of once this is all connected walk through once again to then be able to connect the tenth of the four and so if if your head was going somewhere similar like in terms of recursion and doing this uh there's a better way to do i'm only sharing that because that's how i it's not a fail i think that still would have it would have passed but it was a bit more complicated than it needed to be the the approach though in terms of like walking through until we actually find a node with a child that's going to hold water so what we're going to do is we're going to start walking through this thing and we're going to start at the head and really nothing interesting ever happens unless we find a child or rather a node with a child if we don't find one of those we're just going to return the head as it is so we're all good there like that's when the fun begins so let's pretend that i'm i'm starting up a walk at node one and then i'll do something like set curry equal to head and then while curry exists we we continue walking does this have a child no it doesn't nothing to write home about does this have a child no it doesn't not the right home vote does this have a child okay yes it does this thing has a this one has a child over here so what do we want to do by flattening it we are going to want to redirect kind of the direction of this next pointer and we're going to want to move it downwards meaning my child is going to now become my next it's going to almost like pivot upwards so a couple things we're going to need to do we're going to need to say let me let me almost take this next and i'll make the next pointer go go this way now i know it kind of looks like child but bear with me um i'm going to say my child previous now wants to point this or so i'm going to connect these two like a steady relationship and then i'm going to scrap so one thing that i really messed up when i was doing this problem is i never um this took me so long to figure out but you need to also scrap the child property so once i find a child i want to say let me reroute my next and previous pointers here so that uh my my child comes next in line and then i'll all drop this this child on this child connection so we're kind of looking like this now um if this was my next point or at some or my next note at some point from the node three it no longer is i'm going to sever these relationships i have three relationships that i want to sever and then i want to redirect my um my next and previous pointers respectively the question becomes though what do i actually do with this now even even before maybe before i sever these connections i may be jumping on there let's keep that we'll keep that question let's keep that we'll keep that question off the side and then once we get off the side and then once we get through the end of our walkthrough we'll through the end of our walkthrough we'll we'll kind of decide what we can do with we'll kind of decide what we can do with that as we're as we're doing this that as we're as we're doing this walkthrough and then we'll see how that walkthrough and then we'll see how that how that kind of helps us fill in the how that kind of helps us fill in the entire uh picture from start to finish entire uh picture from start to finish so so i think so far we're so good and so for i think so far we're so good and so for actually our picture is looking how we actually our picture is looking how we wanted to we now have one two three wanted to we now have one two three seven eight so this is exactly how we seven eight so this is exactly how we want it to start so i know i know want it to start so i know i know that imagine this down there it's no that imagine this down there it's no longer a child it's like a next longer a child it's like a next pointer we've got one two three uh seven pointer we've got one two three uh seven eight but then we get to the eight so i eight but then we get to the eight so i mean mean i'm no longer here seven eight i get to i'm no longer here seven eight i get to the eight the eight and now the eight has a child so once and now the eight has a child so once again i'm gonna repeat the same process again i'm gonna repeat the same process i'm gonna kill off this relationship i'm gonna kill off this relationship i'm going to kill off this relationship i'm going to kill off this relationship so these two are no longer connected i'm so these two are no longer connected i'm going to make my next point down here going to make my next point down here my child's previous now is going to my child's previous now is going to become my current node become my current node the 8 and i'm going to sever this child the 8 and i'm going to sever this child relationship we don't have a child relationship we don't have a child anymore without the next and previous anymore without the next and previous so what does our list look like we've so what does our list look like we've got one two three seven eight eleven got one two three seven eight eleven twelve twelve so we're getting there right in the so we're getting there right in the original example original example we had one two three one two three we had one two three one two three seven eight eleven twelve is now we got seven eight eleven twelve is now we got this 910 and 456 to deal with this 910 and 456 to deal with we've got 910 over here which is like in we've got 910 over here which is like in in no man's land and same with this four in no man's land and same with this four five six five six and what are we going to want to do and what are we going to want to do about these well about these well let's think about it this way now um so let's think about it this way now um so i've found i've found eight and i've done this connection i eight and i've done this connection i want to keep walking through want to keep walking through my next variable at this point or my my next variable at this point or my next uh my next value is the 11 next uh my next value is the 11 my next one after that it's got no child my next one after that it's got no child so i keep going i get the 12 so i keep going i get the 12 and i notice that 12 warm at the end of and i notice that 12 warm at the end of my walk my walk so whatever list i have now i'm at the so whatever list i have now i'm at the end of it and i'm sitting at the tail of end of it and i'm sitting at the tail of this list this list so what the hell do i do so what the hell do i do well in an in an ideal world well in an in an ideal world we know that we want our next answer to we know that we want our next answer to look like this i want to get from this look like this i want to get from this 12th this 9 somehow now 12th this 9 somehow now so how do i do that i'm sitting at 12 so how do i do that i'm sitting at 12 i've got the last item in my tail i'm i've got the last item in my tail i'm not off the i'm not often let's see i not off the i'm not often let's see i don't have the last item don't have the last item and i want this item here okay well and i want this item here okay well let's say hypothetically add access to let's say hypothetically add access to this line over here for just one second this line over here for just one second what i would ideally like to do is i'd what i would ideally like to do is i'd like to say let me let me set like to say let me let me set my my next pointer this way my previous my my next pointer this way my previous pointer this way so i'm going from 7 pointer this way so i'm going from 7 eight eleven twelve nine and nine points eight eleven twelve nine and nine points backwards this way and then we continue backwards this way and then we continue the ten the ten so we've got one two three seven eight so we've got one two three seven eight eleven twelve nine ten all right this is eleven twelve nine ten all right this is where we wanna be so far right where we wanna be so far right nine ten and then i was nine ten and then i was sitting at this fault i'm done with it sitting at this fault i'm done with it i'm going to keep walking through my i'm going to keep walking through my list list i'm going to keep walking to 9. i'm i'm going to keep walking to 9. i'm going to keep walking to 10. i'm not the going to keep walking to 10. i'm not the tail of my list tail of my list what do i do now well what about this what do i do now well what about this bad way right we wanted this bad way right we wanted this we wanted somehow to keep a reference to we wanted somehow to keep a reference to this this four this this four five six and so again in an ideal world five six and so again in an ideal world i can kind of point this i can kind of point this next this way i could point this next this way i could point this previous here and now we've got previous here and now we've got one two three seven eight eleven twelve one two three seven eight eleven twelve nine ten if i was to continue my walk nine ten if i was to continue my walk from 10 i go to 10 dot next is four from 10 i go to 10 dot next is four four on x is five five dot next is six four on x is five five dot next is six and now we're at the end we're done and now we're at the end we're done the main question here is though there's the main question here is though there's one kind of assumption that i made which one kind of assumption that i made which i haven't clarified how i'm going to do i haven't clarified how i'm going to do this yet this yet actually this was fine um is what do i actually this was fine um is what do i do with these do with these well let's think about it the first item well let's think about it the first item that i i dislocated or kind of yanked that i i dislocated or kind of yanked off was 456 off was 456 and then what i did was the the 910 and then what i did was the the 910 if you think about the order in which we if you think about the order in which we did these in the the nineteen nine ten did these in the the nineteen nine ten came after the four five six came after the four five six meaning the last thing that i dislocated meaning the last thing that i dislocated or pulled off is the first one i'm going or pulled off is the first one i'm going to want to reattach to want to reattach what data structure does that remind you what data structure does that remind you right what if we get the stack of these right what if we get the stack of these so what if i said when i came to this so what if i said when i came to this three originally and i said i noticed three originally and i said i noticed that a child that a child okay let me say that if i've got okay let me say that if i've got something after the three if i've got a something after the three if i've got a next next node if i do because i may not i have node if i do because i may not i have one here let me take that note let me one here let me take that note let me take a reference to it in memory take a reference to it in memory and put it in a stack and let me do this and put it in a stack and let me do this every other time i have a child so i'm every other time i have a child so i'm going to continue my trigger so i'm going to continue my trigger so i'm going to get the eighth going to get the eighth and when i do this whole business would and when i do this whole business would be with the 11 and changing the child up be with the 11 and changing the child up what if i took the 9 and said let me now what if i took the 9 and said let me now store a reference to the nine store a reference to the nine over here now when i get to the tail of over here now when i get to the tail of my list and i get this fall eventually i my list and i get this fall eventually i got nowhere else to go got nowhere else to go then i realized okay i've gotten to the then i realized okay i've gotten to the end i'm sitting at my tail end i'm sitting at my tail and now that i'm sitting at my tail let and now that i'm sitting at my tail let me check my stock if i have any items in me check my stock if i have any items in my stock my stock pop them off attach them and keep going pop them off attach them and keep going so so we pop it off we attach we do this next we pop it off we attach we do this next for your business for your business we keep going we walk to the nine we we keep going we walk to the nine we walk the tent we're at the end of the walk the tent we're at the end of the list list check the stock do i have anything in check the stock do i have anything in the stock i do the stock i do pop it off pop off the floor pop it off pop off the floor attach attach keep walking attach attach keep walking keep walking keep walking we're at the keep walking keep walking we're at the end nothing in the stock end nothing in the stock we're done so the key trick here is to we're done so the key trick here is to keep keep walking through the rate that always walking through the rate that always sweet until right at the tail and once sweet until right at the tail and once we get to the tail we get to the tail we want to check the stock meanwhile as we want to check the stock meanwhile as we're walking through if we've got a we're walking through if we've got a child child we're gonna we're gonna rearrange this we're gonna we're gonna rearrange this relationship this next grieve child relationship this next grieve child business going on uh we're gonna take business going on uh we're gonna take the we're gonna take the we're gonna take what would have been if it's there the what would have been if it's there the the next point we're gonna put it on a the next point we're gonna put it on a stack stack and as we keep walking on through we're and as we keep walking on through we're gonna start once we get to the end we're gonna start once we get to the end we're going to pop going to pop off the stock until the stock is empty off the stock until the stock is empty that's so we're going to rebuild that's so we're going to rebuild and and make this thing flat so this is and and make this thing flat so this is how we're going to do it iteratively how we're going to do it iteratively we're going to do it in in all of n we're going to do it in in all of n space we're only hitting every element space we're only hitting every element once once sorry all of that time and sorry all of that time and hypothetically in a worst case i guess hypothetically in a worst case i guess this would be o event space where we this would be o event space where we could have a list that actually goes could have a list that actually goes straight down so every item just only straight down so every item just only has a child that doesn't have has a child that doesn't have anything else so we could keep kind of anything else so we could keep kind of building a stack uh that way we'd keep building a stack uh that way we'd keep kind of unwinding it so linear time kind of unwinding it so linear time linear space linear space i hope that made sense i i think the i hope that made sense i i think the code won't be too code won't be too too difficult to deal with and yeah we too difficult to deal with and yeah we can uh we can figure it out so at this can uh we can figure it out so at this point point let's pull it up i'm pulling up some let's pull it up i'm pulling up some notes here that i got just because uh notes here that i got just because uh there are a few like moving pieces here there are a few like moving pieces here and i'm kind of starting to realize that and i'm kind of starting to realize that it's it's almost better to it's it's almost better to sometimes i'll keep my notes here on the sometimes i'll keep my notes here on the side as i'm going through the code just side as i'm going through the code just so we don't so we don't uh spend time in in confusion and yeah uh spend time in in confusion and yeah anyways we'll see how this walkthrough anyways we'll see how this walkthrough goes i hope it's smooth enough but goes i hope it's smooth enough but uh anyways we said that we don't need to uh anyways we said that we don't need to do any error checking because we're do any error checking because we're going to have a linked list of at least going to have a linked list of at least length one so what we can do then is we length one so what we can do then is we can just begin can just begin by uh stating or not stating but by uh stating or not stating but declaring the declaring the stack over here we're going to create stack over here we're going to create the stack so just the stack so just any empty stack and we're going to start any empty stack and we're going to start by saying let's create a pointer called by saying let's create a pointer called cur which is going to point to the head cur which is going to point to the head and we're going to use this courageous and we're going to use this courageous as our our walk through through the list as our our walk through through the list as as as we would with a standard walk through as we would with a standard walk through so while kerr actually exists so while kerr actually exists we start walking if uh if cur we start walking if uh if cur dot child exists so really again this is dot child exists so really again this is where things are gonna get fun if we're where things are gonna get fun if we're pointing at an pointing at an item and that item has a child that's item and that item has a child that's we're gonna have to do a whole bunch of we're gonna have to do a whole bunch of logic logic otherwise typically if we don't we would otherwise typically if we don't we would just say let's go on to the next item just say let's go on to the next item and and typically what we do is we would and and typically what we do is we would just say uh cur is equal to curd.next just say uh cur is equal to curd.next um i'll leave that here for now but i'm um i'll leave that here for now but i'm i'm going to change it just very i'm going to change it just very slightly once we actually build the slightly once we actually build the build the logic into here uh build the logic into here uh what i want to do then i'm going to undo what i want to do then i'm going to undo this a bit this a bit and so maybe maybe we'll start from here and so maybe maybe we'll start from here so let's say imagine that we're sitting so let's say imagine that we're sitting at this at this eight and then we think about what we're eight and then we think about what we're going to need to do in terms of severing going to need to do in terms of severing these ties these ties putting this onto the stack and then putting this onto the stack and then rearranging rearranging um our relationship with the with the um our relationship with the with the child child if we have if our current dot next if we have if our current dot next actually exists so if we have an item actually exists so if we have an item after the eight because we don't after the eight because we don't necessarily need to right these could necessarily need to right these could not exist that's that's perfectly valid not exist that's that's perfectly valid if they are there we're going to want to if they are there we're going to want to take take that item and append it so credit next that item and append it so credit next we're going to want to put it on our we're going to want to put it on our stack stack and also once we put on the stock we're and also once we put on the stock we're going to want to sever this this going to want to sever this this previous relationship we're not going to previous relationship we're not going to want that anymore want that anymore so we're going to say curd.next.previous so we're going to say curd.next.previous is equal to none that previous isn't is equal to none that previous isn't going to exist anymore going to exist anymore we will then say uh cur.next is equal to we will then say uh cur.next is equal to child the reason we're going to say that child the reason we're going to say that is because we've severed this is because we've severed this i now want to sever this as well i now want to sever this as well and make it point down here okay and make it point down here okay we're going to kill this one in a second we're going to kill this one in a second too um what we're going to want to say too um what we're going to want to say before we kill it though is we're going before we kill it though is we're going to have to reference our child and say to have to reference our child and say create a child so the 11 create a child so the 11 and set its previous up to equal where and set its previous up to equal where we are to occur we are to occur so curve.child.preview is equal to occur so curve.child.preview is equal to occur that's going to create that's going to create again this relationship right over here again this relationship right over here and finally so we're going to get a and finally so we're going to get a weird air if we don't do this but we weird air if we don't do this but we want to scrap the child want to scrap the child relationship all together so we need to relationship all together so we need to kill this off so we're going to say kill this off so we're going to say ker.child ker.child is equal to none now let me put a bit is equal to none now let me put a bit more space here more space here since we've set kerr dot next to equal since we've set kerr dot next to equal child if i now say curve equals ker.next child if i now say curve equals ker.next that'll that'll actually jump us that'll that'll actually jump us straight down um this child here so from straight down um this child here so from the eight i wouldn't go to the nine the eight i wouldn't go to the nine because i've killed this relationship it because i've killed this relationship it would actually take me straight to the would actually take me straight to the 11. 11. however i'm going to elaborate on this however i'm going to elaborate on this logic very slightly and i'm going to say logic very slightly and i'm going to say that we're only going to go here if that we're only going to go here if cur.next actually exists cur.next actually exists otherwise i'm going to want to break out otherwise i'm going to want to break out of this while of this while and here's the reason why think about and here's the reason why think about what happens if i make my way down here what happens if i make my way down here and eventually i make it to the 12. and eventually i make it to the 12. if i set curve equal to curr.next i'm if i set curve equal to curr.next i'm going to be out here going to be out here pointing at nothing my problem here is pointing at nothing my problem here is going to be then if i want to pull going to be then if i want to pull something off the stack like i want to something off the stack like i want to take the 9 and set it to the tail of my take the 9 and set it to the tail of my of my previous of my previous list i'm not going to have any access or list i'm not going to have any access or reference to the tail because i popped reference to the tail because i popped it off it off so for that reason i'm going to say if so for that reason i'm going to say if cur.next exists cur.next exists let's go there but if it doesn't if it let's go there but if it doesn't if it doesn't that must mean that cur doesn't that must mean that cur is now pointing to my tail if curve is is now pointing to my tail if curve is pointing to my tail pointing to my tail i want to break out of that loop i want i want to break out of that loop i want to leave that tail reference where it is to leave that tail reference where it is so that when i take items off the stack so that when i take items off the stack i can actually i can actually reference them to the the tail of my of reference them to the the tail of my of my current list my current list so that's going to mean that we're going so that's going to mean that we're going to want to see now while stock so if to want to see now while stock so if there are no items in the stack by the there are no items in the stack by the way like way like nothing's going to happen and we're good nothing's going to happen and we're good we're just like we're just like it's fine no no we're not going to have it's fine no no we're not going to have any logic here there have been no any logic here there have been no children that's cool we're going to children that's cool we're going to return return the list as it was and maybe i should the list as it was and maybe i should have done this at the start but that have done this at the start but that just means we're going to return just means we're going to return ahead so the the head pointer that was ahead so the the head pointer that was originally inputted i'm not moving that originally inputted i'm not moving that anywhere i'm not creating anywhere i'm not creating any new variables for the head that any new variables for the head that reference and memory is still going to reference and memory is still going to be returned be returned the only thing we're changing is uh not the only thing we're changing is uh not the items in memory but where where the the items in memory but where where the pointers are pointing to within pointers are pointing to within within memory so if there is a stack and within memory so if there is a stack and we jump in we jump in uh i'm going to say so we had a curse uh i'm going to say so we had a curse still exist cursed the tail still exist cursed the tail of of our our length of so imagine this of of our our length of so imagine this 12 over here 12 over here i'm going to want to set my cur.next i'm going to want to set my cur.next equal to equal to stack.pop so whatever's at the top of my stack.pop so whatever's at the top of my stock i'm going to take it off stock i'm going to take it off and i'm going to say cur.next is going and i'm going to say cur.next is going to point there so we're going to point to point there so we're going to point it it this way that item now this 9 for this way that item now this 9 for instance is now cur.next instance is now cur.next so curv.next which is again the 9 well i so curv.next which is again the 9 well i want to take this 9 and make its want to take this 9 and make its previous previous pointer to the 12 so it's my current pointer to the 12 so it's my current value value so crew.next.3 is equal to current so crew.next.3 is equal to current now that i've done that we we have this now that i've done that we we have this relationship here relationship here i'm going to want to take i'm still i'm going to want to take i'm still sitting at this 12. i'm going to want to sitting at this 12. i'm going to want to say let me say let me walk through let me keep walking through walk through let me keep walking through this list until i get to the end this list until i get to the end okay none of these items now are going okay none of these items now are going to have a child we'd already severed to have a child we'd already severed every child relationship that could every child relationship that could exist exist they're not going to have any children they're not going to have any children but we still want to walk through the but we still want to walk through the end until we get to the tail end until we get to the tail and not pass the tail because once i get and not pass the tail because once i get to the tail here i'm going to want a to the tail here i'm going to want a reference reference from the top of my stack down to this from the top of my stack down to this tail over here so i can make this tail over here so i can make this connection connection meaning that i'm going to say walker and meaning that i'm going to say walker and curdo curdo next so while there's well this item next so while there's well this item actually actually is not none um although i think actually is not none um although i think actually even just seeing wow even just seeing wow ker.next should be sufficient here i can ker.next should be sufficient here i can test that out after um test that out after um so while my item is none and i also have so while my item is none and i also have somewhere to go somewhere to go then i'm going to say crazy equal to then i'm going to say crazy equal to next if i've got nowhere to go then next if i've got nowhere to go then we're going to stick where we are we're going to stick where we are and we'll attach what we need to uh from and we'll attach what we need to uh from the stack we'll pop it off the stack we'll pop it off and i'm going to run this very quickly and i'm going to run this very quickly because that should be it because that should be it child is not defined because that should child is not defined because that should be curved be curved child shouldn't it see if i did anything child shouldn't it see if i did anything else else should be okay cool all right so you see should be okay cool all right so you see it passes like with it passes like with flying colors is very well and and like flying colors is very well and and like i said i think that this here is i said i think that this here is redundant redundant um i hope i'm not gonna um i hope i'm not gonna there you go all right so exact same there you go all right so exact same solution with a bit less code and solution with a bit less code and there's like a 30 something percent there's like a 30 something percent difference in the uh difference in the uh in the speed so so don't worry about in the speed so so don't worry about that as long as your your complexity is that as long as your your complexity is where you where you want it to be where you where you want it to be so just we can we can do a quick recap so just we can we can do a quick recap of how we solve this of how we solve this uh we said that we're going to want to uh we said that we're going to want to start walking through this list and start walking through this list and we're going to pause we're going to pause and think about what to do if we ever and think about what to do if we ever hit a child we ever hit a child hit a child we ever hit a child um if we ever hit a node that or we um if we ever hit a node that or we reach a node that has a reach a node that has a a child pointer i'm sorry and uh a child pointer i'm sorry and uh so if that's the case we're going to so if that's the case we're going to want to think about a few things we're want to think about a few things we're going to need to add going to need to add whatever we're cutting off whatever's whatever we're cutting off whatever's after us our next value to after us our next value to to the stack um if it exists once it to the stack um if it exists once it does does once we've added it we're going to sever once we've added it we're going to sever these relationships we're going to these relationships we're going to recreate the next and previous recreate the next and previous relationships with with the child now relationships with with the child now and we're going to cut that child and we're going to cut that child relationship relationship off rinse and repeat until we get to the off rinse and repeat until we get to the end of the list end of the list right until we're sitting at the tail right until we're sitting at the tail once we're sitting at the tail once we're sitting at the tail we're going to want to say let's go to we're going to want to say let's go to the stack and whatever items we've saved the stack and whatever items we've saved for later for later let's bring them back and reattach them let's bring them back and reattach them right every time we reattach we'll say right every time we reattach we'll say i've attached this extra branch on and i've attached this extra branch on and i'm going to walk through the branch i'm going to walk through the branch until again i get to the tail that's until again i get to the tail that's what this piece of code right here is what this piece of code right here is doing doing once i get to the tail i'm going to go once i get to the tail i'm going to go back to the top of my while loop here back to the top of my while loop here and say grab the next item off the stack and say grab the next item off the stack pull it down reconnect those pull it down reconnect those relationships relationships right here walk through to the end wait right here walk through to the end wait at the tail at the tail rinse and repeat once we're done we rinse and repeat once we're done we return the original head return the original head and that's it guys i hope this made i and that's it guys i hope this made i hope this made sense i thought it was a hope this made sense i thought it was a pretty pretty neat trick on on how to work especially neat trick on on how to work especially with the stack it wasn't something that with the stack it wasn't something that i thought of i thought of on my first goal so i hope this video on my first goal so i hope this video helped if it did like comment share helped if it did like comment share subscribe all that good stuff subscribe all that good stuff and i'll see you guys in the next video and i'll see you guys in the next video peace
2024-03-22 11:22:37
430
https://i.ytimg.com/vi/N…axresdefault.jpg
FLATTEN A MULTILEVEL DOUBLY LINKED LIST (Leetcode) - Code & Whiteboard
_KAjEdomX7M
[Music] Torch Light Welcome Back Pade Hai This Problem List Code 84 Some of Distance in This Problem and Decision Related to Graph Problem Statement Notes of Loop 007 Connect Note Se Zara Play List and Subscribe Small Distance Between Noida Subscribe Subscribe Subscribe Now to 9 Now to 9 I show you some I show you some confided with confided with example from 2009 2013 for 1000's 2009 2013 for 1000's not from travel e used. not from travel e used. not from travel e used. Problem Solve Distance of 101 Distance Problem Solve Distance of 101 Distance of one to is two distance of 1383 in three of one to is two distance of 1383 in three languages ​​Amazing address what does we know languages ​​Amazing address what does we know how can we find a distance of one how can we find a distance of one word using debit the meaning of On return edit joyfully On return edit joyfully On return edit joyfully dist here and dist here and this question from best equal to new this question from best equal to new intent of eyes and will return gift in intent of eyes and will return gift in converting this is to-do list play list converting this is to-do list play list of graft new map of graft new map a fight between product half this is not a fight between product half this is not fair lovely vikram 025 witch are fair lovely vikram 025 witch are fair lovely vikram 025 witch are and and this GPS is equal to new year a list of this GPS is equal to new year a list of science and and up for lok point i20 for science and and up for lok point i20 for electronic eye plus speech is equal to electronic eye plus speech is equal to new research officer with oo the inte are new research officer with oo the inte are HC in apps HC in apps HC in apps Filter and Oil GPS Switch Off 8086 The one that someone also has to and the reverse right that GPS of Ajwain Add that GPS of Ajwain Add 90 A says a good 90 A says a good one reminder is actually this off but this graph Middle East Using Various Weapons Know Who After 10 We Call Song Deficit And Will Feel Distance To Return To Know Who After 10 We Call Song Deficit And Will Feel Distance To Return To Introspect Total Distance Distance And Presentation Incomplete Distance Distance And Not To Focus On Different Subscribe Subscribe Subscribe Distance Supreme Plus Account Of Pride When They Distance Supreme Plus Account Of Pride When They Are Talking Are Talking Are Talking great distance from a subscribe total account deficit in nod subscribe total account deficit in nod ki pind parents site and schedule ki pind parents site and schedule ki return ek tot waqt se int account 109 subscribe to ki in find next in GPS of not right For all the connected notes of this month I want to avoid A to Z plus security difficult next9 that good any all set to right this next equal to parents the country will fight that 80 look at this day with r jhadu this vaccine A Potato Ko Later To Have Actually Counted In Total Account For A Given More Okay And Trying To Go Step By Step 64 Will Be Too For Election Live Vote From This Video Clips I Want To Calculate Distance Node Equal To Node Equal To Node Equal To Play List Of Is Next Plus Right Good That Social Mrs. D'Souza Ne Are Right Knowledge Total In It Third End Tricks 040 Parents - 1404 Remove This Comment And See What Is The Distance From A Long Way To Calculate Distance Of 00 Subscribe To Saving individual contract Saving individual contract Saving individual contract word this individual can edit modify subscribe and share and subscribe from bottom of runes in the bottom of the deficit to account for individuals are free from fear loot edward this in it third is a complaint against the count of nod plus equal to a that Agar Na White Replace Discount With Account Up Next Ki And Because Of Calculating For Inch Tape Se Distance Of No Difficult Classic Look Look Look Poster For Quality Of Mid Day Meal A Travel Samay Poster Shakkar Dal Disposal Meal A Travel Samay Poster Shakkar Dal Disposal Mithila Tours 272 Plus App Co Co Co Physicians Central Se Account Account Is Of Physicians Central Se Account Account Is Of Science And Schools And On Account Of Noise Science And Schools And On Account Of Noise Loot Support Order And Verifier Don't Stick To It Loot Support Order And Verifier Don't Stick To It Directly How To Directly How To Fix That Doll They Have Completed The Total Distance For The Highest Position More Knowledge Some Help In The Province Of 351 Some Help In The Province Of 351 Some Help In The Province Of 351 Verify Add A Six Sixes Good Civic Bodies For Two A Six Sixes Good Civic Bodies For Two Cars In 14k That Ko Nice E Waiting 10435 This Nice Okay So Definitely Ko Indira G Ki Previous Test One Old And Father Particular Know It Is Successful Written In -list correction equal proportion at which -list correction equal proportion at which -list correction equal proportion at which indicates in for loop in the unit indicates in for loop in the unit digit turns into a bit but will be solution digit turns into a bit but will be solution of class relation distance of quality of class relation distance of quality education for all total solution total education for all total solution total distance for using total distance distance for using total distance calculator the meaning of Total Total Total distance is 12th part in difficulty distance is 12th part in difficulty connected amount and you can see what was connected amount and you can see what was the value water quality account airtel in its ok total give the value water quality account airtel in its ok total give a clear picture of a clear picture of moral value of 10 to anywhere you want moral value of 10 to anywhere you want after 06 2012 after 06 2012 total distance now zero is nadeem malik total distance now zero is nadeem malik total total total tight soen want you already have a total of which has a distance of one also included total distance of descent of total total distance of descent of total subscribe to the whole subscribe to the whole second 500 to 1000 this five second 500 to 1000 this five times a distance of 105 times a distance of 105 times a distance of 105 Distance of 1521 Adhir 110 Subscribe To I just got married The above knowledge can give more clarity on this thank you will take another example Will calculate distance of to-day I am alone How can we distance to using distance from which is acquire record and Now Zero here equates to is the Now Zero here equates to is the Now Zero here equates to is the connected of Zero and when they are collecting to you already have to calculate distance from Jio phone to consider collecting to you already have to calculate distance from Jio phone to consider top-down stay deficit at some relief and top-down stay deficit at some relief and vent of to the truth know your soul from root vent of to the truth know your soul from root and they vent subscribe my account of to 4 total subscribe to torch light admits and declares sorry for a moment to return shot dead in the total distance of to will be total distance from this right side parts and distance FROM THE FROM THE FROM THE LEFT PARTIES TO PUSH ME NOTE 6 - FORBIDDEN LEFT PARTIES TO PUSH ME NOTE 6 - FORBIDDEN ONLY - 4 AND TOTAL DISTANCE FROM THIS RIGHT ONLY - 4 AND TOTAL DISTANCE FROM THIS RIGHT SIDE PATH IS NOTHING BUT A TOTAL SIDE PATH IS NOTHING BUT A TOTAL DISTANCE - SEE IT IS CLEAR NOW THE DID NOT DISTANCE - SEE IT IS CLEAR NOW THE DID NOT FROM LEFT SIDE SHOULDER SO WAR PREVIOUS FROM LEFT SIDE SHOULDER SO WAR PREVIOUS SUBSCRIBE TO BALANCE CALCULATOR MOD n't forget n't forget a right my free water alcohol this a right my free water alcohol this pre-order ok on the contrary order I don't need this pre-order ok on the contrary order I don't need this country are neem and someone already have don't ok country are neem and someone already have don't ok happy will get discount ki ok khoyi hai tourist calculation for more a right click before order and After next that equal to tense of no d - account of contact to have a distance distance of contact to have a distance distance of individual next subscribe is bad individual next subscribe is bad size of size of - dikha findhoon ok ab ki is - dikha findhoon ok ab ki is look gautam in ho akbar de staff look gautam in ho akbar de staff next equal disturb note next equal disturb note next equal disturb note Subscribe to Subscribe to Kaun-kaun zero and mind Kaun-kaun zero and mind aapke khadi hua aapke khadi hua hua hua main let me hua hua main let me Rajesh ko don't si hain to ya is background bank deposit se pher hai ko sadbuddhi length apne a person sulut Default Submit I Want To Taste This Taking Default Submit I Want To Taste This Taking Default Submit I Want To Taste This Taking One Is My One Is My Rushta Hokar Should Take One Is My Root And Tagged As Rushta Hokar Should Take One Is My Root And Tagged As Which Nice Recordist Vikram Which Nice Recordist Vikram Randomly Takes Three Do Places Of Interest Randomly Takes Three Do Places Of Interest In 10 From One Or More Liye Fuel 10th In 10 From One Or More Liye Fuel 10th Result Start For Free Result Start For Free Loot Loot Loot Open Whatsapp Guddu Guddu Will Submit This Loot Gayi A Good Good Night Radhe-Radhe Isi Loot Gayi A Good Good Night Radhe-Radhe Isi Dekhte Hu Find Problem In Following This Dekhte Hu Find Problem In Following This Please Feel Free To Write In Comment Please Feel Free To Write In Comment Interviewer This Post Older Post Third Interviewer This Post Older Post Third Party Easy-to-Follow Tuk A Party Easy-to-Follow Tuk A Party Easy-to-Follow Tuk A
2024-03-22 15:07:54
834
https://i.ytimg.com/vi/_…axresdefault.jpg
Leetcode 834. Sum of Distances in Tree Explained with DFS Solution in O(N) time
AQTrdxW1wiU
hello friends today last of the astronaut collision problem they first astronaut collision problem they first see the statement we are given array see the statement we are given array astronauts of integers representing astronauts of integers representing estrin asteroids in a row for each estrin asteroids in a row for each astral road the absolute value astral road the absolute value represents his size and the site represents his size and the site represents its direction party means represents its direction party means meaning writing negative meaning left meaning writing negative meaning left this is crucial because we will see the this is crucial because we will see the example in a second each astronaut moves example in a second each astronaut moves at the same speed find out the state of at the same speed find out the state of astronaut F after all collisions if two astronaut F after all collisions if two astronauts meet the smaller one will astronauts meet the smaller one will explode if both the same size both will explode if both the same size both will explode two astronauts moving in the explode two astronauts moving in the same direction will never meet so let's same direction will never meet so let's see the example as the 5 and the 10 want see the example as the 5 and the 10 want to go right and the negative 5 want to to go right and the negative 5 want to go left so this 2 will click complete as go left so this 2 will click complete as the absolute value of 10 is greater than the absolute value of 10 is greater than the absolute value of the negative 5 so the absolute value of the negative 5 so their negative 5 will explode then we their negative 5 will explode then we just get to the five intend this to just get to the five intend this to astronauts have the same size and they astronauts have the same size and they want to go to the different direction so want to go to the different direction so they both explode we just written empty they both explode we just written empty array this one and negative 5 once you array this one and negative 5 once you go left and if you want to go right so go left and if you want to go right so this to explode and the US sorry this to this to explode and the US sorry this to conclude and this two will explode we conclude and this two will explode we get to negative 5 and negative 5 we are get to negative 5 and negative 5 we are concrete with the 10 and we get a 10 concrete with the 10 and we get a 10 this example is different because this example is different because negative 2 and next one won't you go negative 2 and next one won't you go left left and the one and two won't you go right and the one and two won't you go right so we just suggested them so we just suggested them so this for astral noise we are not meet so this for astral noise we are not meet so we just return them so the I think so we just return them so the I think the key of this problem is you need to the key of this problem is you need to find a suitable data structure let's see find a suitable data structure let's see how do you find the suitable data how do you find the suitable data structure we handle this extra noise structure we handle this extra noise from left or to right like the fire we from left or to right like the fire we will just first keeper the fire and then will just first keeper the fire and then we meet the ten it has the same we meet the ten it has the same direction with the five so we shall keep direction with the five so we shall keep it and then we meet an active fire as it and then we meet an active fire as they have different direction thrown the they have different direction thrown the 10 so we should handle these two and 10 so we should handle these two and they will conclude and then the next they will conclude and then the next fire wheel exploded well explode so we fire wheel exploded well explode so we get we do not add the neck you find our get we do not add the neck you find our result array you see this example in the result array you see this example in the same way we get the 10 - and then we get same way we get the 10 - and then we get negative 5 it will that's the to explode negative 5 it will that's the to explode and we keep it either will keep make and we keep it either will keep make conclusion with the 10 and the neck if I conclusion with the 10 and the neck if I will explode so L you can see well first will explode so L you can see well first go from left to right and then we we go from left to right and then we we want you make sure if we add this want you make sure if we add this current astronaut into our result array current astronaut into our result array we all go left or to compare one by one we all go left or to compare one by one so I think those older miss may be so I think those older miss may be obvious for you as it'll last in first obvious for you as it'll last in first out so we should use a stack to handle out so we should use a stack to handle the astronaut one by one the astronaut one by one so let's first relate and you will see so let's first relate and you will see how to use this that how to use this that so we'll use the array deck and though so we'll use the array deck and though we just handle every astronauts will see we just handle every astronauts will see some cases the first case is we just some cases the first case is we just added a current astronaut into our stack added a current astronaut into our stack the first situation will be the stack is the first situation will be the stack is empty and the same situation should be empty and the same situation should be it has the same side wheezes or pickup it has the same side wheezes or pickup with the stack so the static he'll pick with the stack so the static he'll pick who comes if it times the a greater than who comes if it times the a greater than zero which means they have the same size zero which means they have the same size so we shall put into the stack and they so we shall put into the stack and they can see this example if the previous an can see this example if the previous an astronaut will go left and the current astronaut will go left and the current will go right so they will not meet that will go right so they will not meet that means if the stack peak is less than means if the stack peak is less than zero and the eighth grade has n 0 we zero and the eighth grade has n 0 we just put a push to the current astronaut just put a push to the current astronaut into the stack but another if not the into the stack but another if not the case we will know that they will make case we will know that they will make conclusions right let's see there is conclusions right let's see there is some example or some cases first the some example or some cases first the case the current astronaut is the size case the current astronaut is the size of the current estrin is less than the of the current estrin is less than the peak of them stack we just her to not peak of them stack we just her to not add them into a stack we are done if add them into a stack we are done if they have the same size posts will they have the same size posts will explode the complicated case is if their explode the complicated case is if their size is greater than the peak of the size is greater than the peak of the stack we will pop from the stack and stack we will pop from the stack and keeper compare so we may need a loop keeper compare so we may need a loop here but we need a to mark if we should here but we need a to mark if we should add a current astronaut into our stack add a current astronaut into our stack so I will use a boolean variable name so I will use a boolean variable name the flag means we do oh if we need to the flag means we do oh if we need to add a current astronaut into our stack add a current astronaut into our stack so Wilder stack is not empty so Wilder stack is not empty and the stack peak times their current and the stack peak times their current restaurant noid is less than zero we restaurant noid is less than zero we know there are simple research cases know there are simple research cases their stack peak eco tutor mess absolute value over there a both will explode and there's a stack which other pop it and the flagger will be there for so we do not yet add a current astronaut into our stack so we just break another case either if the mass absolute value the stack pick it's great to the Ender a we do not need to add as a right and we just let the flag in to the force and a break complicates the case is we needed to explode sir pick up the stack so the stack who were just a pop and their continued to compare so also a loop if their flag is true we push their astronaut into our stack so finally we just needed to gather the result from the stack the size should be the start size and neither result array this set will be n an index will start from the I minus 1 because the stack is last in first out we start from the very last so the kids should be if the stack is not empty a result index minus minus a will equal to the stack top if an okay thank you for watching see you next okay thank you for watching see you next time
2024-03-21 11:52:35
735
https://i.ytimg.com/vi/A…axresdefault.jpg
LeetCode 735. Asteroid Collision Explantion and Solution
aIfT0QJQFKg
foreign [Music] immutable let's read the question given an integer array Norms it handles multiple queries of the following type calculate calculate the sum of the elements of nums between indices left and right in laser where left equal to less than or equal to right so implement the array norms they are given an integer and we are given a queries so you need to sum up the elements between from left to the right including those elements see if you can see the example this is the error and uh the these are the queries so 0 to 2 means you have to add from minus to 0 3. so 2 to 5 is R3 minus 5 minus 2 minus 1 you have to add the elements in between those ranges let's see how to solve let's say how we can solve this problem so you have a randoms minus two zero three minus five to minus 1. so the first query is 0 comma 2 so 0 is the left one and the 2 is the right number so if we look into the error you can see minus 2 0 3 or falls under in between 0 to 2 so we need to sum up those elements minus 2 plus 0 plus 3 equal to 1. and then next Y is 2 to 5. if we check it in there then it is a 3 minus 5 2 minus 1. so if you add up if you add all those elements we got the minus one so coming to the time complexity every time for every query we have to Traverse from left to right so there are M queries and uh n elements to Traverse so the time complexity is admin to n it's a very time consuming and slow process for every sub query we have to Traverse again and again so can we do better yes we can do it with the help of prefix some concept so now I will explain the prefix some concept so so first if you take the original array let's take the original array minus two zero three minus five two minus one so first we will same we will keep the same element in the first question minus 2 then we take that number minus 2 and add it to the next element so the minus 2 plus 0 then it becomes a minus 2 again then from my again take that updated minus 2 and add it to the next element and replace that next element with the updated value minus two plus three this one just update it again 1 plus minus 5 minus 4 updated in the next position like that minus 4 plus 2 minus 2 a next minus 2 plus minus 1 minus 3 yeah now we got the prefix some array just we Traverse the entire array only once now can we do that queries in constant time with the help of this prefix sum yes we can do it let's take some examples like the first query is 0 comma two zero is the left one and two is the right ah and you can see here I high highlighted the number one zero second position in the area so that is the answer for 0 to 2 see if the left num the left value in the query is zero the result is nums of red because till 2 we added the all numbers so the second question contains the summation of 0 to 2. so that's the click behind this prefix sum let's take a one more query 2 comma 5 if we highlight the two comma Five Points then these are the points one comma and minus three I want the sum of these in between these elements now let's see the condition the left is not equal to zero yes it is not zero it is actually two then the result is nums of right minus nums of left minus one so basically you are taking the fifth position element that is the summation of from 0 to 5 and then we are removing we are removing some we are removing some x value from that uh numps right so what we are doing is we already we need in between two to five but we have taken in between in between 0 to 1 in the summation of five so we need to remove that that's why we take nums of five minus nums of one that means minus 3 minus minus 2 that's the minus one answer so the time complexity for this solution is of n times yes you need to Traverse entire area once and you need to make a prefix some array by using that we prefix sum you can do every sub whereas every sum I mean every query you can do it in of one time now let's write the code for this problem now first we will write the code in Python then we will write the code in Java also first self dot nums equal to nums yes I'm very variable s equal to zero for in range 0 comma then we need to create a prefix array so then we need to create a prefix array so we are starting from 0 to and length of we are starting from 0 to and length of nums that means the number of lines is 5 nums that means the number of lines is 5 then 0 1 2 3 4 so first element we it then 0 1 2 3 4 so first element we it have to kept it as a same element so have to kept it as a same element so just adding nums of five just adding nums of five plus equal to S just first the element s plus equal to S just first the element s is I mean the variable s is zero we are is I mean the variable s is zero we are adding it to the first element in the adding it to the first element in the array initially array initially so it it won't change so the next we so it it won't change so the next we need to update the S variable nums of I need to update the S variable nums of I then again next element when it added then again next element when it added the previous element and it creates a the previous element and it creates a entire prefix sum entire prefix sum so now we created the prefix sum so now we created the prefix sum so we just add yourself dot nums cell dot nums then now we need to write cell dot nums then now we need to write the code for the queries the code for the queries left equal to 0 left equal to 0 then then return return cell dot nums right else return dot nums off right minus of now let's run this code [Music] done now we will write the code in Java done now we will write the code in Java also initializing nums in test equal to zero you didn't you don't need to use this uh extra variable you can do it in you can do it directly I can manipulate that nums array directly you don't need to use this table just you need to think up with a different logic I mean this is a more I equal to zero a less than nonstop length I I plus equal to s plus equal to s equal to equal to numbers of I uh this dot nums equal to numbers now we created the prefix array now just write we will write the code for the foreign runs off else else written written lumps off right lumps off right minus sums of minus sums of F minus one [Music]
2024-03-24 10:01:11
303
https://i.ytimg.com/vi/a…axresdefault.jpg
Leetcode - 303 Range Sum Query - Immutable (Easy) in Java,Python
gsnTEtiN8T8
subscribe subscribe subscribe ko Video then subscribe to Video then voice mail solution intermediate let's move with oo are unique pass veer lead wave subscribe wave subscribe Subscribe What is the Meaning Meaning Adhik Hai Adhik Hai Mein Soega Robot Movie With Ispat Mein Soega Robot Movie With Ispat Aur Dasham CPMT Sales And Ka Word And Aur Dasham CPMT Sales And Ka Word And Finally Veervikram Working In Path In 10 Minutes Recent Statements Of Witnesses Who Want To 040 040 Subscribe Subscribe To That Last Yeh Movie Mein Process Bandhe Don't Want To To That Last Yeh Movie Mein Process Bandhe Don't Want To Deal With Same To You Now Skin Deal With Same To You Now Skin Adhir Adhir V subscribe V subscribe Video Subscribe Subscribe Subscribe Subscribe To Hai What Is The First Day Cover Back Feedback Where Is The Mission More Robot Veer Robot Veer Veer Subscribe To Hai To Ise Dhokar Problem And You Will Get To No More Avoiding Porn Subscribe Video Subscribe Subscribe Reddy Subscribe Subscribe Main Andhero Account Select Swaroop Main Andhero Account Select Swaroop Dheer Va Subscribe Subscribe Subscribe Volume Day In All Directions From In All Directions From In All Directions From The Amazing The Amazing Plunge In Veer Veer Veer Plunge In Veer Veer Veer Veer Subscribe subscribe our subscribe our Channel subscribe Video Subscribe
2024-03-25 14:23:26
980
https://i.ytimg.com/vi/g…svl4PvU6CtlyWoRQ
Unique Paths III | Leetcode 980 | Live coding session 🔥🔥🔥| DFS with backtracking
vAroILlQK0I
[Music] so today i want to talk about create today i want to talk about create reversal and as you know trade reversal reversal and as you know trade reversal is basically moving on a tree between is basically moving on a tree between nodes through different edges and if any nodes through different edges and if any of this of this terminologies does not make sense to let terminologies does not make sense to let me know in the comment section and be me know in the comment section and be happy to explain them in more detail happy to explain them in more detail in an interview setting there are three in an interview setting there are three main approaches that we can do to main approaches that we can do to traversal with one is pre-order traversal with one is pre-order the other one is in order and the last the other one is in order and the last one is post order and each of them can one is post order and each of them can be implemented either be implemented either iteratively or recursively in today's video i will be talking about the pre-order approach and i'll talk about post order and in order on separate videos later there are two things one need to know about pre-order app which you want is that it's a top to bottom approach meaning that if this is your root you start from the root and you move toward the leaves that there are somewhere at the bottom of three and the second thing is that the procedure is that you start from the root you cover left subtree and then you cover right subtree it means that if this is your root and there exists a left subtree i'm going to call it left subtree and i'm going to call this right subtree so you need to cover the whole thing on the left subtree before moving to the right subtree and cover that and assume left subtree here and then we have left subtree here and then we have right subtree right right subtree right but the right subtree has two parts but the right subtree has two parts let me make it clear let me make it clear the right subtree has the right subtree has a left subtree of his own and a right a left subtree of his own and a right subtree of its own subtree of its own when you come here when you come here you cover this node and then you go and you cover this node and then you go and cover the whole left subtree of this cover the whole left subtree of this node before moving to the right subtree node before moving to the right subtree of this node i hope it's clear but we'll of this node i hope it's clear but we'll do some examples in the first example you're given this tree as you can see note that in an interview setting you note that in an interview setting you don't get that the actual shape of the don't get that the actual shape of the tree schematic you get a list like this tree schematic you get a list like this and generally it's leveled like it and generally it's leveled like it starts from level one this is loot level starts from level one this is loot level level two and then level two and then for level two it starts from left to for level two it starts from left to right and so on and so forth and they right and so on and so forth and they ask you to do ask you to do to process or traverse the tree using a to process or traverse the tree using a pre-order approach pre-order approach and what you do is that you start from and what you do is that you start from the root you add one the root you add one if there is a left subtree you go left if there is a left subtree you go left which is which there is here you add two which is which there is here you add two and then you cover the right subtree so and then you cover the right subtree so basically one two three is the basically one two three is the correct here thing here and then you correct here thing here and then you want to do want to do example number two let me clear this example number two let me clear this stuff here i hope stuff here i hope you understood it was talking about and when you want to do here note that because there is no left subtree here in the input we have no but you start again from the root you add one there is no left sub three so you go to right you get here you add two and then here basically this is your new route you need to cover left subtree first you come here and then you cover number three that's why you get one two three so now we get to the last example example number three for the pre-order case and then i just added this procedure here as a reminder you start from the root you cover left subtree lst and then you cover right subtree and for this example you want to know what is the pre-order traversal right we have an array of you add one here you add one here then you're supposed to cover the whole then you're supposed to cover the whole left subtree before you move to the left subtree before you move to the right subtree right so we come here right subtree right so we come here oops right and now basically 2 is our new right and now basically 2 is our new root root right 2 is our new root we need to cover right 2 is our new root we need to cover let me change colors let me change colors you need to cover the left subtree of you need to cover the left subtree of two two everything about the left sub two of two everything about the left sub two of two before you move to the right subtree up before you move to the right subtree up to to therefore therefore you add you add four here four here you cover this one you cover this one and then when you go you get to the and then when you go you get to the leave you go up leave you go up you come to two have you covered the you come to two have you covered the right subtlety no now you come down to right subtlety no now you come down to the right subtree up two and then the right subtree up two and then you add five you add five now your five is your new root you go now your five is your new root you go left left you add seven you add seven when you come to a leaf you go back to when you come to a leaf you go back to the root is your right sub to yes there the root is your right sub to yes there is there you go and you cover it now you is there you go and you cover it now you have eight have eight now what you've done is that you covered now what you've done is that you covered the whole the whole left subtree of the main root the actual left subtree of the main root the actual root of the tree now root of the tree now what you do let me change color you go what you do let me change color you go to right subtree you need to cover the to right subtree you need to cover the whole thing here now whole thing here now when you go right you have this one when you go right you have this one therefore therefore you add three to the list you add three to the list and then you come down you there is no and then you come down you there is no left left is null here so you come down left left is null here so you come down you add six you add six and once you're at six six is basically and once you're at six six is basically your new root what do you have you need your new root what do you have you need to cover left subtree first you come to cover left subtree first you come here you add nine here you add nine now you now you cover the whole right subtree basically cover the whole right subtree basically your output your output is going to be is going to be 1 1 2 2 4 4 5 5 7 8 7 8 3 3 6 9. 6 9. i hope i haven't made any mistake but i hope i haven't made any mistake but the whole idea is that whatever node the whole idea is that whatever node you're at you're at whatever node you're at let's say you whatever node you're at let's say you are at this node are at this node right right you need to cover the left subtree if you need to cover the left subtree if there is a left subtree first and once you get to the leaf you move back basically to the root and then you go and you cover the right subtree and you do this either iteratively or recursively as i'm going to talk about later so let's do an actual coding problem for this i'm going to do an easy problem let me change color let me change color so it's like so it's like a binary tree pre-order a binary tree pre-order traversal as you can see here traversal as you can see here it's you're given a root it's you're given a root and with a binary tree and with a binary tree if you don't know what is binaries you if you don't know what is binaries you just google it's a tree which has just google it's a tree which has for each node maximum of two channels so for each node maximum of two channels so it's like something like this and um you're required to return the pre-order traversal of the notes we talked about a couple of exam three examples actually before but as an additional example you can see here you're given this and the pre-order result as we talked about is one two three and on a solution section note that you're given a three note class if you don't know what is a class in python just google and i also i honestly think that if you want to do that code or if you want to be a good programmer learn about class just spend a couple of hours learn about class what it is exactly and what's where it's useful and where it's not useful and why there are there are classes out there why they exist so a three node class is a class which has a value a left node and a right node basically it's you have a node white node or left node it can be null or none as it is by default you can see here its default is not and the default value is 0 and each node so for example this node has a value for itself and it has a left node and what i'm going to do here i'm going and what i'm going to do here i'm going to talk about two approaches to talk about two approaches one recursive iterative approach iterative approach note that uh generally cursive is a note that uh generally cursive is a little bit easier little bit easier than than iterative that's why i'm going to talk iterative that's why i'm going to talk about it about it all right let's first talk about a all right let's first talk about a recursive solution recursive solution i hope you know what is a recursive i hope you know what is a recursive solution but if you're not please make solution but if you're not please make sure that you understand what is a sure that you understand what is a recursive solution by googling and there recursive solution by googling and there are a lot of uh problems are a lot of uh problems on lead column on lead column on the internet that can be solved using on the internet that can be solved using a recursive approach a recursive approach i talked about the first part here this i talked about the first part here this is a three note class is a three note class which basically is you have a node you which basically is you have a node you have left and right subtree or left and have left and right subtree or left and right basically children right basically children and the way i'm going to write the code and the way i'm going to write the code here as you can see here i'm going to here as you can see here i'm going to basically use the class approach and i'm basically use the class approach and i'm going to define two functions within the going to define two functions within the class solution class solution and i initiate an empty list and i initiate an empty list as you can see here the as you can see here the self res res stands for results and i'm self res res stands for results and i'm gonna return that self rest finally as gonna return that self rest finally as my output but my output but using this using this middle function the self traverse route middle function the self traverse route which basically is a function called which basically is a function called traverse traverse and you can see the function here i'm and you can see the function here i'm going to talk about in a minute going to talk about in a minute which accepts the route which accepts the route and then does some stuff updates the res and then does some stuff updates the res and finally i return the rest and finally i return the rest in this line as you can see here in this line as you can see here but the main part of the code is but the main part of the code is the traverse function the traverse function this function basically this function basically this function is part of the class this function is part of the class solution that's why there is a self here solution that's why there is a self here and then it accepts the root and then it accepts the root the reason that we don't need to add res the reason that we don't need to add res here like having something like this is here like having something like this is that because that because it's part of the class it's part of the class if you don't know why i don't have res if you don't know why i don't have res here but res gets updated here but res gets updated please make sure that you understand how please make sure that you understand how classes work so this is the function that does the updating for us what happens here is that you have a root let me start by an example let's say we have one two the example we talked about before let's say we have this example we're supposed to return one to we're supposed to return one to three three right right it means that you start from here it means that you start from here you're supposed to move here you're supposed to move here and then add two and then we're supposed and then add two and then we're supposed to move here and add three and then it to move here and add three and then it will give us one two three will give us one two three and this is what exactly the traverse and this is what exactly the traverse function does function does the trovers function what it does is the trovers function what it does is that it first checks whether root exists that it first checks whether root exists if the root is none if the root is none it stops it stops it doesn't do anything but if there is a it doesn't do anything but if there is a root meaning that as in first step if the root that you gave which basically is this one that we have here if it exists to the to the self rest which is basically our output self rest which is basically our output right so that value gets added what right so that value gets added what happens happens so far is that we have so far is that we have 1 here 1 here we need to somehow add 2 and 3. what we need to somehow add 2 and 3. what would we do would we do the next thing is that if you remember the next thing is that if you remember in a solution what in a solution what the procedure for pre-order was root left sub 3 and then right sub 3 right so we need to consider left sub 3 here but for example for the example that we're considering here that this tree there is no left software left subtree is null but in a recursive approach what happens is that we call this using the root left right what happens now if we call the same function using left meaning the root left is null what happens that this line does not get passed and we're going to return let's say none here meaning that nothing happens for the case that you're considering here for the exam and what's the next line the next line is that we do the same thing we call the function self.traverse right but this time with root right what is your diet root right is this excuse me with white is this 2 here when we call this function we do it right let me expand this function what happens is that we are we are doing self traverse root and right what is root right is basically 2 three this is what we're doing and what happens if we call this function it goes and start the traverse function again what's the first step in the traverse traverse function note that this is now or new route correct what happens it adds the root value to self.address meaning that this one gets updated here and now 2 is added now 2 is our new root what is the procedure for um pre-order after the dude we need to check and take care of the left sub-order right what happens here is that after we add the let me change color again after we add the two at this line we go and check the left software left stop uh left sub three and this line this line gets called the second line for the left subtree and then that's where three is gonna be added and that's all we don't need anything else there is no other node node and then you got it we have the whole thing we have our output and this is this was we have our output and this is this was as as you know was just an example you know was just an example this approach works for any tree or the this approach works for any tree or the examples we talked about before because examples we talked about before because it's genetic right for each tree if you give the function the root it's going to check the root whether root exists or not if it exists a it adds the root value as should next it takes care of the left subtree and then it takes care of the right subtree note that we talked about this it takes care of the left subtree meaning that once it's gone into this line or this function once this line is calling this function is called again it's going to go to the left subtree does everything for the left subtree first before moving to line c before moving to this line therefore once you have your route which gets added it does everything for the left subtree before moving to the right subtree does that make sense that's pre-order right there you have it next we move to the iterative approach or iterative solution i hope you understood the recursive one and let me know if anything was unclear explain it in more detail i hope i explain it in more detail i hope i haven't been repeating myself too much haven't been repeating myself too much in a recursive part in a recursive part let's move on for iterative approach let's move on for iterative approach the high level idea is the same it the high level idea is the same it doesn't matter you do it recursively or doesn't matter you do it recursively or iteratively iteratively you're doing the pre-order and the you're doing the pre-order and the approach is the same however approach is the same however you do it in a different way to do it you do it in a different way to do it iteratively right and just as a iteratively right and just as a general i don't know tip or like general i don't know tip or like out of experience out of experience whenever i hear hear iterative i'll whenever i hear hear iterative i'll think about why think about why and i'll think about stack and i'll think about stack and and in pretty much all the iterative in pretty much all the iterative examples that i've solved i've used this examples that i've solved i've used this too so maybe it comes handy for you as too so maybe it comes handy for you as well this car this part we covered well this car this part we covered before so we don't need to waste any before so we don't need to waste any time on this time on this and and here here instead of doing your um instead of doing your um recursive approach we're going to focus recursive approach we're going to focus on the iterative and the way we do is on the iterative and the way we do is that we start from the roots that we start from the roots here it is here it is you check the root if there is no root you check the root if there is no root it means that you don't have anything it means that you don't have anything right you have an empty tree you return right you have an empty tree you return an empty an empty list list then then you start from the root if you start from the root if there is a root you add the root to the there is a root you add the root to the stack and you initiate a rest function a stack and you initiate a rest function a res list basically result risk which res list basically result risk which you're going to return at the end here so you start the while and what happens is that let me draw that famous example of ours in this line you're basically doing a in this line you're basically doing a while stack right it means that while while stack right it means that while there is something the stack keep there is something the stack keep running and while stack is empty done running and while stack is empty done and return res as an output however while you are in the stack do something we added root to the stack so at least the stack should be called once except for the fact that this line gets activated and we turned on if we don't do that if we pass this line and we come here we have root in the stack and we need to do the stack we need to do the while loop at least once what happens is that we pop the last element of stack meaning that we pop it and we call it root what do we do now we are looking at our root we add it to the rest right this is what we do whatever node we are looking at right now this is our new root and in a pre-order approach we start the we start from the root we go left and then we go right correct therefore we add root value to the rest now here based on this example we have one added now we're supposed to add two o and then three right here it goes we check the right subtree you may ask you're doing the pre-order why why we are checking the right sub to your right and you're correct we are checking the right subtree first because we are appending to the stack meaning that when you do append right you add you add from this site then appending and then you add a b c you append a b c and then you're going to pop the stack pop something from the stack later what happens that the the right most element gets popped first right and what do you want in a pre-order you want the right most being the left subtree that's why first you check the right subtree which means that it goes down into the stack and then you check the right subtree you check the left subtree excuse me first right then left which means that this gonna be oops something happened excuse me your left this speed is your right and your left this speed is your right and then you're gonna pop c pops first then you're gonna pop c pops first meaning that left pops first you deal meaning that left pops first you deal with that left sub three and then you with that left sub three and then you move on to the right subtree move on to the right subtree so here so here uh you have a right uh basically root uh you have a right uh basically root right gets activated you add this two to right gets activated you add this two to your slack to your stack and then you your slack to your stack and then you come here come here you don't have any left subtree nothing you don't have any left subtree nothing happens then you go happens then you go the second iteration of the while the second iteration of the while now the root is 2 now the root is 2 right basically you right basically you write subtree of your initial goods now write subtree of your initial goods now 2 is going to get added to res 2 is going to get added to res meaning that this is updated to 2 meaning that this is updated to 2 and then you go again for the check do and then you go again for the check do you have you have let me clean this up a little bit so let me clean this up a little bit so that we can communicate more effectively now where are you you're here right you're at two you come into the check do you have a right sub 3 the that sub 3 is not therefore this line doesn't get activated but there is a left sub 3. you add this to the stack let me tell you what is the stack right now stack is what the only thing in the stack is three because initially root was in the stack you popped it here and then you added the right in the second iteration and then you popped it again when you popped it it got added here if you remember and now you're adding three in the last iteration when you come here to pop to basically pop the root and add the root to the res you're looking at three and that's where the tree gets added and then when you're coming here after the third iteration this one doesn't get activated this one doesn't get activated therefore you jump out of the loop the while when you come here return the res which is what we need and that's your code and just to explain a little bit more what you do is that you add the root if there is a root you add the root to the slag to the stack you pop the root add the root to the res check the right check the left if light exists at the right if left exists at the left what happens here right gets added first and then left gets added second and then you want to pop that's what you need for pre-order and that's what you need for pre-order and then finally you turn the rest then finally you turn the rest all right i hope you enjoy it all right i hope you enjoy it let me know if there is anything unclear
2024-03-21 12:45:38
144
https://i.ytimg.com/vi/v…axresdefault.jpg
Preorder Traversal + Leetcode 144
VFskby7lUbw
hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve let's solve burst balloons and this problem has burst balloons and this problem has really earned that category of being a really earned that category of being a hard hard problem so this is going to be another problem so this is going to be another dynamic programming problem and dynamic programming problem and we're going to solve it with the optimal we're going to solve it with the optimal solution which is going to be big o solution which is going to be big o of n cubed time complexity and i believe of n cubed time complexity and i believe big o of n squared memory complexity big o of n squared memory complexity and i'm going to try my best to explain and i'm going to try my best to explain the intuition of this problem and kind the intuition of this problem and kind of walk through my thought process but of walk through my thought process but if your question if your question is if you saw this problem for the first is if you saw this problem for the first time in an interview time in an interview how would you be able to solve it that's how would you be able to solve it that's a good question and honestly i don't a good question and honestly i don't have the answer to that unless your have the answer to that unless your interviewer interviewer gave you a couple of hints that kind of gave you a couple of hints that kind of pointed you in the right pointed you in the right direction because this problem requires direction because this problem requires a couple tricks to get it to work a couple tricks to get it to work efficiently efficiently so the description is pretty simple so the description is pretty simple we're given n balloons we're given n balloons indexed from position zero to position n indexed from position zero to position n minus one minus one each balloon is painted with a each balloon is painted with a particular number on it particular number on it so basically we're given an input array so basically we're given an input array of nums or other words balloons of nums or other words balloons and we're asked to burst all of the and we're asked to burst all of the balloons now when we burst a particular balloons now when we burst a particular balloon balloon i we are going to add to the total we're i we are going to add to the total we're basically going to get a total number of basically going to get a total number of coins from popping that balloon coins from popping that balloon we're going to the total that we're we're going to the total that we're going to get is basically the number going to get is basically the number that was painted on that balloon that was painted on that balloon multiplied by the two adjacent balloons multiplied by the two adjacent balloons to that balloon at that particular time to that balloon at that particular time and of course we might have a balloon and of course we might have a balloon that's on the boundary or on the edge of that's on the boundary or on the edge of our input array so if that's the case our input array so if that's the case for example if i minus 1 or i plus 1 for example if i minus 1 or i plus 1 are out of bounds of the input array are out of bounds of the input array then we're basically going to assume then we're basically going to assume that there's that there's you know a couple balloons with one you know a couple balloons with one painted on them on the edge painted on them on the edge basically there's gonna be some implicit basically there's gonna be some implicit ones so for example if this is our input ones so for example if this is our input array we're assuming there's a one over array we're assuming there's a one over here and there's one over here the here and there's one over here the reason why is let's say we were given an reason why is let's say we were given an input array of one number let's say that input array of one number let's say that value was five right if we pop this value was five right if we pop this we're going to assume that there's ones we're going to assume that there's ones on the edge right so if we pop five what on the edge right so if we pop five what are we going to get we're gonna get five are we going to get we're gonna get five times the right neighbor which is one times the right neighbor which is one times the left neighbor which is one times the left neighbor which is one right so basically these are just right so basically these are just neutral values so the total number of neutral values so the total number of coins we're going to get from a single coins we're going to get from a single balloon balloon is just going to be that value right 5. is just going to be that value right 5. that makes sense that's why we're doing that makes sense that's why we're doing this this so in this example the total number of so in this example the total number of maximum coins we can get is 167 maximum coins we can get is 167 and that is if we first pop this one and that is if we first pop this one value value and then we get three times one times and then we get three times one times five because three and five are the five because three and five are the neighbors neighbors since we pop that next what we're going since we pop that next what we're going to pop is the to pop is the five now since we're popping this five five now since we're popping this five well we need to get its neighbors right well we need to get its neighbors right it's right neighbor is obviously it's right neighbor is obviously a since we popped this one its its left a since we popped this one its its left neighbor now is going to be neighbor now is going to be the 3 that's over here so we're going to the 3 that's over here so we're going to do 3 times 5 times 8 do 3 times 5 times 8 so after we pop the 5 we now have 2 so after we pop the 5 we now have 2 remaining remaining we're going to pop the 3 first and we're going to pop the 3 first and that's going to give us 3 that's going to give us 3 times 8 and the left neighbor of course times 8 and the left neighbor of course remember we remember we talked about the beginning is implied to talked about the beginning is implied to be a 1 so then we're going to get 1 be a 1 so then we're going to get 1 times 3 times 8. times 3 times 8. now the 3 has been popped last one left now the 3 has been popped last one left is just the eight is just the eight right so the neighbors of that right so the neighbors of that implicitly are just one and one so eight implicitly are just one and one so eight times one times one times one times one we add that up to our total we get 167. we add that up to our total we get 167. now now these implicit extra ones on our input these implicit extra ones on our input array for example array for example those are not actually going to be those are not actually going to be popped right so we need to remember that popped right so we need to remember that because obviously if we did pop them because obviously if we did pop them right we pop a one we'd add one to our right we pop a one we'd add one to our total and if we pop the other one we'll total and if we pop the other one we'll add another one but that's not actually add another one but that's not actually going to be the case right we don't want going to be the case right we don't want to pop these extras to pop these extras so even if you can't get the dynamic so even if you can't get the dynamic programming solution at the very least programming solution at the very least we know that there's a brute force we know that there's a brute force approach right we could choose to pop approach right we could choose to pop three first we could choose to pop one three first we could choose to pop one first we could choose to pop first we could choose to pop five we could choose to pop eight right five we could choose to pop eight right and then we could continue and then we could continue down this decision tree right that's the down this decision tree right that's the brute force right brute force right something like a backtracking approach something like a backtracking approach but in that case but in that case obviously we have n choices roughly at obviously we have n choices roughly at each layer each layer and the height of the tree is going to and the height of the tree is going to be n so basically the time complexity is be n so basically the time complexity is going to be something like going to be something like n to the power of n now that's not super n to the power of n now that's not super efficient efficient and in this case we actually can do and in this case we actually can do better but it's not easy to better but it's not easy to arrive to that solution so now let me arrive to that solution so now let me explain a little bit of the thought explain a little bit of the thought process process to get us there and then i'm going to to get us there and then i'm going to jump into the code in this case the code jump into the code in this case the code is actually not too bad once you see is actually not too bad once you see the couple of tricks that we need in the couple of tricks that we need in this problem so we know the brute force this problem so we know the brute force approach but can we identify approach but can we identify any sub-problems your first idea might any sub-problems your first idea might be something like this okay so let's say be something like this okay so let's say i pop i pop the fifth element right we popped this the fifth element right we popped this balloon now we have a new sub problem balloon now we have a new sub problem right we have right we have this entire array minus this value as this entire array minus this value as the sub problem right the sub problem right or for example maybe i popped one now we or for example maybe i popped one now we would get this entire array would get this entire array except the one as a sub problem right except the one as a sub problem right now if i continue popping for example i now if i continue popping for example i pop 1 pop 1 next i pop 8 now we have a different sub next i pop 8 now we have a different sub problem problem so if i keep going like this how many so if i keep going like this how many sub problems are we gonna have well sub problems are we gonna have well basically what we're doing as we pop basically what we're doing as we pop elements we're basically getting every elements we're basically getting every single single subsequence right now how many sub subsequence right now how many sub sequences sequences for an input array are there well for for an input array are there well for each value we could choose to include it each value we could choose to include it or not or not include it right so for each value we include it right so for each value we have two choices two times two have two choices two times two times two right we're basically going to times two right we're basically going to do this for the size of the input array do this for the size of the input array which is let's say n so we're going to which is let's say n so we're going to have 2 to the power of have 2 to the power of n sub sequences so basically what i'm n sub sequences so basically what i'm getting at here getting at here is this is not the correct sub problem is this is not the correct sub problem that we're looking for we need to look that we're looking for we need to look for an even more for an even more simple sub problem because if we have simple sub problem because if we have this many sub problems that's not going this many sub problems that's not going to help us to help us caching something like this is not going caching something like this is not going to make the to make the the solution more efficient we want to the solution more efficient we want to get something like n cubed get something like n cubed and squared et cetera right this is what and squared et cetera right this is what i'm aiming for let's try to see if we i'm aiming for let's try to see if we can get it can get it so let's say i pop the five now is there so let's say i pop the five now is there an even more simple sub problem well we an even more simple sub problem well we notice notice now we actually have two subarrays right now we actually have two subarrays right we have one sub array over here we have one sub array over here and one sub array over here now these and one sub array over here now these sub arrays are contiguous they're not sub arrays are contiguous they're not subsequences that's pretty good subsequences that's pretty good because we know that at most for an because we know that at most for an input array of size input array of size n there could be at most there could be n there could be at most there could be at most at most n squared sub array so that's something n squared sub array so that's something we can work with to make an we can work with to make an efficient solution so now you might efficient solution so now you might think well can i take each of these sub think well can i take each of these sub arrays right arrays right basically by popping this we got basically by popping this we got something like one times five something like one times five times eight now we wanna know times eight now we wanna know independently what the each of these sub independently what the each of these sub arrays arrays could get us like how many maximum coins could get us like how many maximum coins could this subreddit and this subarray could this subreddit and this subarray get us right independently get us right independently but what we're gonna notice is we can't but what we're gonna notice is we can't just look at this subarray independently just look at this subarray independently right because independently a three right because independently a three times one right times one right the max we could get is we first pop the the max we could get is we first pop the one right one right in that case we get one times three and in that case we get one times three and you know the right neighbor is nothing you know the right neighbor is nothing so once we pop that and then we pop this so once we pop that and then we pop this three right then we'll get three right then we'll get three times basically just three by three times basically just three by itself right so itself right so we pop this then we add the second we pop this then we add the second balloon that we pop so we'd get a total balloon that we pop so we'd get a total of six right just independently of six right just independently if we had this sub subarray 3 and 1. but if we had this sub subarray 3 and 1. but we we know that in reality this 3 and 1 is now know that in reality this 3 and 1 is now going to be connected going to be connected to this 8 right and independently what to this 8 right and independently what this 8 would get us this 8 would get us is 8 by itself right because it doesn't is 8 by itself right because it doesn't have any neighbors so in total if we have any neighbors so in total if we took a took a look at both of these independently we'd look at both of these independently we'd get something like 6 plus 8 get something like 6 plus 8 so in total 14 right but in reality so in total 14 right but in reality when we look at 3 1 8 what's the max we when we look at 3 1 8 what's the max we could possibly get in this case could possibly get in this case well we'd pop the 1 first right then well we'd pop the 1 first right then we'd get we'd get three times one times eight now that's three times one times eight now that's 24 that already by itself 24 that already by itself went over the total that we would get if went over the total that we would get if we did these independently so basically we did these independently so basically what i'm getting at is what i'm getting at is we can't break the problem up like this we can't break the problem up like this right right we can't look at these arrays separately we can't look at these arrays separately because in reality we know that they're because in reality we know that they're going to be connected to each other going to be connected to each other okay so that's not going to work now okay so that's not going to work now this is the part where you have to be this is the part where you have to be kind of kind of clever we said what happens if we pop clever we said what happens if we pop this one this one first and then try to do the remaining first and then try to do the remaining array let's reverse our array let's reverse our thinking instead of popping this first thinking instead of popping this first let's say we pop this value last let's say we pop this value last so what happens if we pop this value so what happens if we pop this value last last meaning we pop this entire subarray meaning we pop this entire subarray and before right before we pop this and and before right before we pop this and we pop we pop this entire subarray before we pop this this entire subarray before we pop this what's going to happen then well we know what's going to happen then well we know if this is the last value that we pop if this is the last value that we pop meaning we popped everything here we meaning we popped everything here we popped everything here its left and popped everything here its left and right neighbors right neighbors are both going to be 1 right there's are both going to be 1 right there's going to be a 1 over here and there's going to be a 1 over here and there's going to be a 1 over here so we're going going to be a 1 over here so we're going to get 1 times 5 to get 1 times 5 times 1. but what's the remaining amount times 1. but what's the remaining amount that we that we get from popping these two subarrays now get from popping these two subarrays now because in this case since we're popping because in this case since we're popping this value this value last that means these two subarrays are last that means these two subarrays are never going to be connected to each never going to be connected to each other other ever not at any point because this is ever not at any point because this is being popped being popped last so since these two subarrays are last so since these two subarrays are not going to be connected that means we not going to be connected that means we can now pop them independently so let's can now pop them independently so let's take a look now let's take a look now let's pop this 3-1 independently what's going pop this 3-1 independently what's going to happen to happen well we remember when we pop this well we remember when we pop this independently we're basically going to independently we're basically going to get 1 times 3 plus 3 right get 1 times 3 plus 3 right that's going to total up to 6 once again that's going to total up to 6 once again right but that's not right but that's not actually what we're looking for because actually what we're looking for because remember this remember this sub array is not independent we are it's sub array is not independent we are it's true we're going to pop this before we true we're going to pop this before we pop the five pop the five but we can't just forget about the five but we can't just forget about the five right there is right there is a five right next to this three one so a five right next to this three one so in reality when i pop the one in reality when i pop the one i'm gonna get three times one times five i'm gonna get three times one times five and then when i pop the three because we and then when i pop the three because we know we're not gonna put we're popping know we're not gonna put we're popping this last right so we are popping these this last right so we are popping these two first two first but then when i pop the three i'm gonna but then when i pop the three i'm gonna get one times three get one times three times five right because there's an times five right because there's an implicit one over here implicit one over here so how can i handle that what i'm saying so how can i handle that what i'm saying is is our array hasn't actually changed there our array hasn't actually changed there is is the five still over here but we want to the five still over here but we want to pop all of these elements before we pop pop all of these elements before we pop this five how can i handle that well this five how can i handle that well it's actually not it's actually not too different than what we went over at too different than what we went over at the beginning remember we said that the beginning remember we said that let's say we had a single element in our let's say we had a single element in our input array let's say it's a three right input array let's say it's a three right we're assuming even for this input array we're assuming even for this input array there's gonna be an implicit there's gonna be an implicit one on the left and there's going to be one on the left and there's going to be an implicit one on the right an implicit one on the right these two values are not going to be these two values are not going to be popped when we're popping this popped when we're popping this array but we're still assuming that array but we're still assuming that they're there for that computation that they're there for that computation that we're going to be doing we're going to be doing that's exactly the same rule that we're that's exactly the same rule that we're going to follow going to follow so when we go from up here to down here so when we go from up here to down here right right this is our sub problem so we we have we this is our sub problem so we we have we have identified what the sub problem is have identified what the sub problem is going to be it's going to be this going to be it's going to be this sub array the only thing we have to sub array the only thing we have to remember is just like at the beginning remember is just like at the beginning how there's going to be an how there's going to be an implicit 1 on the left now there's going implicit 1 on the left now there's going to be an to be an implicit 5 on the right so implicit 5 on the right so for the sub array that we're doing the for the sub array that we're doing the left boundary left boundary is going to be at this value the right is going to be at this value the right boundary is going to be boundary is going to be at this value but these values are not at this value but these values are not going to go away going to go away we are going to leave this in the input we are going to leave this in the input array and array and we are going to make sure that we have we are going to make sure that we have an implicit 1 at the beginning of the an implicit 1 at the beginning of the input array input array and similarly when we want to solve this and similarly when we want to solve this subarray we are going to assume that subarray we are going to assume that yeah there's just a single eight right yeah there's just a single eight right so the left boundary is going to be here so the left boundary is going to be here as well as the right boundary both as well as the right boundary both boundaries are going to be here but boundaries are going to be here but we're going to assume that there's an we're going to assume that there's an implicit 1 at the right implicit 1 at the right and this 5 is not going away the 5 is and this 5 is not going away the 5 is going to be here as well we're not going going to be here as well we're not going to pop it because take a look at our to pop it because take a look at our boundary our boundary tells us just to boundary our boundary tells us just to pop pop this subarray before we end up doing this subarray before we end up doing anything else so this is going to stay anything else so this is going to stay here we're not going to pop it here we're not going to pop it but it is going to contribute to the but it is going to contribute to the total number of coins for example when total number of coins for example when we pop eight we pop eight we're gonna get five times eight times we're gonna get five times eight times one that's going to be the total number one that's going to be the total number of coins we get of coins we get once we pop this entire sub-array so once we pop this entire sub-array so using using sub-arrays using this technique where sub-arrays using this technique where for every value we're going to identify for every value we're going to identify well what if we popped this value well what if we popped this value last that allows us to actually get a last that allows us to actually get a sub problem that we can cache now in our sub problem that we can cache now in our cache it's going to be cache it's going to be let's say we call it dp this is our let's say we call it dp this is our cache it's going to be a two dimensional cache it's going to be a two dimensional cache because we are going to be using cache because we are going to be using the left value as the first index and the left value as the first index and the right value as the the right value as the second index these left and right values second index these left and right values are basically just going to tell us are basically just going to tell us what the sub array is from the original what the sub array is from the original array right left is going to be the left array right left is going to be the left boundary boundary r is going to be the right boundary with r is going to be the right boundary with that being said let me just give you a that being said let me just give you a quick quick high level run through of the algorithm high level run through of the algorithm and then we're going to dive into the and then we're going to dive into the code code so we remember in the brute force we so we remember in the brute force we started out with okay what happens if we started out with okay what happens if we pop this first what happens if we pop pop this first what happens if we pop this this first right so that's going to give us a first right so that's going to give us a decision tree now we're going to do it a decision tree now we're going to do it a little bit differently our decision tree little bit differently our decision tree now is going to be what happens if we now is going to be what happens if we pop pop this last what happens if we pop this this last what happens if we pop this last last what happens if we pop this last which what happens if we pop this last which one of those paths one of those paths is going to lead us to the maximum is going to lead us to the maximum number of coins right number of coins right so we are still going to brute force it so we are still going to brute force it kind of we are going to have that exact kind of we are going to have that exact same decision tree same decision tree only thing is we're going to use a cache only thing is we're going to use a cache we're going to take that sub problem and we're going to take that sub problem and cache them so for example let's say we cache them so for example let's say we pop this value last what am i going to pop this value last what am i going to do do and we actually are going to modify the and we actually are going to modify the input array so we are gonna add that input array so we are gonna add that implicit one at the beginning and at the implicit one at the beginning and at the end end but our boundary is gonna be left is but our boundary is gonna be left is gonna be from here and right is gonna be gonna be from here and right is gonna be from here that's ultimately from here that's ultimately these are the values that we're actually these are the values that we're actually gonna be popping we're not actually gonna be popping we're not actually gonna be popping these gonna be popping these again the brute force what happens if we again the brute force what happens if we pop this last pop this last if we pop this last our left subarray if we pop this last our left subarray becomes becomes empty right there's nothing there in the empty right there's nothing there in the left sub-array left sub-array but our right sub-array is going to have but our right sub-array is going to have this entire portion right this entire portion right so since currently our boundary our left so since currently our boundary our left boundaries here in our right boundaries boundaries here in our right boundaries here if we pop here if we pop this value last this is what our total this value last this is what our total is gonna be we're gonna get is gonna be we're gonna get so if we pop this last we know it's so if we pop this last we know it's gonna gonna we're gonna end up popping everything we're gonna end up popping everything here before that right so when we pop here before that right so when we pop this value we're gonna get this value we're gonna get three times one times one right so what three times one times one right so what i'm gonna say is three i'm gonna say is three times nums of right which is over here times nums of right which is over here plus plus one and nums of left which is over here one and nums of left which is over here minus one that's going to give us once minus one that's going to give us once we pop this we pop this plus we want the remaining number of plus we want the remaining number of coins that we get coins that we get from popping the remaining portion of from popping the remaining portion of the left sub array we see that there's the left sub array we see that there's nothing here right nothing here right remember we're not actually popping this remember we're not actually popping this value there's no other values in between value there's no other values in between so there is no left sub array what about so there is no left sub array what about the right sub array we're going to take the right sub array we're going to take our left pointer shift it by our left pointer shift it by one that's going to put left over here one that's going to put left over here so the right sub array is going to be so the right sub array is going to be all of these elements right so you can all of these elements right so you can see we're going to get that total amount see we're going to get that total amount computed from our dp computed from our dp right we're going to get it from our dp right we're going to get it from our dp if that's already been computed as a sub if that's already been computed as a sub problem if it hasn't been computed then problem if it hasn't been computed then we're just going to do that we're just going to do that brute force depth first search passing brute force depth first search passing in these same parameters right in these same parameters right l plus one and right now let's look at l plus one and right now let's look at it for a more general it for a more general case if we were popping let's say a case if we were popping let's say a middle value as the last value where we middle value as the last value where we actually do have both a left sub array actually do have both a left sub array and a right sub array what's the and a right sub array what's the equation going to look like then equation going to look like then so we were looking at if we popped this so we were looking at if we popped this value last next we're going to look at value last next we're going to look at if we pop this value if we pop this value last we're also then going to look at last we're also then going to look at this and this right that's basically the this and this right that's basically the brute force right so basically we're brute force right so basically we're going to have an i right it's going to going to have an i right it's going to start here start here it's going to run all the way through it's going to run all the way through the end of the input array but now if we the end of the input array but now if we pop pop this last we know that if if this was this last we know that if if this was popped last we'd end up popping all of popped last we'd end up popping all of this first and we'd pop this first so this first and we'd pop this first so then once we popped this its left would then once we popped this its left would be the one be the one its right would be the one right so its right would be the one right so that's where we're getting this from that's where we're getting this from right right r plus one's here left minus one is over r plus one's here left minus one is over here here multiplied by the value at index i which multiplied by the value at index i which is one right is one right but then what's our right sub array but then what's our right sub array going to be clearly this is what the going to be clearly this is what the right sub array remaining sub array is right sub array remaining sub array is right how much could we get from right how much could we get from doing that well again in our dp or if doing that well again in our dp or if it's not already computed in our dp it's not already computed in our dp we're basically going to call our depth we're basically going to call our depth search clearly you can see that the left search clearly you can see that the left boundary now is i boundary now is i plus one right basically we're taking plus one right basically we're taking this i moving it over here our right this i moving it over here our right boundary remains boundary remains unchanged right this is the sub array unchanged right this is the sub array that's what i'm saying here that's what i'm saying here what about our left sub array over here what about our left sub array over here well the left boundary didn't change well the left boundary didn't change but the right boundary was decremented but the right boundary was decremented by one that makes sense right by one that makes sense right so that's basically the idea now my so that's basically the idea now my question is we know why the memory question is we know why the memory complexity is big o of n squared right complexity is big o of n squared right the the cache is basically going to be from cache is basically going to be from every single subarray right every single subarray right and it's two dimensional so that makes and it's two dimensional so that makes sense i think why it's sense i think why it's the memory is n squared but why is the the memory is n squared but why is the time complexity big o time complexity big o n cubed well we know we're going to be n cubed well we know we're going to be breaking this problem down breaking this problem down into sub problems of every single into sub problems of every single subarray we know that there's subarray we know that there's n squared number of sub arrays right so n squared number of sub arrays right so for once we have a sub array right like for once we have a sub array right like let's consider the entire input array let's consider the entire input array was a sub array right was a sub array right we know that for every subway we're we know that for every subway we're basically going to be iterating through basically going to be iterating through every value right this is the first this every value right this is the first this is the second this is the is the second this is the and so on and so on right and and so on and so on right and considering if this was the last value considering if this was the last value popped so popped so it's basically taking the total number it's basically taking the total number of sub arrays which we know is n squared of sub arrays which we know is n squared and multiplying it by another n because and multiplying it by another n because we're having to iterate through every we're having to iterate through every single single value for a given subarray with that value for a given subarray with that being said let's jump into the code once being said let's jump into the code once you actually know these tricks and you actually know these tricks and especially once you know especially once you know this formula the algorithm is actually this formula the algorithm is actually pretty easy with pretty easy with recursion so like i mentioned we are recursion so like i mentioned we are going to be going to be updating the input array we're basically updating the input array we're basically going to be adding a 1 at the beginning going to be adding a 1 at the beginning and then adding a 1 at the end we're and then adding a 1 at the end we're also going to be having also going to be having a cache i'm going to call it dp because a cache i'm going to call it dp because it's short and then we can start with it's short and then we can start with our our depth first search function so let's depth first search function so let's define it we know that we're just going define it we know that we're just going to have left to have left and right boundaries right so basically and right boundaries right so basically left and right are going to be indices left and right are going to be indices of the input array but let's call that of the input array but let's call that depth first search function we know depth first search function we know we're just going to be end up calling it we're just going to be end up calling it and then returning the results so let's and then returning the results so let's do that before we actually define the do that before we actually define the function function now what am i going to pass in as a left now what am i going to pass in as a left and right boundary zero and right boundary zero and you know the last index no right and you know the last index no right because we don't want to actually because we don't want to actually include include this one and we don't want to include this one and we don't want to include this one so i'm going to be passing in this one so i'm going to be passing in zero plus one which is one and basically zero plus one which is one and basically passing in passing in the length of the entire empire numbs the length of the entire empire numbs minus two because we know minus two because we know this minus one would give us the last this minus one would give us the last value minus 2 is going to be 1 value minus 2 is going to be 1 less than that so because remember we're less than that so because remember we're not actually popping these not actually popping these and these okay so now what are actually and these okay so now what are actually the base cases for this algorithm well the base cases for this algorithm well if left equaled right that means we have if left equaled right that means we have only one only one balloon left to pop so that's actually balloon left to pop so that's actually okay but if left okay but if left past the right pointer so if left became past the right pointer so if left became greater than right greater than right that's when we know we've ran out and that's when we know we've ran out and that's when we know we're gonna that's when we know we're gonna we're gonna return zero meaning there's we're gonna return zero meaning there's nothing left to pop nothing left to pop otherwise maybe we've already computed otherwise maybe we've already computed this before and it's already in our this before and it's already in our cache cache right this left and right pair is right this left and right pair is already in dp in that case we're just already in dp in that case we're just going to return dp going to return dp of left and right otherwise of left and right otherwise we know that it hasn't been computed so we know that it hasn't been computed so now it's our time to actually compute it now it's our time to actually compute it so let's set it initially to zero so let's set it initially to zero and now we're going to determine what is and now we're going to determine what is the max number of coins we could get the max number of coins we could get for this pair so remember we're going to for this pair so remember we're going to be iterating through every i be iterating through every i considering if at index i that balloon considering if at index i that balloon was the last balloon we popped so let's was the last balloon we popped so let's go through every index from go through every index from left all the way to right and let's left all the way to right and let's compute the number of coins compute the number of coins we could get from that so we know that we could get from that so we know that if if this numbs of i was popped last we'd get this numbs of i was popped last we'd get numbs numbs of i multiplied by nums of i multiplied by nums of right plus 1 multiplied of right plus 1 multiplied numbs of left minus one right and now to numbs of left minus one right and now to coins we're going to coins we're going to add the additional coins that we would add the additional coins that we would get from the left and right get from the left and right sub arrays right so we're going to be sub arrays right so we're going to be calling our depth first search function calling our depth first search function the left boundary stays the same and the left boundary stays the same and we're gonna do i we're gonna do i minus one and we're also going to be minus one and we're also going to be calling it for the right subarray which calling it for the right subarray which we know we can get we know we can get with i plus one as a left boundary and with i plus one as a left boundary and our right boundary is going to stay the our right boundary is going to stay the same so now we've computed the total same so now we've computed the total number of coins right it makes sense why number of coins right it makes sense why we're doing this we're doing this and then calling our debt for search and then calling our debt for search function so now we can potentially function so now we can potentially update the result which we know we're update the result which we know we're storing here in dp storing here in dp of left and right so we're going to of left and right so we're going to update it to the max of potentially what update it to the max of potentially what it already it already is and the max of what we just computed is and the max of what we just computed the total number of coins that we just the total number of coins that we just computed and so we're basically going to computed and so we're basically going to be running through the entire loop be running through the entire loop doing that i hope that this kind of doing that i hope that this kind of makes it a little more obvious of why makes it a little more obvious of why this is n cubed we know that this debt this is n cubed we know that this debt for search function for search function the maximum possible number of ways it the maximum possible number of ways it could be called is could be called is n squared right every pair of the left n squared right every pair of the left and right indices could be n squared and right indices could be n squared times times e and then if we actually if it's e and then if we actually if it's already been cached then we're going to already been cached then we're going to return it in big o return it in big o of one time if it hasn't been cached of one time if it hasn't been cached meaning it's the first time we're meaning it's the first time we're computing this computing this we're going to have to run through a we're going to have to run through a linear time loop linear time loop and for each of these pairs we are going and for each of these pairs we are going to have to run through a loop at least to have to run through a loop at least once so that's what's going to give us once so that's what's going to give us the n cubed the n cubed time complexity but yeah once this has time complexity but yeah once this has been computed we know been computed we know you know we can just go ahead and return you know we can just go ahead and return it from this recursive function it from this recursive function and that is the entire thing so and that is the entire thing so you know we defined a function inside of you know we defined a function inside of a function but once you know a function but once you know you know the trick which is not so you know the trick which is not so obvious we do have to do this obvious we do have to do this and then we do have that relationship of and then we do have that relationship of you know we're popping this you know we're popping this this balloon last it's not super this balloon last it's not super intuitive but once you do have it intuitive but once you do have it hopefully your interviewer gives you hopefully your interviewer gives you that hint that hint but and if you do get that the code is but and if you do get that the code is actually not too bad as you can see when actually not too bad as you can see when you do you do recursion so i hope that this was recursion so i hope that this was helpful if it was helpful if it was please like and subscribe it supports please like and subscribe it supports the channel a lot and i'll hopefully the channel a lot and i'll hopefully see you pretty soon thanks for watching
2024-03-24 10:13:57
312
https://i.ytimg.com/vi/V…axresdefault.jpg
Burst Baloons - Dynamic Programming - Leetcode 312 - Python
hWBeywkKCRc
hey what's up guys this is chung here again so actually i this is chung here again so actually i want to briefly talk about want to briefly talk about today's daily challenge problem which is today's daily challenge problem which is number number 74 search or 2d matrix 74 search or 2d matrix you know so i think it's a okay it's a medium problem right so basically you're given like uh examples of m times n matrix right a 2d matrix and this matrix has the following properties okay so integers in each row are sorted from left to right and the first integer of each row is greater than the last than the last integer of the preview the last integer of the previous row so basically you know so this is like a sorted sorted string right but in instead of 1d it's a 2d so 7 is greater than 1 10 is greater than 7 and then and then basically from here here and here and it's it's just like a sorted string sorted list but instead it's it's being converted to a 2d here so then it asks you just do a search right to find like a value so it's just like it's obvious it's going to be a binary search right i mean the only difference with the 1d binder search is that we just need to somehow convert that that's uh that 2d coordinates into that 1d 1d index right so here we have a two we have x and y but in the binary search we only have one one one one value or one index okay so i mean we just need to uh to know that right i mean let's do uh so here's how we do it right okay so the the uh length of the uh matrix zero right so that's m and n and uh of course so the left is zero the left is zero okay and the right so how do we convert that so to convert that we just do at m times n minus one right so that's the uh that's the total number of the index right for this binary search okay and and other than that it's just like the the the regular binary search template in this case we need to do a left equal less than or equal to write because it could be uh the left and right pointer will end up at one at the middle right so here here here so at the middle right so here here here so the left here the left here and left and right 11 right so this is left and this is right and yeah it could be uh you know and yeah it could be uh you know we have to move somehow left and to the we have to move somehow left and to the right so that we know the uh right so that we know the uh we can cover all the other cases right we can cover all the other cases right even though even though the left and right are on the same same the left and right are on the same same position we still need to check if this position we still need to check if this position position has the uh has the answer we need okay has the uh has the answer we need okay basically if we do a left less than or basically if we do a left less than or less than right so we'll be missing the less than right so we'll be missing the case case or where left is equal to right okay so or where left is equal to right okay so here here middle equals to left plus middle equals to left plus right minus left divided by two right minus left divided by two right so and you know like i said this is like a a 1d index but in order to check the values right we have to convert this one in back to the uh to the to the x and y right so how do we do that so we have i and j right so the i and j basically the i is equal to the middle basically the i is equal to the middle we uh we do a we uh we do a divided right we do it divided by by n divided right we do it divided by by n that's how we convert it to i that's how we convert it to i and j is like the middle and j is like the middle uh do a mod mod by uh do a mod mod by n okay so that's how we n okay so that's how we convert this 1d convert this 1d value into this 2d coordinates okay and value into this 2d coordinates okay and then then we simply check the uh if the it's smaller than the target right and it's smaller than the target right and then we know okay then we know okay it's smaller we need to move this left it's smaller we need to move this left to the uh to the uh middle class one okay how's if right middle class one okay how's if right house if house if matrix inj matrix inj is greater than target then we is greater than target then we we know we do a right equals the middle we know we do a right equals the middle minus one okay else else we simply minus one okay else else we simply return true here right because we have return true here right because we have find that find that the answer and if we didn't find it in the answer and if we didn't find it in the while loop we the while loop we simply return false here you know so simply return false here you know so here we don't do a plus one because here we don't do a plus one because actually we're actually we're actually we're looking for a number actually we're looking for a number that's in this that's in this if if we didn't find it we we do a left if if we didn't find it we we do a left plot we do a left equals to middle plus plot we do a left equals to middle plus one so one so there won't be a any uh infinite loops there won't be a any uh infinite loops issue here so that's why issue here so that's why we just simply do a right minus left we just simply do a right minus left okay yeah so i think that that that's it right so oh yeah so of course oh yeah so of course so if not matrix right if there's no so if not matrix right if there's no matrix we simply return matrix we simply return fast okay cool it's accepted i mean pretty cool it's accepted i mean pretty straightforward right i mean the uh straightforward right i mean the uh the time complexity of course it's the time complexity of course it's obvious obvious time complexity is log log time complexity is log log m times times n right that's the m times times n right that's the that's the time complexity cool i think yeah that that's all for this problem yeah the only the only difference is the uh just convert the uh conver convert this 2d range to the 1d a 2d like m and n to this 1d left and right range and then after that we you when we when we have the middle value we have to use the same the reverse conversion to get the other 2d coordinates so that we can compare the value with our target okay other than that nothing too special cool i think that's it for this problem uh thank you so much for watching this video guys stay tuned
2024-03-20 11:37:44
74
https://i.ytimg.com/vi/h…axresdefault.jpg
LeetCode 74. Search a 2D Matrix
29y2dJ937ik
of string made only from lower lowercase letters made only from lower lowercase letters return a list of all characters that return a list of all characters that shows up shows up in all strings within the list including in all strings within the list including duplicates duplicates for example if a character occurs three for example if a character occurs three times you know all strings but times you know all strings but not four times you need to include the not four times you need to include the character three times in the final character three times in the final answer you may return the answer in any answer you may return the answer in any order order so string overrate uh string operates at so string overrate uh string operates at tonight [Music] frequency equal to not equal to main frequency of um c minus a not a gallon [Music] current equal to current frequency current equal to current frequency uh eq of the current frequency equal to uh eq of the current frequency equal to new another four char another four char actually four ain't j equals to zero actually four ain't j equals to zero j is less than um twenty six j is less than um twenty six twenty six clicks have no uh iteration twenty six clicks have no uh iteration another mean frequency of zero mean frequency of zero high with uh current frequency current high with uh current frequency current frequency frequency of j minus now there we go okay mean frequency of i results that add string greater legal so results that add string greater legal so string that string that value string the value of know [Music] thank you
2024-03-25 13:03:19
1,002
https://i.ytimg.com/vi/2…ik/hqdefault.jpg
Find Common Characters LeetCode Solution
fhruChRgoSc
so so so [Music] [Music] so [Music] [Music] so so [Music] so so [Applause] [Applause] [Music] [Music] [Applause] [Applause] [Music] [Music] [Applause] [Applause] [Music] [Music] [Applause] [Music] so [Music] [Music] [Music] [Music] so so [Music] so so so [Applause] [Music] [Music] so so so [Applause] [Music] [Applause] [Music] [Applause] [Music] [Applause] [Music] [Music] so so so [Music] [Music] [Music] so so [Music] so so [Applause] so [Music] [Music] [Applause] [Applause] [Music] [Music] [Applause] [Applause] [Music] [Music] [Applause] [Applause] [Music] [Music] [Applause] [Music] so so [Music] [Music] so [Music] [Music] [Music] [Music] so [Music] so so
2024-03-21 12:10:05
741
https://i.ytimg.com/vi/f…axresdefault.jpg
Leetcode 741. Cherry Pickup
zbImSGug-oc
what's gonna buddy welcome to leak a passing solution 252 many rooms so if a passing solution 252 many rooms so if a new here will come be sure to check my new here will come be sure to check my personal website nanny Plata calm there personal website nanny Plata calm there are a lot of coding projects you know so are a lot of coding projects you know so articles that might be helpful to you articles that might be helpful to you alright so my first of all my poetry alright so my first of all my poetry since I do not have a premium account so since I do not have a premium account so I have to refer to others on website to I have to refer to others on website to see the questions so this question is see the questions so this question is very common in our own life like for very common in our own life like for example if you were going to schedule a example if you were going to schedule a meeting with your friends or your meeting with your friends or your colleagues then you might probably come colleagues then you might probably come up with this kind of you know issue in up with this kind of you know issue in our real life all right so what are this our real life all right so what are this question so this question is basically question so this question is basically to ask by giving you start and end times to ask by giving you start and end times for a meeting for a meeting we just like this determine if a person we just like this determine if a person could attend or meeting us or not and could attend or meeting us or not and the format's are like in the least so the format's are like in the least so for example the first meeting start it for example the first meeting start it starts at zero and and the 3d and second starts at zero and and the 3d and second meeting starts five and end at 10 so the meeting starts five and end at 10 so the return type is true of course so what return type is true of course so what should we do and what is the algorithm should we do and what is the algorithm for this question so when we are given a for this question so when we are given a schedule of meetings so for example I schedule of meetings so for example I got a meeting like ah so this is a got a meeting like ah so this is a meeting and this is that time so this is meeting and this is that time so this is a short so here is a strong time and a short so here is a strong time and this is the end time and I got another this is the end time and I got another meeting like here and I got a third meeting like here and I got a third meeting like here so the first thing meeting like here so the first thing that we need to do is restored the input that we need to do is restored the input and we are going to have this kind of and we are going to have this kind of you know meetings in schedule like by you know meetings in schedule like by sorting the first element which is the sorting the first element which is the start time for all the meetings and start time for all the meetings and that's we're going to do is regularly that's we're going to do is regularly check for each meeting the starting time check for each meeting the starting time with their previous and inclined so as with their previous and inclined so as long as the starting time is its what long as the starting time is its what the value is larger than the previous the value is larger than the previous ending time then ending time then the person can attend both meetings and the person can attend both meetings and Sam for all the following of meetings Sam for all the following of meetings so as long as all the meetings for each so as long as all the meetings for each meeting their starting time is larger or meeting their starting time is larger or equal to the previous meeting time then equal to the previous meeting time then the return should be true otherwise it'd the return should be true otherwise it'd be force which is in the third meeting be force which is in the third meeting here this story ends on is smaller than here this story ends on is smaller than the previous and it's on and therefore the previous and it's on and therefore in that case you should return false so in that case you should return false so let's see how to realize this in the car let's see how to realize this in the car in Python so here how define the in Python so here how define the functions name as meeting room here and functions name as meeting room here and I also initialize the function so the I also initialize the function so the first thing I'm gonna do is I'm going to first thing I'm gonna do is I'm going to sort my of intervals by the first sort my of intervals by the first element which is 0 5 or 15 alright so element which is 0 5 or 15 alright so next thing I'm gonna do is I'm going to next thing I'm gonna do is I'm going to compare to compare on the yeah on the compare to compare on the yeah on the meetings with the previous are ending meetings with the previous are ending all right and probably here you can have all right and probably here you can have in interval not or meeting them might be in interval not or meeting them might be very length of the intervals so for very length of the intervals so for ranch one two now the reason I ups my ranch one two now the reason I ups my the reason I started from a 1 is because the reason I started from a 1 is because the first meeting I don't need to the first meeting I don't need to compare it right and just gently compare compare it right and just gently compare the start time with the previous the start time with the previous meetings on any time so here if meetings on any time so here if intervals I and if this value is smaller intervals I and if this value is smaller than the previous one from this one's than the previous one from this one's any time then it will just written post any time then it will just written post otherwise it will just return true all otherwise it will just return true all right so let's run it in terminal so right so let's run it in terminal so oops I think the third line so we oops I think the third line so we restored you you don't have the punic restored you you don't have the punic assigned but if it is sorted then you assigned but if it is sorted then you have to just run again and it returns to have to just run again and it returns to false and that is what we are expecting false and that is what we are expecting all right I think this is the end for all right I think this is the end for this tutorial if you have any questions this tutorial if you have any questions comments please feel free to leave comments please feel free to leave comments below otherwise I will see you comments below otherwise I will see you in the next tutorial in the next tutorial media room - thank you very much and media room - thank you very much and have a nice day
2024-03-22 12:06:11
252
https://i.ytimg.com/vi_w…xresdefault.webp
Python Leetcode Solution 252: Meeting Rooms
H6qmQJZGMSY
all right what's up guys we're doing binary zigzag level binary zigzag level traversal top interview questions medium traversal top interview questions medium set binary tree question number two set binary tree question number two so given the root binary tree return the so given the root binary tree return the zigzag level or traversal with nodes zigzag level or traversal with nodes values so for the first level you want values so for the first level you want to go left to right to go left to right then right to left and left to right all then right to left and left to right all right right and over here they just have some edge and over here they just have some edge cases so let's look at a cases so let's look at a example that i set up for you guys so example that i set up for you guys so for this question let me just hide all for this question let me just hide all of that of that you want to go left to right a then you want to go left to right a then right to left c b right to left c b then left to right again dfg and ih and then left to right again dfg and ih and that's exactly what that's exactly what lev uh the zigzag level traversal is so lev uh the zigzag level traversal is so you might be thinking you might be thinking what's a level word traversal because what's a level word traversal because they say zigzag level or traversal they say zigzag level or traversal level or traversal is you'll just go level or traversal is you'll just go left to right so over here you go a b left to right so over here you go a b c d f g h i you might be wondering all c d f g h i you might be wondering all right how do i get a zigzag from a level right how do i get a zigzag from a level or traversal and it's pretty obvious or traversal and it's pretty obvious you just reverse the list i go right to you just reverse the list i go right to left so they go left to right right left so they go left to right right easy so how do i get a level or easy so how do i get a level or traversal traversal that's the next question that comes up that's the next question that comes up so so the way i see there's three steps to the way i see there's three steps to level reversal so level reversal so you got to get the nodes that are stored you got to get the nodes that are stored on a level in a data structure let me on a level in a data structure let me just just delete the zigzag delete the zigzag so you get a right and then you want to so you get a right and then you want to add its children add its children uh to the data structure or you want to uh to the data structure or you want to add a to list first for that row add a to list first for that row so list just for that row do you want so list just for that row do you want children to data structure and then children to data structure and then repeat the process just like that rinse repeat the process just like that rinse and repeat right and repeat right but you might be wondering what's the but you might be wondering what's the ideal data structure to use ideal data structure to use so for one value it really doesn't so for one value it really doesn't matter you know you use a stack or q matter you know you use a stack or q it's only one value it doesn't affect it's only one value it doesn't affect the flow but when you have two values is the flow but when you have two values is what it's one that's really matters so what it's one that's really matters so you have a and you have b you have a and you have b and c to some data structure i'll let and c to some data structure i'll let you know you guys will figure it out you know you guys will figure it out with me with me so for b you add in you add it to the so for b you add in you add it to the list and you add in d list and you add in d and e and then you want to access c so and e and then you want to access c so let's just let's just give a little example here we have a q and we have some list so initially our q has a right and you want pop a l as oh i give it away it's a q but basically i'll show you how this works so you add in a to list then you have b and c in your q you want to add in b add its children to q which are d and e and then you all pop out c and add its children to q which are f and g but the reason we use the q is because look how we act we're able to access b and c first because they're first in first out that's obviously a q and you might be wondering both how do i know when to stop like why would i just stop at bc what if i just kept on going and the secret of that is you look at how many values how many nodes are in the cube before you start popping out and adding a new value that way you know how many nodes you have to look at for that level so in this level it's just two so this level you'd only look at four values but the q could get bigger like pop out d at its children which are just h and then you pop out e then f pop in his children which is then f pop in his children which is i and then i and then [Music] [Music] pop out g and add in its children which doesn't have any but and you stop here because you only you knew from before there's only four values in this uh level and then you just make another while loop in your while loop you create a new list for that row you just add in convincing repeat just add in all the values to the list add the new values to the queue and with that we have the solution so let me quickly talk about space and time complexity space complexity worst case we're just storing one value uh it's the node in a q that's all of n time complexity on the other hand this time the time complexity is one you gotta think about the traversal and reversing the list so the reversal is oven right you traverse through the entire endnotes but the um reversing it may take it may increase that to low and square i'm going to show you guys a way to keep it old and um basically the way is the way you can add to the list is you can add to the front of the list or you can add that back of those so if you continually add to back the list you're basically or adding them in reverse order so let me show you real quick so d e f g right say you wanted to reverse this and you want to add it to a reverse list so you always add it to your front that's the secret so first you add in d then you add an e then you add in f and then you add in g and as you're always uh adding them to the front the last values in the front and the first values in the last and that's basically the idea on how to keep this solution all in space on time to really impress your interviewer so now let's start coding up the solution uh first thing we need return array and first check we want to do is we want and first check we want to do is we want to check if the root value that we're to check if the root value that we're looking at looking at is null because then you just return the is null because then you just return the empty list and empty list and we need a starting note to go through we need a starting note to go through all the children in the uh all the children in the uh tree right because we're just adding tree right because we're just adding into a cube but if there's no starting into a cube but if there's no starting no if it's no no if it's no then we can't really do anything so we then we can't really do anything so we just return just return an empty list great otherwise you want an empty list great otherwise you want to add it to the two so q to add it to the two so q dot add roots dot add roots and you want to do a while loop while and you want to do a while loop while the q the q is not empty is not empty first things first add a list of first things first add a list of integer for that row integer for that row we'll call it kero all right now uh you want to look at the length of the cube before you add or push anything out of this so int row length is equal to q dot size all right cool and let's make a value to store the current note that we're perfect so you want to make a for loop perfect so you want to make a for loop only through the only through the values in that row which so for values in that row which so for and isaac will do zero and isaac will do zero eyes less than rolling plus plus a new keyboard all right what you want to do is first thing curve is equal to q dot pull that's how you get the front of the queue first and first out then you want to add but we got do we'll think about but we got do we'll think about uh zigzag in a second then you want to uh zigzag in a second then you want to add the left and right children if they add the left and right children if they exist so if exist so if cur dot left is not equal to null cur dot left is not equal to null then q dot add then q dot add curve out left and do the same thing for curve out left and do the same thing for the right all right that's cool and what we want to do is we want to add that current row and at the end you wanna return and at the end you wanna return our return array that looks good and our return array that looks good and this is right now it's just a level this is right now it's just a level order traversal how we're going to make order traversal how we're going to make it a it a zigzag level or traversal is we're going zigzag level or traversal is we're going to add a boolean to add a boolean to check if we should reverse the row to check if we should reverse the row and initially it's equal to false right and initially it's equal to false right first one you don't first one you don't uh reverse secondly you do and every uh reverse secondly you do and every time time you wanna flip the value so reverse you wanna flip the value so reverse row is equal to not reverse row is equal to not reverse row all right and row all right and we've got colon there and the way you do we've got colon there and the way you do is is i showed you before so if you reverse i showed you before so if you reverse row you want to add it to front so for lift and java they have this index and value so you can define the index to be zero it's that way you can add to the front of the list otherwise you can just add to the back so not uh indicating an index just automatically adds a back to list all right that looks good let's try running it um okay dang honestly that's a reason i honestly that's a reason i don't like java don't like java i think i might just switch oh yeah i think i might just switch oh yeah i called it her everywhere else except i called it her everywhere else except for for the declaration so i'm going to be the declaration so i'm going to be switching to seatbelts for my later switching to seatbelts for my later videos videos i'm still going to have java solutions i'm still going to have java solutions up on the github page it's pretty much up on the github page it's pretty much going to be the same going to be the same so solution was accepted but i really so solution was accepted but i really want to try learning c want to try learning c plus and i think it'd be a good plus and i think it'd be a good opportunity don't worry though all the opportunity don't worry though all the solutions will still be posted in java solutions will still be posted in java on the github and the explanations are on the github and the explanations are pretty much universal pretty much universal so thank you guys so much for watching so thank you guys so much for watching uh leave a like comment subscribe uh leave a like comment subscribe give me some suggestions on how i make give me some suggestions on how i make these videos better i'll see you guys in these videos better i'll see you guys in the next one the next one and that's about it codes in the github and that's about it codes in the github description so check that out description so check that out uh peace out
2024-03-21 10:16:02
103
https://i.ytimg.com/vi/H…axresdefault.jpg
Binary Tree Zigzag Level Order Traversal - Leetcode 103
9nJkhX2ABls
hello everyone welcome back here is vanamsin and we are back with another vanamsin and we are back with another exciting SQL program from lisco today we exciting SQL program from lisco today we are looking at the problem average time are looking at the problem average time of process per machine so let's get of process per machine so let's get right into it uh here is the problem right into it uh here is the problem statement we have a table code activity statement we have a table code activity that represents user activity on a that represents user activity on a factory website this table has following factory website this table has following columns machine ID process ID activity columns machine ID process ID activity type and time step the machine ID is the type and time step the machine ID is the ID of the machine process ID is the ID ID of the machine process ID is the ID of process running on the machine of process running on the machine activity type is an Anum of the type activity type is an Anum of the type start and end and timestamp is a float start and end and timestamp is a float representing the current time in s representing the current time in s seconds seconds start means that machine start the start means that machine start the process at the given time step and end process at the given time step and end that machine ended the process at the that machine ended the process at the given timestamp so now task is to write given timestamp so now task is to write a SQL query to find the average time a SQL query to find the average time each machine takes to complete approcess each machine takes to complete approcess the time to complete a process is the the time to complete a process is the end time stamp minutes the start end time stamp minutes the start timestamp the average time is calculated timestamp the average time is calculated by the total time to complete every by the total time to complete every process on the machine divided by the process on the machine divided by the number of processes that were run number of processes that were run so the resulting table should have the so the resulting table should have the machine ID along with the average time machine ID along with the average time as processing time which should be as processing time which should be rounded to three decimal places so let's rounded to three decimal places so let's break this problem down we need to break this problem down we need to calculate the processing time for each calculate the processing time for each machine which is the end timestamp minus machine which is the end timestamp minus the start timestamp and we do this for the start timestamp and we do this for each process each process and add them up and then divide by the and add them up and then divide by the number of process to get the average so number of process to get the average so let's start by joining the activity let's start by joining the activity table with itself on the machine ID and table with itself on the machine ID and process ID but we will make sure one process ID but we will make sure one side of the join has activity type start side of the join has activity type start and the other end and this will give us and the other end and this will give us pair of start and end time for the pair of start and end time for the process process and using a self-jorn to get the start and using a self-jorn to get the start and at end time for each process on the and at end time for each process on the same row we will use allies S and E for same row we will use allies S and E for the stars and activity type respectively the stars and activity type respectively and that we have the starts and end and that we have the starts and end times on the same row we can calculate times on the same row we can calculate then the process time for each process then the process time for each process by subtracting the start timestamp from by subtracting the start timestamp from the end timestamp the end timestamp and finally adding a new column to our and finally adding a new column to our SLX statement to calculate the process SLX statement to calculate the process time for each process so and yeah time for each process so and yeah finally we need to calculate the average finally we need to calculate the average process time for each machine process time for each machine we can do this with a group by close on we can do this with a group by close on machine ID using the average function on machine ID using the average function on the process time so uh let's Implement the process time so uh let's Implement our query so our query so select as machine ID as machine select as machine ID as machine ID and round average ID and round average timestamp minus s times temp timestamp minus s times temp 3 as 3 as process process time time and from activity as join activity and from activity as join activity e e on as machine ID is a machine ID and as on as machine ID is a machine ID and as process ID equal process ID equal process ID process ID and as activity type equal and as activity type equal start and start and activity type equals and activity type equals and Group by Group by s machine ID s machine ID and yeah here you have it so finally we and yeah here you have it so finally we are using Group by to cows to for a are using Group by to cows to for a machine ID to get group for each machine machine ID to get group for each machine then we are applying uh average on the then we are applying uh average on the beginning of our query to return the beginning of our query to return the process time column to get the average process time column to get the average process time for each machine so let's process time for each machine so let's run it and check if it's working for run it and check if it's working for test cases test cases so so yes so we have machine ID one yes so we have machine ID one zero and two so all machines and we have zero and two so all machines and we have successfully calculated successfully calculated War every War every machine machine ID so here are machine ID and as you can ID so here are machine ID and as you can see so we have see so we have three machines but some have multiple three machines but some have multiple processes so we need to processes so we need to join uh all of this join uh all of this machine as average and also calculate machine as average and also calculate for the particular process that has for the particular process that has started and ended so they are averaged started and ended so they are averaged so for example yeah we have here machine so for example yeah we have here machine ID 0 1 ID 0 1 and then Machine 2 and obviously we and then Machine 2 and obviously we start with uh yeah start with uh yeah end time minus starting time and same end time minus starting time and same for the other process on the same for the other process on the same machine ID so let's run it for unsynced machine ID so let's run it for unsynced cases and see if our query works cases and see if our query works so so hopefully it does it's a bit bigger hopefully it does it's a bit bigger query yeah so it's working and yeah it's query yeah so it's working and yeah it's five percent so uh but uh result is five percent so uh but uh result is correct and correct and there you have it working query there you have it working query and yeah the output is correct maybe the and yeah the output is correct maybe the query is a bit long but the result is a query is a bit long but the result is a list of machine IDs along with their list of machine IDs along with their average processing time around into average processing time around into three decimal places and remember SQL is three decimal places and remember SQL is a a about breaking a problem down into a about breaking a problem down into a smaller parts and building up your query smaller parts and building up your query step by step and I hope this tutorial step by step and I hope this tutorial was helpful and remember to practice is was helpful and remember to practice is the key to mastering SQL keep solving the key to mastering SQL keep solving problems and you will get the hack of it problems and you will get the hack of it in no time and if you like this video in no time and if you like this video don't forget to hit the like button and don't forget to hit the like button and subscribe for more coding tutorials subscribe for more coding tutorials until next time happy coding until next time happy coding see you next time
2024-03-20 10:20:22
1,661
https://i.ytimg.com/vi/9…axresdefault.jpg
Master SQL with VanAmsen: Solve 'Average Time of Process per Machine' from LeetCode | 1661
c2nQk4vP55s
hey everyone welcome back and today I'll be doing another lead code problem seven be doing another lead code problem seven four six minimum cost climbing stair four six minimum cost climbing stair this is an easy one and a very similar this is an easy one and a very similar problem or exactly the same problem you problem or exactly the same problem you can say uh to the 70 climbing stair but can say uh to the 70 climbing stair but in this problem we are just only going in this problem we are just only going to return the minimum cost of the to return the minimum cost of the climbing stairs so that what is the cost climbing stairs so that what is the cost the cost is the step we are on so let me the cost is the step we are on so let me explain explain if we have an array like this and we if we have an array like this and we have to reach the ending point which is have to reach the ending point which is zero then obviously we can take two zero then obviously we can take two steps this s and it is at 10 we can take two steps which will may give us 20 but we are not at the very end we will take another step the whole cost operation is going to be 20. but if we take 15 we can either Start From First index or the second index if we start from 15 we can just take two steps and reach the very end that's why we are going to return to 15 because it just cost less what we can do is just take the last start from the very last and add the values add the values next take the minimum of the I plus 1 the location we are on plus one plus two take the minimum index and add them at that location so for 20 it is going to be 20 plus 0 we are not going to you can say change the last two indexes because it does not make sense and 20 can take one steps and from at 0 and 15 can take two steps and at the very last for 10 it does matters because if we go from 10 to 15 then it is going to be a 10 cost operation and now we are in 15 we are going to take a 15 cost operation which will make us to the very end and this will just make the output at 10 25 so we'll be taking the minimum and the minimum is going to be 15 so that's it so cost dot append it with 0 so for I in range of length of cos minus 3 because we do not want to change the last two indexes or that's it and now we want to go till -1 and decrementing one at each point uh like this okay so cost at I is going to be added by the minimum of its next or of its next so cos add I plus 1 post at I plus 2 minimum between minimum between the cost at the very first because we the cost at the very first because we can start from zeroth index or the first can start from zeroth index or the first index so we'll be taking the minimum index so we'll be taking the minimum cost which is present at those indexes cost which is present at those indexes or one and that's it this should work
2024-03-21 12:20:21
746
https://i.ytimg.com/vi/c…5s/sddefault.jpg
746. Min Cost Climbing Stairs | Leetcode | Python
tC-aM1rG1HA
in this video we're going to take a look at a legal problem called nest at a legal problem called nest permutation so implement the nest permutation so implement the nest permutation function which rearranges permutation function which rearranges numbers into the numbers into the lexicographically nest greater lexicographically nest greater permutation of numbers so if such an permutation of numbers so if such an arrangement is not possible where let's arrangement is not possible where let's say we have a situation where we have say we have a situation where we have the maximum permutation of our current the maximum permutation of our current sequence that we want to rearrange it as sequence that we want to rearrange it as the lowest possible order sorted in the lowest possible order sorted in ascending order right so the replacement ascending order right so the replacement must be in place basically means that we must be in place basically means that we want to want to compute this or complete this function compute this or complete this function in a constant space complexity so in a constant space complexity so you can see here we have an example you can see here we have an example right so let's say we have nums is equal right so let's say we have nums is equal to one two three so if it's one two to one two three so if it's one two three we want to generate the next three we want to generate the next permutation the next permutation that is permutation the next permutation that is greater than 123 which is 132 right greater than 123 which is 132 right there's also other permutations like there's also other permutations like 213 right or 321 213 right or 321 right these are permutations are greater right these are permutations are greater than this element but in this case we than this element but in this case we want to find the nest greater element want to find the nest greater element that is greater than you know the that is greater than you know the current uh in in this case the current current uh in in this case the current sequence right so in this case the the sequence right so in this case the the solution will be 132 or in this case solution will be 132 or in this case 132. 132. and like i said before if we have a and like i said before if we have a situation in this case if it if it's not situation in this case if it if it's not possible to rearrange it to the next possible to rearrange it to the next greater element in this case what we greater element in this case what we have to do is we have to you know have to do is we have to you know rearrange it as the lowest possible rearrange it as the lowest possible order which is sorted in ascending order order which is sorted in ascending order right so you can see here we convert it right so you can see here we convert it into 1 2 3 which basically means that into 1 2 3 which basically means that we reverse the array into a sorted array we reverse the array into a sorted array right because we know that this is the right because we know that this is the max right so there's no more that we can max right so there's no more that we can go above that so in this case we can go above that so in this case we can just reverse the array into one two just reverse the array into one two three right and let's say we have an three right and let's say we have an example like this one one five in this example like this one one five in this case if i case if i the next greater element for this the next greater element for this sequence is with basically one five one sequence is with basically one five one right and same thing here the last if right and same thing here the last if there's only one element in this case we there's only one element in this case we can just say that we cannot find an s can just say that we cannot find an s permutation we can just don't do permutation we can just don't do anything right and remember the function anything right and remember the function returns void so we're not returning returns void so we're not returning anything we're basically just modifying anything we're basically just modifying the array the array so in this case the constraints is that so in this case the constraints is that the length of the array is between 1 to the length of the array is between 1 to 100 can each element can can contain 100 can each element can can contain duplicates in the array and we can also duplicates in the array and we can also uh the element range is between 0 to uh the element range is between 0 to 100. 100. so in this case how can we better solve so in this case how can we better solve this problem so let's take a look at the this problem so let's take a look at the example here right so let's say we have example here right so let's say we have one two and three so let's say we have one two and three so let's say we have one two and three in this case what we one two and three in this case what we can do is though maybe we can look at can do is though maybe we can look at the current element right we we look at the current element right we we look at the current element in this case current the current element in this case current element is greater than the left element element is greater than the left element maybe we can just swap their order right maybe we can just swap their order right and then in this case you can see we get and then in this case you can see we get one three two right so you might be one three two right so you might be thinking maybe this will this will be a thinking maybe this will this will be a the correct approach to solve this the correct approach to solve this problem but you you're wrong right problem but you you're wrong right because you can see here let's say if i because you can see here let's say if i want to find the next permutation for want to find the next permutation for this sequence then in this case i know this sequence then in this case i know that the current element which is less that the current element which is less than the the uh which is less than the than the the uh which is less than the left element so in this case we this is left element so in this case we this is not this nut element is not we cannot not this nut element is not we cannot swap those two right because if we were swap those two right because if we were to swap those two you can see that the to swap those two you can see that the order will be one two three so therefore order will be one two three so therefore this is actually less than this element this is actually less than this element right so this is not going to work so right so this is not going to work so what we need to do is we continue so we what we need to do is we continue so we know that this current element is know that this current element is actually greater than this element so actually greater than this element so maybe we follow the same logic we will maybe we follow the same logic we will uh swap those two elements here right so uh swap those two elements here right so you can see we will swap those two you can see we will swap those two elements and then what we will get we elements and then what we will get we will get three one two and three one two will get three one two and three one two is not the correct answer for this is not the correct answer for this sequence because in this case the the sequence because in this case the the proper answer for this sequence is proper answer for this sequence is actually two actually two one one three right because you can see here the three right because you can see here the next greater element here is two one next greater element here is two one three so in this case this approach that three so in this case this approach that we were just talking about is wrong so we were just talking about is wrong so in this case in this case what's the in this case in this case what's the right approach to solve this problem right approach to solve this problem so in this case you can see here so in this case you can see here um for following the the the approach um for following the the the approach that we just talked about we can be able that we just talked about we can be able to find the element that we want to to find the element that we want to change right because in this case the change right because in this case the element that we want to change here is element that we want to change here is for sure it's going to be one right we for sure it's going to be one right we cannot change cannot change two or three in this case if we swap two two or three in this case if we swap two and three that's not going to happen and three that's not going to happen because if we swap two and or three and because if we swap two and or three and two right three and two then we will two right three and two then we will then we will become something like this then we will become something like this so in this case the only thing that we so in this case the only thing that we can swap is basically this element right can swap is basically this element right here here right so in this case if i want to swap right so in this case if i want to swap this element to something else which this element to something else which element should we swap in this case this element should we swap in this case this element should swap to the next greater element should swap to the next greater element right the next greater elements element right the next greater elements what is two right if we swap this what is two right if we swap this element with an estimator element element with an estimator element in this case it's not gonna be three in this case it's not gonna be three because three is because three is is the biggest right two is basically is the biggest right two is basically just in between one and three which is just in between one and three which is the next greater element than one so in the next greater element than one so in this case we to swap right what we want this case we to swap right what we want to do is we will actually want to swap to do is we will actually want to swap one with two instead of three so in this one with two instead of three so in this case we have two case we have two right three and one and then what we right three and one and then what we notice is that right we got three here notice is that right we got three here right we got two here but then what we right we got two here but then what we had to do is we have to fix the you know had to do is we have to fix the you know the remaining elements here because in the remaining elements here because in this case the net square element should this case the net square element should be 2 1 3 instead of 3 1 right so maybe be 2 1 3 instead of 3 1 right so maybe what we can do here is that we we can what we can do here is that we we can just reverse the order because in this just reverse the order because in this case we know that this is three this is case we know that this is three this is one right so what we can do is we can one right so what we can do is we can just reverse the order of the remaining just reverse the order of the remaining subsequence right so in this case it subsequence right so in this case it will give us two one three because in will give us two one three because in this case we want to find the next this case we want to find the next greater element right because after we greater element right because after we swap the swap the less greater element than one which is less greater element than one which is two we also have to make sure to reverse two we also have to make sure to reverse that the reason why we reverse this part that the reason why we reverse this part is because in this case you know that we is because in this case you know that we know that the know that the the right side right there this the right side right there this subsequence they're all in a decreasing subsequence they're all in a decreasing order right because the condition is order right because the condition is that if the current element right if the that if the current element right if the current element is greater or in this current element is greater or in this case is not greater than the left case is not greater than the left element then this is not then this this element then this is not then this this is not the element that we wanted that is not the element that we wanted that we want to change right so in this case we want to change right so in this case we continue to search on the left side we continue to search on the left side to find that element so that's what to find that element so that's what we're trying to do here so let's say we we're trying to do here so let's say we give you another example right so let's give you another example right so let's say we have one or maybe three two three say we have one or maybe three two three two one so let's say we have three two two one so let's say we have three two one one so in this case you can see here we can so in this case you can see here we can basically do the same logic we check to basically do the same logic we check to see if current element is greater than see if current element is greater than this the left element in this case is this the left element in this case is not not this is not this is not so therefore this is not this is not so therefore what we can do is we basically what we can do is we basically uh in this case you can see our pointer uh in this case you can see our pointer basically point out a bound so we basically point out a bound so we basically just have to reverse the right basically just have to reverse the right subsequence but in this case let's say subsequence but in this case let's say we have like one one and five right in we have like one one and five right in this case let's say we have 115 we check this case let's say we have 115 we check to see if this is greater than this to see if this is greater than this element in this case it is right the element in this case it is right the current element is greater than the left current element is greater than the left element so we know that this is the element so we know that this is the element that we want to change that we element that we want to change that we want to swap to right in this case we want to swap to right in this case we want to swap to a element that is want to swap to a element that is greater than the current element in this greater than the current element in this case the next greater element case the next greater element on the right side is five right so we on the right side is five right so we swap swap one with a five so now we have one five one with a five so now we have one five one and then what we have to do is we one and then what we have to do is we have to reverse the right side so we have to reverse the right side so we have have uh just one here right so basically our uh just one here right so basically our job is so let's say we have another job is so let's say we have another example right so let's say we have this example right so let's say we have this sequence right here right so we're gonna sequence right here right so we're gonna do is we check to see if current element do is we check to see if current element is greater than the left in this case is greater than the left in this case it's not it's not this element is not greater than the this element is not greater than the left this element is not this element is left this element is not this element is greater than the left so we know that greater than the left so we know that this is the element that we want to this is the element that we want to change right so what we have to do is we change right so what we have to do is we basically trying to find the next basically trying to find the next smallest element on the right side which smallest element on the right side which is five so in this case what we're going is five so in this case what we're going to do is we have swap the order right to do is we have swap the order right with five and four right so in this case with five and four right so in this case we have something like this and then now we have something like this and then now what we have to do is we basically have what we have to do is we basically have to reverse the right side right the to reverse the right side right the right subsequence right subsequence in this case we have something like in this case we have something like this right four and six in this case you this right four and six in this case you can see this is basically the net square can see this is basically the net square uh or the nest permutation of this uh or the nest permutation of this sequence right here right so now you sequence right here right so now you know how we can be able to solve this know how we can be able to solve this problem let's take a look at how we can problem let's take a look at how we can do this in code so now let's take a look do this in code so now let's take a look at the code right so you can see here we at the code right so you can see here we have a function that's permutation which have a function that's permutation which takes the integer right so our base case takes the integer right so our base case is that if n right is only there's only is that if n right is only there's only one element in the array then we could one element in the array then we could just return right because in this case just return right because in this case the next permutation is basically the the next permutation is basically the array itself array itself so what we're going to do then is that so what we're going to do then is that we're going to first find the elements we're going to first find the elements to replace right so in this case let's to replace right so in this case let's say we have 4 6 say we have 4 6 5 5 3 right it doesn't really matter what we 3 right it doesn't really matter what we have up front basically you can see here have up front basically you can see here we want to find the elements that we we want to find the elements that we want to replace in this case we are want to replace in this case we are starting from here right the current is starting from here right the current is pointing here the previous point here pointing here the previous point here right so in this case we have a current right so in this case we have a current pointer and the previous pointer we're pointer and the previous pointer we're shifting right moving from the right shifting right moving from the right side to the left side right we go from side to the left side right we go from the right to the left in this case what the right to the left in this case what we're going to do is that if we if we're going to do is that if we if there's a situation where the previous there's a situation where the previous element is actually bigger than the element is actually bigger than the current element right and that will be current element right and that will be at this position right in this case six at this position right in this case six is actually bigger than four then what is actually bigger than four then what we have to do is we just break and once we have to do is we just break and once we break what we're going to do is that we break what we're going to do is that we're going to check the two things we're going to check the two things right if the current index in this case right if the current index in this case this is current this is current if current is actually bigger than or if current is actually bigger than or equal to zero why because there could be equal to zero why because there could be a situation where we only have six a situation where we only have six five three right if we only have six five three right if we only have six five three and in this case guess what five three and in this case guess what current is here and the previous is current is here and the previous is right here right so you can see here right here right so you can see here current is out of bound so if it's out current is out of bound so if it's out of bound then we just have to reverse of bound then we just have to reverse what we have for prev and the last what we have for prev and the last element right which is element right which is this sequence right here right but if this sequence right here right but if not not if the element that we wanted to replace if the element that we wanted to replace is somewhere in the array right which is is somewhere in the array right which is bigger than or equal to zero bigger than or equal to zero now what we do first is we want to find now what we do first is we want to find the index that we want to swap right and the index that we want to swap right and then we reverse the remaining then we reverse the remaining subsequence right so you can see here we subsequence right so you can see here we have our in this case we have our uh have our in this case we have our uh pointer right so in this case you can pointer right so in this case you can see see the reason why we want to do this way the reason why we want to do this way right this code right here the reason right this code right here the reason because you can see here you notice because you can see here you notice during the process of during the process of coming towards current right coming towards current right here is a decreasing order right because here is a decreasing order right because of this condition if it's a of this condition if it's a decreasing order then we know that we decreasing order then we know that we can basically try to find the next can basically try to find the next element by starting from the last element by starting from the last element right so does this element element right so does this element greater than 4 in this case not 5 in greater than 4 in this case not 5 in this case 5 is right because in this this case 5 is right because in this case you can see it's a decreasing order case you can see it's a decreasing order so the next element that we can find so the next element that we can find that's greater than this current element that's greater than this current element is guaranteed to be the next greater is guaranteed to be the next greater element for four right so the next element for four right so the next greater element for four is five so greater element for four is five so we're going to replace that so five six we're going to replace that so five six four three right and then what we're four three right and then what we're gonna do is we're just gonna reverse the gonna do is we're just gonna reverse the last half or the you know you know in last half or the you know you know in this case the right half of the sub this case the right half of the sub array right in this case we have 5 array right in this case we have 5 3 4 and 6. so now you can see this is 3 4 and 6. so now you can see this is basically our answer and that's why we basically our answer and that's why we reverse it here so this is how we solve reverse it here so this is how we solve the problem so in this case the time the problem so in this case the time complexity for this solution is going to complexity for this solution is going to be big o of n where we're basically just be big o of n where we're basically just going to iterate the array a couple of going to iterate the array a couple of times right so first we want to find the times right so first we want to find the elements to replace and then what we do elements to replace and then what we do is we basically try to find the replace is we basically try to find the replace index and then we reverse the the array index and then we reverse the the array which still the time complexity is big o which still the time complexity is big o of n right and the space complexity here of n right and the space complexity here is basically just going to be big o of is basically just going to be big o of one because you can see here we're only one because you can see here we're only using pointers right using couple using pointers right using couple pointers to reverse the array or pointers to reverse the array or basically try to find the nest or the basically try to find the nest or the elements to replace or try to find the elements to replace or try to find the elements to or the replace index right elements to or the replace index right so in this case the overall space so in this case the overall space complexity is basically just going to be complexity is basically just going to be big over 1.
2024-03-20 08:37:40
31
https://i.ytimg.com/vi_w…xresdefault.webp
[Java] Leetcode 31. Next Permutation [Array #11]
wgH7VvEy5jY
hello everyone i'm young first i'm young first welcome to my channel welcome to my channel this is the series about the self mocha this is the series about the self mocha technical interview in english technical interview in english today in this today in this episode episode we will to solve any problem of little code so let's start today the difficulty is a medium so i think we should resolve this problem within 20 minutes unique binary searcher trees given integer returns a number of structurally unique binary search trees which has exactly a note of unique so so so it's so it's it's water very clearly it's water very clearly so let's so let's look at the example say look at the example say this is the three this is the three so we have four for binary circuitry tree which reaches the node is from one to n yes so it's a more com so it's a more com connear connear when we had the example when we had the example uh uh we have a unicorn we have a unicorn and we need to and we need to get the get the the number of the the number of the unique binary trees unique binary trees [Music] [Music] ratio has exactly a nose ratio has exactly a nose for example for example three is one two three one two three one three is one two three one two three one two three one two three one two three two three one two three one two three and those five and those five [Music] [Music] binary circuitry binary circuitry uh are uh are valid by research tree and uh valid by research tree and uh and it has three nodes and it has three nodes and there is no other and there is no other binary trace binary trace that that that has a nodes so that has a nodes so so we need to return five so we need to return five another one in fact is very small another one in fact is very small which is uh which is uh from one to from one to none none nothing so so what do you think sample for example if sample for example if is zero is zero uh no there is no zero if it is one so uh no there is no zero if it is one so there is just one there is just one uh one binary search tree it's just one uh one binary search tree it's just one node node uh and if there is a two and equals two uh i think there is a um um there is a there is a first one first one and then this is two and this is two and uh and this is two and uh this is one there is a two put to this is one there is a two put to two binary surgery two binary surgery and uh and uh when when and use this three how how do we construct the bandwidth tree and like like two way first try to put a uh put the ivory node node as the the root node and uh and we put a put the remain nodes in the left or in the right so so for um equal to three we first put a one and then we put a uh put a two and uh finally we put the three as the root note and then for for for one is the route we have two and three so we can we can restart recursively car cars cause a num trace the same function with the argument equal to two and and two two with an equals two there this is the two with an equals two there this is the two so so so there is two such situations when one is the one is the root tree and if uh two is a router node uh we have one three here so we need to call numtrace function with argument one and with the argument one and we need to multiply the the two numbers because they are independently the they are independent with each other [Music] whether the three is the rule node is very similar with the one one is the glutamate we have two nodes in the left so and and we recursively call the same trace we recursively call the same trace in the left and the way there is no note in the right so it's one so finally we get our answer it's a recursively solution we need to [Applause] we need to we need to um um to iterate every possible ruth note to iterate every possible ruth note uh and uh and after we choose the router node either after we choose the router node either [Music] [Music] part part it it divided the whole divided the whole nodes into two parts nodes into two parts after part and the red part after part and the red part and we recursively and we recursively call the call the function function and and we multiplies to we multiplies to to answer to answer so let's do that so let's do that and and hope hope maybe we can maybe we can analyze the time camp city first analyze the time camp city first because we need a two iterator or because we need a two iterator or a possible route so it's a a possible route so it's a that we need to car um the two the two functions functions and to the left tree and the left tree so the the on the answer the time constitutes the answer in fact if the answer is five we we will so how how how do we present the so how how how do we present the the temporality the temporality time capacity with um i'm not sure [Music] and the and the the space community is the same as the the space community is the same as the time capacity because because we need to we need a car cars or we need a car cars or the with arguments one to be honest i'm i'm not sure about the time complexity and the space completely but i believe that my solution can pass so as a 2r as a 2r function function let's do our implementation and uh if n [Music] is one and and if it's is larger than one we need to if it's is larger than one we need to iterate iterate every possible have a possible new note answer and we need to answer and we need to [Music] [Music] sum the sum the left and and and [Music] [Music] i i here is i um we put one here i have to use zero here here and we need to return on and we need to return on because there is some duplicator because there is some duplicator computation computation so we need a catch here so we need a catch here so so wait with this wait with this annotation we can annotation we can we we can catch we we can catch the the the answer which we have calculated so [Music] so we can avoid the opening the [Music] [Music] so so we need to return here so that's the r code the code is very short and very oh let's try to submit that yes way way success the the solution is right i did this before one years and ago and two years ago now i want to see some more discuss let's do some [Music] uh there is no time uh there is no time capacity analysis tool capacity analysis tool i think maybe it's very difficult to i think maybe it's very difficult to analyze that okay oh so it's a catholic number it's impossible to analyze the time it's impossible to analyze the time capacity capacity [Music] [Music] so okay so okay i think the time capacity is i think the time capacity is is a combination number is a combination number which we call the kitteny number yeah it's buddha um it's good to know the catalytic number and the temperature but you but but i think it's a fan if you don't know it super super super difficult and mathematically super difficult and mathematically solution so so i think you you just need to learn how to solve this problem of ways uh with the recursive under the dynamical so i think this is my today's video so i think this is my today's video thank you for your watching thank you for your watching and bye bye see you tomorrow
2024-03-20 13:39:14
96
https://i.ytimg.com/vi/w…axresdefault.jpg
Self Mock Technical Interview: Day 23 LeetCode 96. Unique Binary Search Trees
aua3ljs7iqg
hello and welcome to another video in this video we're going to be video in this video we're going to be working on determine if two strings are working on determine if two strings are Clos and in the problem two strings are Clos and in the problem two strings are considered close if you can attain one considered close if you can attain one from the other using the following from the other using the following operations one swap any two existing operations one swap any two existing characters so swap their location and characters so swap their location and two transform every occurrence of one two transform every occurrence of one character into another and do the same character into another and do the same for the other so for example transform for the other so for example transform all A's into B's and all B's into A's all A's into B's and all B's into A's you can use operation as many times on you can use operation as many times on each string as many times as you want each string as many times as you want given to strings word one and word two given to strings word one and word two return true if they are close and false return true if they are close and false otherwise so in this example you can otherwise so in this example you can just use word one to make the strings just use word one to make the strings the same because word One lets you swap the same because word One lets you swap the order of oper the swap the order of the order of oper the swap the order of letters and the letters are all the same letters and the letters are all the same so this is fine here you can't because so this is fine here you can't because there's only one a and there's two here there's only one a and there's two here so there's like nothing you can do like so there's like nothing you can do like you're only going to have one a here and you're only going to have one a here and two A's here and in the last one you can two A's here and in the last one you can do it as well and they kind of do it as well and they kind of demonstrate here so the main thing for demonstrate here so the main thing for this problem is you basically have to to this problem is you basically have to to figure out what these operations allow figure out what these operations allow you to do and then what you have to look you to do and then what you have to look for to figure out if it's possible and for to figure out if it's possible and the constraint is 10 the 5ifth that the constraint is 10 the 5ifth that means you need an oven or an login means you need an oven or an login operation so I think this first one is operation so I think this first one is kind of straightforward like what this kind of straightforward like what this operation allows you to do right so this operation allows you to do right so this is basically saying if I have equal is basically saying if I have equal number of number of characters into Strings then I can make characters into Strings then I can make them equal right that like that should them equal right that like that should be pretty easy be pretty easy and let me show what that means so let's and let me show what that means so let's say I have say I have like and it doesn't really matter in like and it doesn't really matter in what order so if I have like ABC D and I what order so if I have like ABC D and I have dcba or dcab or anything basically have dcba or dcab or anything basically if the number of every character is the if the number of every character is the same I can just move these around using same I can just move these around using this operation to make them equal right this operation to make them equal right so that's what this one does and that so that's what this one does and that one's pretty straightforward now the one's pretty straightforward now the second one's a little bit um trickier second one's a little bit um trickier but basically if you can change all of but basically if you can change all of one character into another and backwards one character into another and backwards what this means is if I have like let's what this means is if I have like let's say I have three A's and I have two B's say I have three A's and I have two B's if I change all of my A's into B's and if I change all of my A's into B's and all of my B's into A's I basically swap all of my B's into A's I basically swap their their counts so what would happen is if I use counts so what would happen is if I use this operation then I have two this operation then I have two characters and I basically swap their counts so any characters you have you can swap count so like if I have some B's some C's let's say I have whatever right I can take these four counts and kind of rearrange them around no matter like depending on what I want right if I want Four A's I can swap A's and C's so I can basically get this to be any format I want right like let's say we want for example let's say we want 1 a 2 B's 3 C's and 4 D's this is always possible because your counts are in these numbers so if we wanted this let's just kind of like quickly figure out how we would do that so let's just say we swap C's and D's so we would swap their counts so this would be four now and this would be one now we want three C's so we can swap C's and B's so this would be three and this would be two H sorry it would be one actually and then we want to swap these as well so we would have 1 a and 2 BS so now that you understand like what these operations do it should be a lot easier to solve this problem basically we're looking for two things when we have two words W1 and W2 we need two things for these two words to be correct one we need each word to have the same letters right so for example if I have like ABC I need letters a b and c to be in the other word right like if I have like a z over here I can't I can't do anything with this like I can't change the letter into another letter I can swap stuff but I can never just get rid of the Z so that's one like and we just need to have like one of these so it's totally fine to have different counts but we need each word to have basically like if I if i' get a set of letters in one word and a set of letters in the other word those should be equal now the second thing you need so this is number one the second thing you need is because we can rearrange these counts we need the counts to be the same numbers in both words and what I mean by that is the counts need to be the same numbers they don't need to be the same for every letter but if I just like sort the counts they need to be the same so let's just kind of like walk through an example here so let's say this word on the left has ABCD and we'll have some counts so like a has a count of Four B has a count of three D has count of two c has a count of one this word on the right needs to also have these four letters a b c d you can't have any other letters and it missing and the counts have to be these missing and the counts have to be these numbers so there has to be 1 4 1 3 1 2 numbers so there has to be 1 4 1 3 1 2 and 1 one and if I have that no matter and 1 one and if I have that no matter what these are no matter where these are what these are no matter where these are like if this is 1 2 3 4 let's say now I like if this is 1 2 3 4 let's say now I am always able to turn this word into am always able to turn this word into this word because I can just rearrange this word because I can just rearrange these counts right as long as basically these counts right as long as basically the keys are all the same and these the keys are all the same and these counts are all the same now how do we counts are all the same now how do we look for that so one way to do that is look for that so one way to do that is like get a set of keys let's say and you like get a set of keys let's say and you just compare one by one maybe even sort just compare one by one maybe even sort the keys just to make sure you're like the keys just to make sure you're like comparing them right so you get some comparing them right so you get some word over here on the left you get all word over here on the left you get all the different letters and you sort them the different letters and you sort them and you'll have like a b CD here then on and you'll have like a b CD here then on the right same thing get all the letters the right same thing get all the letters and sort them and it's going to be and sort them and it's going to be pretty fast because there's only 26 pretty fast because there's only 26 letters if you do a set right so you'll letters if you do a set right so you'll have ABCD here so these will be equal have ABCD here so these will be equal and then the counts kind of the same and then the counts kind of the same thing get all of the counts and just thing get all of the counts and just sort them in increasing or decreasing sort them in increasing or decreasing order and just compare the values so in order and just compare the values so in here if I just get the counts put them here if I just get the counts put them into an array it'll be 1 2 3 4 on the into an array it'll be 1 2 3 4 on the right same same thing 1 2 3 4 and if any right same same thing 1 2 3 4 and if any of these criteria doesn't match then you of these criteria doesn't match then you can't have this work right like if this can't have this work right like if this a was a z then this would never work a was a z then this would never work because I need an a here and so on right because I need an a here and so on right or if I had like an extra letter here it or if I had like an extra letter here it wouldn't work either because I can never wouldn't work either because I can never I can never get this Z I can't produce I can never get this Z I can't produce it out of nothing so I need to get a z it out of nothing so I need to get a z here but I but I can't do that so the here but I but I can't do that so the keys have to be exactly the same and keys have to be exactly the same and like I said the counts have to be like I said the counts have to be exactly the same not for letter but just exactly the same not for letter but just overall all all the numbers if you just overall all all the numbers if you just take them together they have to be take them together they have to be exactly the same right so I have 1 2 3 4 exactly the same right so I have 1 2 3 4 and a 1 2 3 4 they can be in any order and a 1 2 3 4 they can be in any order you want but that's basically you want but that's basically it and yeah like I said bunch of ways to it and yeah like I said bunch of ways to code this but that's basically all we code this but that's basically all we need to have these two things and that's need to have these two things and that's why you need to understand what these why you need to understand what these operations do and as long as you see the operations do and as long as you see the first operation make sure that like I first operation make sure that like I don't really care what order my letters don't really care what order my letters are in I can make it in whatever I want are in I can make it in whatever I want and the separ second operation lets me and the separ second operation lets me flip counts so as long as these Keys flip counts so as long as these Keys actually exist I can make their counts actually exist I can make their counts match up and get the word I want so the match up and get the word I want so the order doesn't really matter okay so now order doesn't really matter okay so now we can code it we can code it up so in Python this is a lot easier up so in Python this is a lot easier than other languages so in Python we can than other languages so in Python we can get two counters and what a counter will get two counters and what a counter will do is it'll give you a dictionary of um do is it'll give you a dictionary of um the letter and its count so we can do the letter and its count so we can do that for both of the words so counter that for both of the words so counter one one counter word two counter word two now the other thing that's also really now the other thing that's also really nice in Python is you can actually nice in Python is you can actually compare Keys directly so I can just say compare Keys directly so I can just say like this counter like this counter one dokeys which will be the set of one dokeys which will be the set of letters in the first word and counter letters in the first word and counter to. Keys which will be the set of to. Keys which will be the set of letters in the second word and in Python letters in the second word and in Python um these things aren't compared by um these things aren't compared by reference they're compared by value so reference they're compared by value so if you compare two sets it will compare if you compare two sets it will compare like every value in them and they're like every value in them and they're unordered so if I do like for example if unordered so if I do like for example if I print uh set 1 2 I print uh set 1 2 3 let's say 3 let's say equals equals set21 even though they're in the wrong set21 even though they're in the wrong order this should print true and we can order this should print true and we can test that so we can print it and then we test that so we can print it and then we can just return like false or something can just return like false or something so we can look at this really quick uh so we can look at this really quick uh false so if we run this and we actually false so if we run this and we actually get out of this thing I always forget get out of this thing I always forget how so you can see that it this is how so you can see that it this is indeed true so you can compare sets you indeed true so you can compare sets you can compare arrays you can compare can compare arrays you can compare whatever you want and it will compare by whatever you want and it will compare by value so what this allows us to do is we value so what this allows us to do is we can use this so we basically need these can use this so we basically need these two things to be true so we can just say two things to be true so we can just say like return these two things have to be like return these two things have to be equal right because these are two sets equal right because these are two sets and the two arrays of values have to be and the two arrays of values have to be equal but they have to be equal in like equal but they have to be equal in like you can't really compare uh array the you can't really compare uh array the way array comparison works is you will way array comparison works is you will compare like value by by value right so compare like value by by value right so if I do like let's say I want to print if I do like let's say I want to print let's do one more print just to show let's do one more print just to show this like if I print this like if I print this let tab so if I print like 1 12 3 this let tab so if I print like 1 12 3 equals equals 321 this is going to be false right 321 this is going to be false right because the array is like it Compares because the array is like it Compares element by element so we can see here element by element so we can see here it's false but if I do 1 2 3al 1 2 it's false but if I do 1 2 3al 1 2 3 this will print true so in Python we 3 this will print true so in Python we can literally just pass in the Ed values can literally just pass in the Ed values here right so we'll just sort the values here right so we'll just sort the values in increasing order and just say are in increasing order and just say are they equal and it will do it for us they equal and it will do it for us instead of having to go value by value instead of having to go value by value so you can say sorted counter 1. so you can say sorted counter 1. values equals sorted counter 2. values values equals sorted counter 2. values and so what the values will be is it and so what the values will be is it will be all of the values in the will be all of the values in the dictionary and we will sort them so is dictionary and we will sort them so is this sorted array equal to this sorted this sorted array equal to this sorted array and all the keys are exactly the array and all the keys are exactly the same if that's true we can return true same if that's true we can return true so let's run that like I said you can so let's run that like I said you can definitely code this up with like more definitely code this up with like more lines but this works too and I think lines but this works too and I think it's not super hard to understand what's it's not super hard to understand what's going going on um yeah and we can on um yeah and we can submit so you can see it's pretty good submit so you can see it's pretty good roughly the same as other stuff run a roughly the same as other stuff run a bunch it's like all over the place again bunch it's like all over the place again um but yeah and the nice thing about um but yeah and the nice thing about this once again is since all the letters this once again is since all the letters I think are let's just double check I think are let's just double check they're usually just lowercase English they're usually just lowercase English letters right so lowercase English letters right so lowercase English letters which means that these counters letters which means that these counters are very cheap to make so for the time are very cheap to make so for the time to build these counters is O of let's to build these counters is O of let's just say word one well actually here um just say word one well actually here um you you can do like a you can do you you can do like a you can do something quick to you can also just something quick to you can also just have a little thing here like says like have a little thing here like says like if length of word if length of word one does not equal length of word two one does not equal length of word two return false so you can add that in as return false so you can add that in as well it does not equal well it does not equal um oh um oh yeah so if we add that in now we yeah so if we add that in now we basically avoid the cases where the basically avoid the cases where the letter counts are different right letter counts are different right because you still have to have the same because you still have to have the same total count of letters to have an total count of letters to have an anagram so now basically word one and anagram so now basically word one and word two word two will always be the word two word two will always be the same length so you could say like this same length so you could say like this is O of n where n is the length of word is O of n where n is the length of word one because you're essentially looping one because you're essentially looping through twice the length of word through twice the length of word one and yeah the nice thing is even one and yeah the nice thing is even though we are sorting these values the though we are sorting these values the values are only 26 values maximum right values are only 26 values maximum right because it's only lowercase English because it's only lowercase English letters so even though this is 10 to the letters so even though this is 10 to the 5th these dictionaries will only have 26 5th these dictionaries will only have 26 Keys 26 values of sorting 26 letters is Keys 26 values of sorting 26 letters is super fast so time is oen here and space super fast so time is oen here and space is o1 because like I said uh there's is o1 because like I said uh there's only 26 letters so it's constant no only 26 letters so it's constant no matter how big your word is you can only matter how big your word is you can only have 26 letters and this part is also have 26 letters and this part is also only 26 uh an array of 26 values so it's only 26 uh an array of 26 values so it's constant time and the sort is constant constant time and the sort is constant time as well which because it's only time as well which because it's only sorting 26 values so pretty good sorting 26 values so pretty good um yeah and the main thing is just to um yeah and the main thing is just to understand like what these things are understand like what these things are and not too bad of a problem and I think and not too bad of a problem and I think that should be all for this problem so that should be all for this problem so if you did like it please like it and if you did like it please like it and please subscribe to the channel like please subscribe to the channel like always and I'll see you in the next one always and I'll see you in the next one thanks for watching
2024-03-19 18:37:33
1,657
https://i.ytimg.com/vi/a…axresdefault.jpg
LeetCode 1657 - Determine if Two Strings Are Close - Python
JqJmQzC-Fmg
one so today I'm here to solve this search insert position problem it's a search insert position problem it's a lead code daily lead code daily um and we have been given a sorted array um and we have been given a sorted array of distinct integers and a Target value of distinct integers and a Target value we have to return the index if the we have to return the index if the target is found if not return the index target is found if not return the index where it would be if it were inserted in where it would be if it were inserted in order you must write an algorithm with order you must write an algorithm with four log and runtime complexity it said four log and runtime complexity it said that we have to write o log n so that we have to write o log n so that means we will have to do binary that means we will have to do binary search search linear time o n won't be like possible linear time o n won't be like possible uh since it's going to be o of n uh since it's going to be o of n so so let's try to do it binary search that is offload login if you were to do it in all o of n it would be simple we would like go from here one by one since it's in in a sorted array so you would just simply keep going until we find a bigger number and if we find a bigger number without finding our Target we we would just simply return uh this index -1 so in this case uh we will we we will find 5 and so we return the index 2 and in this case we don't find 2 instead we find that 3 that is bigger than 2 so we'll return this index as our insert index that will be 1. okay let's start coding for binary search we know that we have to do take take two pointers left and right and made uh like start and end and made so let's just start with it let's start equals to 0 initially left n equals to nums dot length then while start is less than equals to um we calculate mid that Mid First let's um we calculate mid that Mid First let's check the constraints first turn is to check the constraints first turn is to power 4 so uh it will be like power 4 so uh it will be like start Plus start Plus start divided by 2 let's make it since it's JavaScript let's make it float math Dot we don't have to make the floor we just we don't have to make the floor we just have to make have to make this one this one okay okay why is it showing an error why is it showing an error ah I missed an i if now we check if we have found our number with a turn with a turn net we return the index if we have found net we return the index if we have found the number the number otherwise what we do is we see if otherwise what we do is we see if mid is um less than Target so in that case that means our number will be inserted uh like after this number so we will have to move our start so suppose we have to find file here so what we will do is we will take mid will be 3 emit a this is smaller so we skip this and start from here so we make start as he made Plus 1. and else minus one minus one and then if we can't find it then we'll turn you know let's you know let's let's see if this works so we have start as 0 that is one we so we have start as 0 that is one we have end as have end as 0 1 2 3 0 1 2 3 1 2 3 3 as 6 and we have Target as five 1 2 3 3 as 6 and we have Target as five then our Midfield please 0 Plus then our Midfield please 0 Plus 0 plus 3 three minus zero three minus zero divided by 2 that will be 1.5 since we divided by 2 that will be 1.5 since we take floor it will be 1 take floor it will be 1 commit of one that is uh three three since three is less than our Target we move start to Mid plus 1 so mid was one so we make start equals to Mid plus 1 that is one plus one which is 2 and then again let's remove this six we only look at let's remove this six we only look at the indexes for now and we calculate the indexes for now and we calculate made as 2 plus 3 minus 2 made as 2 plus 3 minus 2 that is 1 divided by 2 that is 1 divided by 2 this will be 2.5 since we are rounding this will be 2.5 since we are rounding down so it will be 2 down so it will be 2 and then um this is 2 is 5. 0122 is it it's 5 since then we come here and then we have found the target we return made that is correct let's let's look at the oh oh here we have input here we have input nums one three five six Target is two so nums one three five six Target is two so we start same and then we have made that is 3 this is bigger than 2 so we go minus um Mid minus 1 and will be mid minus 1 equals uh what is it end was Midwest three mid was one so we make it zero and start was also is zero start is also zero and is zero as well so in this case at the same index what we do is we at the same index what we do is we calculate mid equals to 0 plus 0 image calculate mid equals to 0 plus 0 image is also zero so this will return made as zero this is less than Target so what we do is we um make start as mid plus 1 so start moves ah it didn't work ah it didn't work for some reason for some reason why why expected is 2 and we return 5. we returned matters oh yeah right we we were we we had to compare is made nums let's see yeah it worked nice so since it's a binary search we have a Time complexity of O of log n it was not so straightforward but yeah if it if you were to do it using a linear search it would be much simpler and we could do it like just keep searching keep looking one by one and then once we find one larger number we return it as the index but since we had to do it in off login we used binary search it was pretty simple and pretty straightforward yeah
2024-03-20 08:52:58
35
https://i.ytimg.com/vi/J…axresdefault.jpg
LeetCode 35: Search Insert Position - Step-by-Step Solution
_trih2YN9vM
hey everyone in this video let's take a look at question 329 longest increasing look at question 329 longest increasing path in a matrix this is part of our path in a matrix this is part of our blind 75 list of questions so let's blind 75 list of questions so let's begin begin in this question you are given M by n in this question you are given M by n integers Matrix so Matrix array which is integers Matrix so Matrix array which is M by n and you want to return the length M by n and you want to return the length of the longest increasing path in Matrix of the longest increasing path in Matrix from each cell you can either move left from each cell you can either move left right up or down and you cannot move right up or down and you cannot move diagonally or go out of bounds diagonally or go out of bounds basically here the longest path is one basically here the longest path is one two six and nine that's increasing and two six and nine that's increasing and looks like it has to be strictly looks like it has to be strictly increasing increasing you can see that this path is a length you can see that this path is a length of four which we return here and here of four which we return here and here it's three four five six similarly it's three four five six similarly Atlanta 4. and at the minimum actually Atlanta 4. and at the minimum actually the path will be one right so at the the path will be one right so at the minimum we can return a length of one minimum we can return a length of one okay so this is our basic like graph okay so this is our basic like graph type not graph but like Matrix type type not graph but like Matrix type question but we will use one of the question but we will use one of the graph type algorithms specifically we graph type algorithms specifically we can use DFS but why did it come up with can use DFS but why did it come up with DFS well usually when you see these DFS well usually when you see these types of problems and a DFS is a good types of problems and a DFS is a good choice whenever you want to find the choice whenever you want to find the maximum something the minimum something maximum something the minimum something especially when it relates to some sort especially when it relates to some sort of Matrix or some sort of Greater grid of Matrix or some sort of Greater grid of numbers so that's one thing of numbers so that's one thing but another another thing is it just but another another thing is it just makes sense right like for example if we makes sense right like for example if we have like one over here then I want to have like one over here then I want to try to go as far as I can along this try to go as far as I can along this Matrix to find out if I can maybe extend Matrix to find out if I can maybe extend this one and form a longest path so this one and form a longest path so that's how kind of DFS comes to my mind that's how kind of DFS comes to my mind now this question if you think if you've now this question if you think if you've done the number of islands question you done the number of islands question you know that in that one we also did DFS know that in that one we also did DFS but one of the differences there was but one of the differences there was that we did not have to do TFS off of that we did not have to do TFS off of every single cell right in the number of every single cell right in the number of islands question we only did DFS from islands question we only did DFS from the islands themselves basically the islands themselves basically wherever the entry was a one here we wherever the entry was a one here we don't really have any of that like don't really have any of that like constraint right here it's not really constraint right here it's not really clear to me that we can only do DFS from clear to me that we can only do DFS from a specific location really here we have a specific location really here we have to DFS from all of these cells because to DFS from all of these cells because there's nothing that tells me that you there's nothing that tells me that you know like only I can do DFS from one know like only I can do DFS from one location so in this case I have to DFS location so in this case I have to DFS from every single cell so that's from every single cell so that's something that's kind of different based something that's kind of different based on um compared to like number of islands on um compared to like number of islands now otherwise if you just think about now otherwise if you just think about this question it's it's not really that this question it's it's not really that hard if you have done these types of hard if you have done these types of questions before so I know this question questions before so I know this question is labeled labels labeled as hard to put is labeled labels labeled as hard to put if you've really done these types of if you've really done these types of questions before then they often try to questions before then they often try to follow like the same sort of invention follow like the same sort of invention or same sort of structure in terms of or same sort of structure in terms of the code but let's take a look at how the code but let's take a look at how how this can work right so how this can work right so let's assume that we start off over here let's assume that we start off over here obviously we won't start our DFS call obviously we won't start our DFS call from here we'll start from over here but from here we'll start from over here but let's just assume that we start from let's just assume that we start from here so then what can we do well we know here so then what can we do well we know our minimum by at minimum our answer our minimum by at minimum our answer will be one right at minimum our answer will be one right at minimum our answer will be one what can we do well will be one what can we do well from this location here I can travel from this location here I can travel either up towards the six right towards either up towards the six right towards the one or left towards the two now I the one or left towards the two now I don't necessarily know which one of don't necessarily know which one of these is going to give me the longest these is going to give me the longest path right I don't even know if any of path right I don't even know if any of these are valid for example if I go to these are valid for example if I go to this side over here this is not valid this side over here this is not valid right because basically I cannot form right because basically I cannot form anything here one and one this does not anything here one and one this does not work one and six work one and two work work one and six work one and two work but one and one does not work okay so we but one and one does not work okay so we have that information so we need to have that information so we need to somehow check like to see if the path is somehow check like to see if the path is even valid in the first place and we'll even valid in the first place and we'll talk about how we can do that talk about how we can do that let's say we go to the two here okay if let's say we go to the two here okay if we go to the two then the two works okay we go to the two then the two works okay cool then the six also works and nine cool then the six also works and nine also works now if we go outside the nine also works now if we go outside the nine then we're like basically like out of then we're like basically like out of bounds right so if we go anywhere over bounds right so if we go anywhere over here or out of bounds so what can we here or out of bounds so what can we have our function return what can we we have our function return what can we we have a recursive function return and if have a recursive function return and if you really think about this one let's you really think about this one let's just say I'm at like a single cell right just say I'm at like a single cell right nine and I go out of bounds but then if nine and I go out of bounds but then if I go out of bounds what is the length of I go out of bounds what is the length of the longest sequence well you may think the longest sequence well you may think it's like zero right because we're going it's like zero right because we're going out of bounds but out of bounds but in reality the length of the sequence in reality the length of the sequence over here is zero like if you go out of over here is zero like if you go out of bounds the length can be zero but when bounds the length can be zero but when we include this nine over here then the we include this nine over here then the length of the longest sequence is one length of the longest sequence is one over here the length of the longest over here the length of the longest sequence basically a one sequence basically a one now we backtrack now we're on the six now we backtrack now we're on the six here what is the length of the longest here what is the length of the longest sequence well whatever this will return sequence well whatever this will return this will return the length of the this will return the length of the longest sequence from nine and onwards longest sequence from nine and onwards so we see from nine and onwards the so we see from nine and onwards the length of the longest sequence was one length of the longest sequence was one and so if we were adding 6 to the and so if we were adding 6 to the sequence then it should be one plus sequence then it should be one plus whatever this one was so now it would be whatever this one was so now it would be two two again let's say we're at the two now and again let's say we're at the two now and we want to return we want to figure out we want to return we want to figure out what is the length of the longest what is the length of the longest sequence well when we did a recursive sequence well when we did a recursive call this call over here from the six call this call over here from the six from right above will return me the from right above will return me the number two it will return me the number number two it will return me the number two now what I can understand from this two now what I can understand from this is that if it returns me to number two is that if it returns me to number two which means that it is increasing then which means that it is increasing then I'm going to add my 2 to this list and I'm going to add my 2 to this list and so it'll become through here the length so it'll become through here the length of the longest sequence up till this of the longest sequence up till this point from Two and onwards is three point from Two and onwards is three again now when I come back to one here again now when I come back to one here then I can see that from my left hand then I can see that from my left hand recursive call I was able to extend my recursive call I was able to extend my longest sequence by three units now if I longest sequence by three units now if I want to include this one here which I do want to include this one here which I do then I can include it add in one more so then I can include it add in one more so get a total of four so that's how we go get a total of four so that's how we go about creating our longest sequences and about creating our longest sequences and we'll basically keep track of the we'll basically keep track of the maximum one and return it in the very maximum one and return it in the very end so let's take a look at how we can end so let's take a look at how we can do this do this and we like to follow our specific and we like to follow our specific format or type of code structure we like format or type of code structure we like to use for these types of problems so to use for these types of problems so first thing I do is I always rename this first thing I do is I always rename this to grid and it's an easier name to just to grid and it's an easier name to just work with then I like to determine what work with then I like to determine what my rows and calls are my rows and calls are and I can do this as so and I can do this as so take the length of the grid and land the take the length of the grid and land the greater zero so that's my m and n and greater zero so that's my m and n and then I like to go through my rows and then I like to go through my rows and calls call in range zero to course calls call in range zero to course and then what well we need to do our DFS and then what well we need to do our DFS call right and we don't have a condition call right and we don't have a condition like if clear that roll call equal one like if clear that roll call equal one then do our DFS and actually here we then do our DFS and actually here we need to we need to do it from every need to we need to do it from every single every single cell so I can do single every single cell so I can do something like after helper I don't know something like after helper I don't know what I'm going to put in here but this what I'm going to put in here but this will be my helper right my my DFS call will be my helper right my my DFS call and this should return to me the log the and this should return to me the log the the list like the longest increase in the list like the longest increase in path starting from this index starting path starting from this index starting from this cell now let's say it returns from this cell now let's say it returns to me like some sort of variable right to me like some sort of variable right like some sort of variable Pat so this like some sort of variable Pat so this is an integer now I need to basically is an integer now I need to basically check this path with my Global path to check this path with my Global path to see which one is longer so maybe I'll see which one is longer so maybe I'll have a global path here call it res and have a global path here call it res and I'll set that equal to one and basically I'll set that equal to one and basically what I can do here is I can do res is what I can do here is I can do res is equal to maximum of res or the path that equal to maximum of res or the path that I got from a recursive call here and I got from a recursive call here and then at the very end you can go ahead then at the very end you can go ahead and return risk okay so that's our and return risk okay so that's our driver function let's see what we can driver function let's see what we can pass in into the helper and a lot of the pass in into the helper and a lot of the time our structure is going to remain time our structure is going to remain the same so what do we need so we need the same so what do we need so we need the grid we need the row and the column the grid we need the row and the column what else do we need well what else do we need well if you think about this right like if if you think about this right like if we're on the 2 here we're on the 2 here how do I know that like how do I know that like this is an increase in path well I need this is an increase in path well I need to know the previous element right to know the previous element right because if I want the two here the only because if I want the two here the only way in which I can maybe even consider way in which I can maybe even consider this path is If the previous number was this path is If the previous number was less than a current number right which less than a current number right which means that I can maybe go ahead and do means that I can maybe go ahead and do my recursion here if I can't do that my recursion here if I can't do that like if this number was a zero then I like if this number was a zero then I can't even do my recursion I just have can't even do my recursion I just have to return so I need to know what my to return so I need to know what my previous number is I will do that previous number is I will do that previous well previous well so I think that's all we need for now so I think that's all we need for now but let's see if we need anything later but let's see if we need anything later on okay so first thing that we want to on okay so first thing that we want to check is whether we're out of bounds or check is whether we're out of bounds or not right and so this is this is what we not right and so this is this is what we always do in these types of questions always do in these types of questions you can check number of islands we you can check number of islands we always like to follow this type of always like to follow this type of format so what we will do here is I'll format so what we will do here is I'll actually just redefine my grid my rows actually just redefine my grid my rows and calls and this could actually be and calls and this could actually be passed in but I just redefined them passed in but I just redefined them because I don't want my helper to be too because I don't want my helper to be too large okay so what are some of the large okay so what are some of the conditions we have to check well we have conditions we have to check well we have a like tiny little formula that we like a like tiny little formula that we like to use so we say if row is less than to use so we say if row is less than zero a row is greater or equal to rows zero a row is greater or equal to rows column is less than zero column is less than zero column very good cause if this is the column very good cause if this is the case then we're out of bounds if we're case then we're out of bounds if we're out of the bounds what do we say well if out of the bounds what do we say well if we're out of bounds basically there's no we're out of bounds basically there's no path right so the length is zero end path right so the length is zero end here here would be zero would be zero what about otherwise well otherwise I'm what about otherwise well otherwise I'm on a cell and I want to check if the on a cell and I want to check if the previous cell was smaller than my previous cell was smaller than my existing cell if it's not smaller then I existing cell if it's not smaller then I can't really do anything I can't recurse can't really do anything I can't recurse from here right so for example it's like from here right so for example it's like if we go from 6 and we go down to one if we go from 6 and we go down to one well this is not an increasing path so I well this is not an increasing path so I can't actually recurse from here what can't actually recurse from here what can we do we can check if can we do we can check if red at row and call if this is less than red at row and call if this is less than my previous value right if it's less my previous value right if it's less than or equal to really less than or than or equal to really less than or equal to my previous value but we have equal to my previous value but we have something like this then it doesn't work something like this then it doesn't work we can return 0 here as well this means we can return 0 here as well this means that from this index we can't form an that from this index we can't form an increase in path increase in path okay so now that we have our base okay so now that we have our base conditions out of the way what can we do conditions out of the way what can we do well now we can go ahead and we can well now we can go ahead and we can recurse recurse let's assume we're at the six now we can let's assume we're at the six now we can request up right down left but let's request up right down left but let's actually just Define that actually just Define that so I would just so I would just Define this like this previous well and Define this like this previous well and then we will fill this in then we will fill this in okay so let's do left right okay so let's do left right up up and then down okay so if I'm going left and then down okay so if I'm going left my column decreases by one if I'm going my column decreases by one if I'm going right my column increases by one I'm right my column increases by one I'm going up my column my row decreases by going up my column my row decreases by one if I'm going down my row increases one if I'm going down my row increases by one now what is previous value here by one now what is previous value here well previous value should now be my well previous value should now be my current value right this is what I'm current value right this is what I'm passing in like I'm going from six to passing in like I'm going from six to nine so I need to pass in the previous nine so I need to pass in the previous value of 9 as 6. so it'll be the current value of 9 as 6. so it'll be the current value which is value which is and actually maybe let me just Define and actually maybe let me just Define because I'm using grid at row and call because I'm using grid at row and call quite a bit let me just Define like um quite a bit let me just Define like um OG here OG as in original as grid on row OG here OG as in original as grid on row and Co and then I will reset this to and Co and then I will reset this to just be OG okay perfect but now now what do I know so if I'm at six right so if I'm at six so let me go back here and I'll actually remove all of this I need to add in this again okay so if I'm at six then I want to know what is the longest path starting here starting here starting here starting here so what would these return well automatically we know that for the bottom case here in this case here it will return zero why because the number is the same or less in this case it's less the one is less and 6 is the same so that's where it overturns zero what about here nine well nine we can see that from nine we can at least do like we can at least like form one right like one is the minimum we can do here because nine at least we can extend at least like the previous one we can extend here so this will be nine right now let's assume that this is actually a 10 here just for argument's sake now what about the a what would the eight return well from the eight we can actually go down and reach this 10 over here right so this 10 and this 8 combined would give us a value of two so then this thing here would return what would it return well it would be one and two the maximum of these right plus the six because I want to extend six into the path here so it would be the maximum one and two which is two and then added one which is three which means this is the longest path six eight and then 10. so let's see how we can do that we can do result is equal to maximum of left right up and down but not just this we want to add the current path so we will do plus one and that's pretty much all there is and then we will return result to whatever the caller was because this will return the maximum the maximum path at the specific index so that's basically all we have so now let's go ahead and run this so we have grid roll call previous vowel so what should I pass in as my previous value well initially I need to pass in something such that the number I'm currently on is greater than previous value so what's the number that's everything is greater than what would be minus infinity right so minus infinity so now let's go ahead and run this code on our test cases to see if we made any mistakes okay so we haven't so let's go ahead and okay and you'll see eventually that okay and you'll see eventually that we'll get a time limit exceeded error we'll get a time limit exceeded error now now I will discuss the time limit exceeded I will discuss the time limit exceeded error in just a moment but one more error in just a moment but one more thing I want to discuss here is if you thing I want to discuss here is if you notice like other are other problems notice like other are other problems what we often did is when we went from what we often did is when we went from one two and then it's possible we could one two and then it's possible we could have went back right so it's possible we have went back right so it's possible we could have had an infinite Loop we have could have had an infinite Loop we have to check this in number of items we have to check this in number of items we have to check this in other graph problems to check this in other graph problems and other grid problems why didn't we and other grid problems why didn't we have to check that here is it possible have to check that here is it possible for us to go for us to go from one and then six and then back to from one and then six and then back to one one and then basically this repeats and then basically this repeats Infinity it just repeats back and forth Infinity it just repeats back and forth is this possible possible do we have to is this possible possible do we have to check for this well check for this well it's possible that we go back and forth it's possible that we go back and forth but notice how if we go back and forth but notice how if we go back and forth we would just return right over here so we would just return right over here so realistically like we don't even need to realistically like we don't even need to check this because we will return right check this because we will return right away so we will not have the case where away so we will not have the case where we just infinitely occurs we will maybe we just infinitely occurs we will maybe go from one to six and then six back to go from one to six and then six back to one but then that's it we will not keep one but then that's it we will not keep going again and again if we want we going again and again if we want we could actually make this a little bit could actually make this a little bit easier just kind of follow our easier just kind of follow our convention in in that what we do is we convention in in that what we do is we set Grid at row and call set Grid at row and call equal to select some arbitrary value equal to select some arbitrary value here and then we can check if Grid at here and then we can check if Grid at row and call is equal to this arbitrary row and call is equal to this arbitrary value that means we visited this in the value that means we visited this in the past so we'll just return zero past so we'll just return zero and then once we are done this we can and then once we are done this we can just reset Grid at row and call back to just reset Grid at row and call back to what it originally was what it originally was and so we can try this out and we will and so we can try this out and we will see that this also works but it actually see that this also works but it actually is not needed and so here I actually is not needed and so here I actually made a mistake because yeah grid arrow made a mistake because yeah grid arrow and call so here maybe I need to do and call so here maybe I need to do something like uh minus one I need to something like uh minus one I need to add an integer here between string and int yeah so this one should actually be minus one and it looks like I can do that because we only have positives okay yeah so this is like something I can check for but I don't really need to but you know I can check for it just to kind of maintain our structure of how we like to do these problems now the last thing is timeline exceeded so the solution actually used to work before um like in 2021 but after they added in this we have to do memoization to basically fix it nope so in order for us to add memoization what we need to do is first of all we can pass in a dictionary here which will essentially be our memo and then here and all of these locations here and we just pass in the memo part of our function okay now what do we need to do well now we can basically check if row call in memo then we can just return ammo at roll call otherwise we need to Cache this so we will do memo at Rocco is equal to Res which is our answer and then we can just return memoiro call which is res in this case let's go ahead and run this test case to see if we pass and we can see that it's actually taking and we can see that it's actually taking a little bit more longer than it needs a little bit more longer than it needs to be it's taking about four seconds so to be it's taking about four seconds so even after memorization why is it so even after memorization why is it so slow well if you take a look at what slow well if you take a look at what we're doing here we're creating a new we're doing here we're creating a new memo every single time right we're memo every single time right we're creating a new memo on every single creating a new memo on every single different cell different cell but do we really need to do this or we but do we really need to do this or we don't right because let's assume like we don't right because let's assume like we have the answer to this cell over here have the answer to this cell over here the cell six over here maybe we got it the cell six over here maybe we got it in some sort of function well if we have in some sort of function well if we have the answer to this cell over here then the answer to this cell over here then that has to be the best answer right it that has to be the best answer right it has to be the best one because from our has to be the best one because from our DFS call we'll try to visit every single DFS call we'll try to visit every single cell we can so if this is the best call cell we can so if this is the best call if this is the best answer then we don't if this is the best answer then we don't need to create a new memo every single need to create a new memo every single time we can actually just create a time we can actually just create a global memo and just reuse that in global memo and just reuse that in subsequent cell calls so we can do memo subsequent cell calls so we can do memo as dictionary here and then we can see as dictionary here and then we can see that if we do it now it is much faster that if we do it now it is much faster so we should be able to finish it within so we should be able to finish it within less than 500 milliseconds which we do less than 500 milliseconds which we do so that's one of the things that we so that's one of the things that we should keep in mind for if you can do should keep in mind for if you can do memorization make sure we don't create a memorization make sure we don't create a new memo every time if you don't need to new memo every time if you don't need to okay so what is the time and space here okay so what is the time and space here so the time basically we're just going so the time basically we're just going through the entire grid and you can see through the entire grid and you can see that memo would basically make us back that memo would basically make us back out very early if we already know the out very early if we already know the answer so you can think of it as worst answer so you can think of it as worst cases like o of M times n and kind of cases like o of M times n and kind of the same thing for the memo in terms of the same thing for the memo in terms of the space complexity it would also be o the space complexity it would also be o of n times m okay thanks for watching
2024-03-24 10:38:32
329
https://i.ytimg.com/vi_w…xresdefault.webp
Longest Increasing Path in a Matrix - Leetcode 329 - Python
Mf7PYwUvxBg
hey guys how's everything going this is Jay sir he's not good at algorithms I'm Jay sir he's not good at algorithms I'm making this video to prepare my making this video to prepare my interview in this video where I'm going interview in this video where I'm going to take take a look at 2/3 sex lowest to take take a look at 2/3 sex lowest common ancestor of a binary tree common ancestor of a binary tree we're coming a man in a tree we need to we're coming a man in a tree we need to find the lowest common ancestor okay say find the lowest common ancestor okay say like we're given a tree like this we like we're given a tree like this we need to find that comma root of 5 + 1 5 need to find that comma root of 5 + 1 5 1 of course is 3 right yeah and it's 1 of course is 3 right yeah and it's lowest so how should we do it while full lowest so how should we do it while full tree the first one great yeah recursion tree the first one great yeah recursion yeah let's find try to find the yeah let's find try to find the relationship between the final week path relationship between the final week path like 5 3 3 5 3 1 and the node itself like 5 3 3 5 3 1 and the node itself what's the relationship between them what's the relationship between them right ok right ok so for one node and the common ancestor so for one node and the common ancestor of two nodes and there are two of two nodes and there are two possibilities right the first one the possibilities right the first one the node is not in the path let's say 4 6 & node is not in the path let's say 4 6 & 2 come on won't be 5 by 3 it's not in 2 come on won't be 5 by 3 it's not in them right if 3 is now in them then the them right if 3 is now in them then the the the common ancestor must be in a the the common ancestor must be in a left tree or in a right tree right yeah left tree or in a right tree right yeah that's for sure that's for sure cool and now if it's if it is the common cool and now if it's if it is the common ancestor what will happen it means in ancestor what will happen it means in left the tree there will be 1 5 or 1 left the tree there will be 1 5 or 1 right yeah there will be five oh one and right yeah there will be five oh one and then another one will be 1 or 5 so that then another one will be 1 or 5 so that 505 and 1 will be in separate tree right 505 and 1 will be in separate tree right that's the case or of course itself must that's the case or of course itself must would be itself might be the target would be itself might be the target right so 4 5 & 3 the common ancestor right so 4 5 & 3 the common ancestor will be 3 so it means that the target will be 3 so it means that the target would be in left tree or uriah tree or would be in left tree or uriah tree or itself so that's that's our relationship itself so that's that's our relationship so for recursion how we do it well for so for recursion how we do it well for case like five industry and one in right case like five industry and one in right tree we cannot we cannot determine the tree we cannot we cannot determine the result until until the recursion of result until until the recursion of these two sub trees returns us the these two sub trees returns us the result right so what we need is that if result right so what we need is that if the tree has five if the tree has one the tree has five if the tree has one right so when we quote create our right so when we quote create our recursion method we are gonna return like four five we need to return the like four five we need to return the node and has Q P and has Q right if we node and has Q P and has Q right if we get Li three we can get a recursion get Li three we can get a recursion function so let's try to do it when we function so let's try to do it when we get when we when we walk on a node what get when we when we walk on a node what we do well first if it's Newell which we do well first if it's Newell which will happen we just return the node is will happen we just return the node is lower right there nothing has B force lower right there nothing has B force that's cute force right now if node it's that's cute force right now if node it's not new not new we will go I will do what we what first we will go I will do what we what first check in the left tree right check in the left tree right it's LCA left has P left as o oak left it's LCA left has P left as o oak left has P left has Q this will be walk note has P left has Q this will be walk note note left right if L see a left note left right if L see a left if the talking common SEC is found then if the talking common SEC is found then what what well we just return them all right we well we just return them all right we don't need to travel to go to write don't need to travel to go to write anymore anymore like for three already get five then we like for three already get five then we don't need to go to a mystery it's a don't need to go to a mystery it's a waste of time waste of time so just return true true right when this so just return true true right when this is true these are these two must also be is true these are these two must also be true cool if left is not found then we true cool if left is not found then we try to walk to the right right the same try to walk to the right right the same if a common SS is found in the right if a common SS is found in the right tree we'll return it a true a true now tree we'll return it a true a true now what's the case now it means there's no what's the case now it means there's no common ancestry left tree or in a right common ancestry left tree or in a right tree right so for this node what will we tree right so for this node what will we do do well let's say let's say cast a speii well let's say let's say cast a speii current node has BT right coventry if it current node has BT right coventry if it has P or not has P or not it means if left has tree if let it has it means if left has tree if let it has P then it must be happy right if right P then it must be happy right if right has B then of course it's also it's has B then of course it's also it's happy or the root itself is B right happy or the root itself is B right so it's node equals B it's has P then Q so it's node equals B it's has P then Q is the same let's ask you right ask you is the same let's ask you right ask you or node equals Q now when we know for or node equals Q now when we know for this node if it has P or Q or not so if this node if it has P or Q or not so if most we has P or Q we were returned the most we has P or Q we were returned the note it's the common ancestor node right note it's the common ancestor node right so yeah true true for the other cases we so yeah true true for the other cases we return new all right it's not the common return new all right it's not the common ancestor ancestor and that we return has be and has q well and that we return has be and has q well this is a perfect recursion is done now this is a perfect recursion is done now let's return walk route I think you let's return walk route I think you should work Oh undefined okay I should review one more time before I run the code anyway let's take a look walk route okay for note if it's new or we return new or false polls its high-speed know if left has been left asked you walk left mmm cool if you found we return yeah and then we do right right happy right ask you what to write if it is right okay and then has P or has Q if we has P means let us be or rat has be or have noted selfie speed let's ask you right ask you node equals Q if SP and ask you if both P and Q are industry then I say this is that oh I think we need to return the first statement right cool yeah you're accepted and let's analyze the time and space complexity time every node out actually has been Travis for once right for space we actually this walk would be for space we actually this walk would be like three five six and then we return like three five six and then we return to five and then two although three five to five and then two although three five and five five and two six two seven two and five five and two six two seven two four and nothing is fine we got two four and nothing is fine we got two three three one and zero right the three three one and zero right the zeroes check let's try to log the note I zeroes check let's try to log the note I think it should be three five six two think it should be three five six two seven four one zero eight all the nodes seven four one zero eight all the nodes are Travis I think Oh No Wow five three seven one eight yeah so yeah for this one is linear time space while for each Travis actually we use an array to keep the result but actually the the maximum depth of the call stack would be worst linear time linear right worst is linear like the tree will be a straight line and we use this us array to store the result but this actually is we actually it's it's linear linear space there will be no nothing like if it's not it's not not like a three n right we use three but it's not because we first of all gets left and then we do the calculation so the arrays won't be recycled in linear time it's near space well I think there's another solution for this this recursion I think there was another way called like much more not much more but a little easier to easier to understand it's that for like we are going to search to was to the common ancestor of two and 0 what's the common node well for every node industry there will be a path right from the from the root to it like to there will be three four two and for a three five two four zero three one two so I think what do we need is just to search on the tree search for specific and node and get the path and then we just compare these two paths and find the common ancestor right this is another approach and try to do that its first I'll create a function to do the search search well what what we do is to will receipt you know a note as a as a as a lot as a parameter and a return what we turn the path up to the load well when we our search will of course really is recursion will well go to the root first and then go to five so we meet - we need to return as return it and and how we will collect a result we actually need to pass down the path right so actually for search there will well so if if no is what we just do the well so if if no is what we just do the return nor right the path is nor and return nor right the path is nor and then if it is not the newel then what do then if it is not the newel then what do we do we do we're first to research on the left we're first to research on the left right so cost right so cost laughs searched equals walk will search laughs searched equals walk will search node left with with what with a path node left with with what with a path contact no oh contact no oh before we searched if itself is the before we searched if itself is the target we need to return right away target we need to return right away so if node equals oh we forgot to pass a so if node equals oh we forgot to pass a target my bad if node is tuck it will target my bad if node is tuck it will return path call cut target all right return path call cut target all right Andy itself is not we search on the left Andy itself is not we search on the left but we pass a new pass a new path with but we pass a new pass a new path with the note in and then we say if left is the note in and then we say if left is found it's found in the left and we have found it's found in the left and we have the path right then we just return the the path right then we just return the path return return this if it is not path return return this if it is not found in the lab we search on the right found in the lab we search on the right oh I do it to the right right search oh I do it to the right right search pull search node right pull search node right don't forget it target target path don't forget it target target path contact no well this is the last chance contact no well this is the last chance so we were just to return right searched so we were just to return right searched so this is our search method so for P so this is our search method so for P and Q I think well path P would be and Q I think well path P would be search routes P right empty array as the search routes P right empty array as the third parameter path Q search now we third parameter path Q search now we have two paths right it's fight first have two paths right it's fight first log it mmm no we don't need so for the log it mmm no we don't need so for the path muscle business we must be have the path muscle business we must be have the same first element as the root right same first element as the root right because every path start from the root so let's say let's result B and Wow actually the common ancestor will be the last element which is the same in both paths right so for a while loop each should end that's where it should at and it should end if you end when they are not the same so while path p 0 equals half q0 when they while path p 0 equals half q0 when they are the same we set it to either one of are the same we set it to either one of them and don't forget to shift them out them and don't forget to shift them out half Q shift and finally the return the half Q shift and finally the return the result run the code result run the code seems like working for this case let's seems like working for this case let's try to submit but oh we are running out try to submit but oh we are running out of memory this is out of memory let's try analyze the time and space for time we search the worst case is out of the node so for search and then the second node Wow all of the know and we would compare your once again what's the worst case well worst case is odd of the node so it's actually triple and still in your time right for space for space let's see we use for each search we are receiving a path and I create a new path so different from the previous one when these recursion goes down from roots that leaf node the space is used the extra space a packed it will be so reference to it so you will not be recycled it won't be not not BG seed and we will this extra space will be in the whole lifetime so the worst case will be all the node are a search and the path what would will be the path wow the path would be [Music] there will be a path will be linear to the depth right so 4 4 4 1 node it will be 1 plus 2 right plus the dot plus n so it actually is N squared this is the space plus this is a cost AK plus plus linear right this is the worst case well this is why you see it says the hip is out of memory we are actually using a lot of out of memory let's try to improve it improve food search first while the problem is that we're keeping the path right this path actually should be recycled we're only searching the target there's no need to keep an extra space for each node right we just to pass the pass it down so here contact we should not use them we should use path well if this node is new or wood of course we use we return new law and and now we could just a path push the node in right now the path has no nodes so here we just return the path and the four-lap search we search on the path if lat if searched when you return it if right we we sort ass and the here if right we found in the right we return path no it should be where I've searched well it's the same reference to the path right so when left and right are all down it means actually there is there is no element there's no target with down in this pattern right so we need to go to the sibling like four five all these found audios Travis so we need good one well of course we need to do what we need to pop pop the five out right so this should work cool this submit well accept it you see for the time in a space for the time it's the same for space we're not using extra like a square you see we only use one path so this path will be actually maximum linear right so it will be linear plus the cost AK so cause so it's linear space why you see since we're using the one path wait why don't we is this better but hmm this path acne is this better but hmm this path acne this is better because search will be a this is better because search will be a standalone function without any standalone function without any dependence if you set create a global dependence if you set create a global like global path array we search we push like global path array we search we push [Music] [Music] we return true and if we return return we return true and if we return return return so actually it's the same anyway return so actually it's the same anyway let's try to write it if we if we write let's try to write it if we if we write it another way another way of global it another way another way of global path global one all right okay so let's say there is a okay we use a recursion okay mm-hmm no I'll say create a new a path empty so there's no need to path we don't pass the array if node is no of course return what if we turn but we need to return something it must be there well we could return new all no we should not return the wall we should just to return empty return empty okay and then we push on no there if no this sub is target we return the path but this is globe all right let's use slice so that when we are calling search PA search Q no no no we should we should return path if we okay I just try to do just to return to and here we return just to return to and here we return false return true return return true and when we were found this at last nothing is found so we puppet cool so this actually was stopped when the target is found so we can collect the path right so search search with P cost P plus path we slice it okay we could use path and the reset it and then serve true to Q wow this is actually a little ugly oh there's some problem we search right right target we okay so she would be so tribe we got three with push it nobody it's not target we search left target and it is target so we turn true and four three left is found we return true and search right if I searched return true if not we'll pop it so search root P and we get the path let's reset bad so such cute oh I see I see what happened this while loop cool this is another except approach but cool this is another except approach but it's kind of ugly so I'd prefer this one it's kind of ugly so I'd prefer this one pass everything needed to the recursion pass everything needed to the recursion function as a parameter this is actually function as a parameter this is actually yeah cool yeah cool so I think this is called backtracking so I think this is called backtracking we found something if we found we just we found something if we found we just returned if not it would go to next one returned if not it would go to next one but we we need to reset we said to the but we we need to reset we said to the we set the cache data which is I we set the cache data which is I remember oh I didn't remember oh I didn't oh cool I forgot to come leave the oh cool I forgot to come leave the previous solution anyway you know you previous solution anyway you know you know what I mean so this is this one chime near-space yeah so this one is uh chime near-space yeah so this one is uh I would recommend it for this kind of I would recommend it for this kind of existence check-in recursion we need to existence check-in recursion we need to we need to stop the recursion as soon as we need to stop the recursion as soon as possible so we return a fly or anything possible so we return a fly or anything to let the parent know that okay I found to let the parent know that okay I found it just to stop stop stop going to my it just to stop stop stop going to my siblings for five we found it so you siblings for five we found it so you don't need to go to one I've found it so don't need to go to one I've found it so for five it tells three with the flag for five it tells three with the flag right if you need we need to find all right if you need we need to find all the solutions it is not like this the solutions it is not like this we the parent won't listen to the child we the parent won't listen to the child we just to continue searching the we just to continue searching the siblings so this is a trick this is the siblings so this is a trick this is the technique we're using in binary technique we're using in binary I mean tree search I think hope it helps I mean tree search I think hope it helps so see you next time bye bye
2024-03-22 11:26:56
236
https://i.ytimg.com/vi/M…axresdefault.jpg
LeetCode 236. Lowest Common Ancestor of a Binary Tree | JSer - JavaScript & Algorithm
o_hVl8IXuIE
hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve the problem maximum element let's solve the problem maximum element after decreasing and rearranging so we after decreasing and rearranging so we have a pretty fair problem today and have a pretty fair problem today and that's good because I'm a bit Rusty we that's good because I'm a bit Rusty we are given an array of positive integers are given an array of positive integers and we can perform some or none and we can perform some or none operations on the array to satisfy a few operations on the array to satisfy a few conditions before we get into what conditions before we get into what conditions we need to satisfy I like to conditions we need to satisfy I like to look at the operations that are actually look at the operations that are actually available to us and that is we can available to us and that is we can rearrange the elements in any order and rearrange the elements in any order and we can also decrease the value of any we can also decrease the value of any element to be a smaller positive integer element to be a smaller positive integer we can actually perform these operations we can actually perform these operations as many times as we want after we are as many times as we want after we are done we just want to return whatever the done we just want to return whatever the maximum possible value in the array maximum possible value in the array could be after performing these could be after performing these operations now the catch is the operations now the catch is the conditions that the array has to satisfy conditions that the array has to satisfy one of them is that the array has to one of them is that the array has to start with a value of one second is that start with a value of one second is that the absolute difference between any two the absolute difference between any two adjacent numbers has to be at most one adjacent numbers has to be at most one so in this case it is at most one for so in this case it is at most one for all of the adjacent pairs now if I make all of the adjacent pairs now if I make a couple values equal it's still true a couple values equal it's still true like the maximum absolute difference like the maximum absolute difference between these is less than or equal to between these is less than or equal to one and it has to be at most one so that one and it has to be at most one so that works the very first thing you might works the very first thing you might think is well if the first element is think is well if the first element is one and the values kind of have to be one and the values kind of have to be consecutive well can we just take the consecutive well can we just take the length the array and return that as like length the array and return that as like the max number because we're starting at the max number because we're starting at one and we're going to be kind of doing one and we're going to be kind of doing plus one each time no we can't do that plus one each time no we can't do that and this example kind of shows you why and this example kind of shows you why because this is a valid array and even because this is a valid array and even the first example here shows you why the first example here shows you why because here we are given these numbers because here we are given these numbers and we can rearrange them in sorted and we can rearrange them in sorted order like this 1 1 2 2 2 now it's order like this 1 1 2 2 2 now it's perfectly valid and we can't make the perfectly valid and we can't make the maximum number in this array any bigger maximum number in this array any bigger because remember remember we can't because remember remember we can't increase the value of a number we can increase the value of a number we can only decrease it so in my opinion this only decrease it so in my opinion this problem isn't super complicated the problem isn't super complicated the hardest part about this problem is hardest part about this problem is really making sure you understand all of really making sure you understand all of the requirements that you don't miss the requirements that you don't miss anything so with all of that in mind it anything so with all of that in mind it seems like sorting the array is seems like sorting the array is definitely helpful because we know that definitely helpful because we know that the array must start with one and if we the array must start with one and if we sort the array it'll be pretty sort the array it'll be pretty straightforward for us to know if we straightforward for us to know if we have at least a one or maybe we have have at least a one or maybe we have something greater than a one we can't something greater than a one we can't possibly have anything less than a one possibly have anything less than a one cuz the integers are positive so don't cuz the integers are positive so don't make make sure not to miss that and make make sure not to miss that and obviously the fact that we want to obviously the fact that we want to arrange them in such a way that adjacent arrange them in such a way that adjacent values have a difference of at most less values have a difference of at most less than or equal to one and the best order than or equal to one and the best order to put the values in to ensure that to put the values in to ensure that would be in sorted order so once we have would be in sorted order so once we have that though once we have the elements in that though once we have the elements in sorted order what do we do next well sorted order what do we do next well let's just run through it without even let's just run through it without even thinking about the code let's just thinking about the code let's just manually solve the problem okay we start manually solve the problem okay we start with a one that's good because if this with a one that's good because if this was greater than a one suppose it was a was greater than a one suppose it was a two we would have to decrease it down to two we would have to decrease it down to a one and it's not like we'd have to a one and it's not like we'd have to count that as an operation because we count that as an operation because we don't care how many operations we don't care how many operations we perform we just want to basically get perform we just want to basically get these values in an order that satisfies these values in an order that satisfies these conditions so that's good so far these conditions so that's good so far now we have a two well let's compare it now we have a two well let's compare it with the previous guy the difference is with the previous guy the difference is definitely less than or equal to one so definitely less than or equal to one so this is good so far now we have five this is good so far now we have five here now We compare these two the here now We compare these two the difference is definitely not less than difference is definitely not less than or equal to one so we have to change or equal to one so we have to change this number because we can't change this this number because we can't change this we can't increase this we have to we can't increase this we have to decrease this how much are we going to decrease this how much are we going to decrease it by we actually have two decrease it by we actually have two choices believe it or not we can if we choices believe it or not we can if we want to make it a two or we can make it want to make it a two or we can make it a three both would be perfectly valid a three both would be perfectly valid but which one do you think is going to but which one do you think is going to lead to a maximum possible value in the lead to a maximum possible value in the array probably the bigger one right so array probably the bigger one right so that's what we do we make this a three that's what we do we make this a three and now we're here we compare seven not and now we're here we compare seven not with five We compare it with three and with five We compare it with three and we check is the difference between 3 and we check is the difference between 3 and 7 less than or equal to 1 nope it's not 7 less than or equal to 1 nope it's not so now again we have those two choices so now again we have those two choices we can make this a three or a four and we can make this a three or a four and of course we're going to make it four so of course we're going to make it four so that's how you solve this problem with that's how you solve this problem with kind of just like manually by hand now kind of just like manually by hand now what's the pattern that you noticed in what's the pattern that you noticed in terms of code well we only like every terms of code well we only like every time we look at a value we only need to time we look at a value we only need to keep track of what the previous value keep track of what the previous value was that's like the first thing to was that's like the first thing to notice and second is when we do decide notice and second is when we do decide to make this element smaller we always to make this element smaller we always set it and actually that's not super set it and actually that's not super obvious yet let me change this example obvious yet let me change this example slightly to illustrate the second Point slightly to illustrate the second Point let's make this a two and now a two now let's make this a two and now a two now what do we do these two are good now what do we do these two are good now when we get here what's the difference when we get here what's the difference between these two it is less than or between these two it is less than or equal to one so we can't decrease this equal to one so we can't decrease this there would be no reason to do that and there would be no reason to do that and we can't increase it we can't make it a we can't increase it we can't make it a three unfortunately so we leave them as three unfortunately so we leave them as is and when we get here we do the same is and when we get here we do the same thing these two are equal so that's fine thing these two are equal so that's fine and now we're done this was the largest and now we're done this was the largest value the last value is pretty much value the last value is pretty much always going to be the largest value so always going to be the largest value so now what do you notice about what we're now what do you notice about what we're doing to this second one well it's not doing to this second one well it's not super obvious but we're always taking it super obvious but we're always taking it and setting it to the minimum of the and setting it to the minimum of the previous Value Plus One or the current previous Value Plus One or the current value let's just call that array at value let's just call that array at index I the reason we're doing this is index I the reason we're doing this is because in cases of a tie we would need because in cases of a tie we would need it to be set to the value that it itself it to be set to the value that it itself is but in cases where this value is is but in cases where this value is bigger something like a seven we're bigger something like a seven we're going to set it now equal to the going to set it now equal to the previous value which is 2 + 1 so then it previous value which is 2 + 1 so then it would be a three so that's where I'm would be a three so that's where I'm getting this formula from that is pretty getting this formula from that is pretty much all we need to code this up now in much all we need to code this up now in terms of time complexity yes we are terms of time complexity yes we are doing a linear scan but before we do doing a linear scan but before we do that we are sorting the array so the that we are sorting the array so the time complexity is going to be Big O N time complexity is going to be Big O N log n so now let's code it up so first log n so now let's code it up so first thing I'm going to do is just sort the thing I'm going to do is just sort the array and and then we are going to start array and and then we are going to start iterating over the array so for n in the iterating over the array so for n in the array we are going to do that minimum array we are going to do that minimum formula but we actually do not need to formula but we actually do not need to modify this array because remember how I modify this array because remember how I said we only are keeping track of the said we only are keeping track of the previous element so instead of actually previous element so instead of actually modifying the array in place I'm just modifying the array in place I'm just going to keep track of the previous going to keep track of the previous element and by the time we finish the element and by the time we finish the entire array we can just return that entire array we can just return that previous element because like I said the previous element because like I said the last value in the array is going to be last value in the array is going to be the return value it's going to be the the return value it's going to be the greatest in the array so what should we greatest in the array so what should we initialize this to before I even do that initialize this to before I even do that let's just write out the formula let's just write out the formula previous is equal to the minimum of previous is equal to the minimum of previous + 1 and the current value that previous + 1 and the current value that we're at in this array this is the we're at in this array this is the formula remember but why are we formula remember but why are we assigning it to previous because we're assigning it to previous because we're taking the previous number because sort taking the previous number because sort of in this context this is the current of in this context this is the current number and we want to populate this for number and we want to populate this for the next iteration of the loop so that's the next iteration of the loop so that's why I'm assigning it to this variable why I'm assigning it to this variable but this is kind of the tricky part but this is kind of the tricky part because remember how they said the array because remember how they said the array has to start at one so if it doesn't has to start at one so if it doesn't start at one suppose it starts at two we start at one suppose it starts at two we would want this formula to evaluate to would want this formula to evaluate to one so how can we do that well think of one so how can we do that well think of it like this we are given an array and it like this we are given an array and to the left of that array we're just to the left of that array we're just kind of putting an implicit zero there kind of putting an implicit zero there we're just assuming that there is a zero we're just assuming that there is a zero that comes for all of these values in that comes for all of these values in sorted order so that's why I'm going to sorted order so that's why I'm going to set previous equal to zero because it set previous equal to zero because it will ensure that this 0 + 1 evaluates to will ensure that this 0 + 1 evaluates to one so if this number is bigger if it's one so if this number is bigger if it's a two this will evaluate to one and then a two this will evaluate to one and then this will sort of be one as well so this will sort of be one as well so that's pretty much the entire idea of that's pretty much the entire idea of this problem that's the code so now this problem that's the code so now let's run it to make sure that it works let's run it to make sure that it works and as you can see yes it does and it's and as you can see yes it does and it's pretty efficient if you found this pretty efficient if you found this helpful please like And subscribe if helpful please like And subscribe if you're preparing for coding interviews you're preparing for coding interviews check out N.O got some cool features check out N.O got some cool features coming and a new course launching coming and a new course launching probably tomorrow thanks for watching probably tomorrow thanks for watching and I'll see you soon
2024-03-25 10:25:34
1,846
https://i.ytimg.com/vi/o…axresdefault.jpg
Maximum Element After Decreasing and Rearranging - Leetcode 1846 - Python
nYLSDwlWzq0
hey what's up guys this is chung here so let's take a look at last problem of so let's take a look at last problem of this week's weekly contest which is this week's weekly contest which is number 1675 number 1675 minimize deviation in array minimize deviation in array it's very interesting it's very interesting i would say it's a math related problem i would say it's a math related problem basically you're given like an array basically you're given like an array numbers of n numbers of n positive integers right and then for positive integers right and then for each of the each of the integers you can perform you can perform any of any of those two operations if the element is even you can divide it by two if the element is odd and then the deviation is the array and then the deviation is the array basically the deviation is the maximum basically the deviation is the maximum difference difference between between any two elements in this array basically the deviation is the max is the difference between the maximum number and the smallest number in this array after this after this operations and it asks you to return the minimum deviation minimum deviation among all those kind minimum deviation among all those kind of of results right so and here are some results right so and here are some examples here examples here so let's say we have one two three four so let's say we have one two three four and and uh as you guys can see so the current uh as you guys can see so the current deviation for this one is three right deviation for this one is three right which is four minus one which is four minus one is three but if we divided four is three but if we divided four if we divide four by two then we have we if we divide four by two then we have we have one two have one two three three two right then the deviation three three two right then the deviation is what is is 2. but then we can we can continue increase the this i increase i by basically double multiply two with resistance with this one here which we have two two three two and then finally we have the our final answer which is three minus two is one so that's the the first examples and similar for this second example here we increase this one to two and we we increase this one to two and we decrease this 20 decrease this 20 to five right and then the final answer to five right and then the final answer is is three so so for this problem you know the uh since we have two ways you know so if you if you make some observations right basically if this number is even it means that it cannot be increased anymore so because the even number can only be divided by two which is can only which means that an even number can only become smaller same thing for out number odd number so an odd number cannot become smaller he it can only become a greater by by multiplying with two right so and since we have these two options to maintain these two options at the to maintain these two options at the same time right same time right operations at the same time so the way operations at the same time so the way we're solving this problem is that we we're solving this problem is that we have to fix have to fix one of those problems or one of those uh one of those problems or one of those uh conditions and then we would conditions and then we would we'll either would either through we'll either would either through we'll try to let's say if we fix the uh and then we'll and then and then we'll and then would basically will try to decrease the would basically will try to decrease the uh uh the maximum values right and if we fix the maximum values right and if we fix the uh the the smallest values and then we'll try to increase the smallest values either way it's fine so base and the way i'm doing here is basically i'm going to i'm going to maintain like a priority queue which will stores the uh which will and then i do it by initializing by and then i do it by initializing by uh by converts each number to its biggest numbers first so which means that you know if this number is like is a even numbers then it's already at its maximum values then i'll just simply insert into that priority queue but if it is odd numbers as i can just uh so with this number the the maximum number for this out number will be uh will be outnumbered times two that's going to be the the maximum value for this number right and then i do this after after the first four loop here i have a priority with with all the with all the biggest numbers for each of the digits right and then in the front from here i'll be i'll try to uh basically decrease the maximum numbers from this priority queue right by by half while maintaining the minimum number and then when we uh then what's going to and then when we uh then what's going to be the be the the exit point the exit point which means that you know we're we're which means that you know we're we're trying to trying to we keep trying we keep uh decreasing the we keep trying we keep uh decreasing the uh uh the maximum values by by getting the the maximum values by by getting the current maximum value from this priority current maximum value from this priority queue queue right and then let's see if the the right and then let's see if the the current biggest number current biggest number from this priority queue is the even from this priority queue is the even numbers and then we know okay so numbers and then we know okay so we can simply uh do a divided by two we can simply uh do a divided by two because we know we we can because we know we we can we can decrease we can change the the we can decrease we can change the the current maximum values by current maximum values by by dividing this current max value by 2 by dividing this current max value by 2 and then we'll push that the new value and then we'll push that the new value back to the priority queue back to the priority queue but if the current max number from the but if the current max number from the product queue is product queue is even numbers let's say if it is seven even numbers let's say if it is seven then we know okay so there's no way we then we know okay so there's no way we can decrease seven because for every can decrease seven because for every seven seven we can only we can only multiply by two we can only we can only multiply by two then we can simply break the while loop then we can simply break the while loop but if this is six and then we'll just but if this is six and then we'll just we can simply uh we can simply uh divide it by three and then we will just divide it by three and then we will just uh divide it by two uh divide it by two now we have three and then we'll push now we have three and then we'll push this three back to the priority queue this three back to the priority queue and every time when we have a new and every time when we have a new numbers here we'll also uh like update numbers here we'll also uh like update the minimum values the minimum values because that's how we uh we get our we because that's how we uh we get our we get get the the current deviation of the uh i know i don't know if i explains clear i know i don't know if i explains clear enough but uh maybe i'll try to enough but uh maybe i'll try to explain a little bit more so like i said explain a little bit more so like i said you know you know the priority queue here right i'm the priority queue here right i'm maintaining like the the current maintaining like the the current the current maximum numbers the current maximum numbers the current max numbers for the for this the current max numbers for the for this array array right i'm using the prior queue because right i'm using the prior queue because that's the priority will only take a that's the priority will only take a long long log n time to update the current max log n time to update the current max number number right so and and i'm also right so and and i'm also i also need to maintain like the minimum i also need to maintain like the minimum numbers right so numbers right so i'm for the minimum numbers i'm just i'm for the minimum numbers i'm just going to use like system going to use like system i'm just going to use the uh variables i'm just going to use the uh variables to maintain that so at the beginnings i'm i'm going to convert each of the the digits number to its biggest biggest possible values and then i'll push it into the priority queue so that i'm sure i have the uh i have the maximum values for all the possible for all the possible uh numbers by doing these two kind of operations and from there i can just safely try to decrease that max numbers and then while maintaining the the deviations right the minimum number and plus the deviation so in nums so if the num divided by two equal to zero which means these are even numbers then we can simply uh i'll just do a heap q dot heap push right priority q and i'll just simply push this number because we i know that's going to be the the answer the sorry that's going to be the max value for this for this num and then i also um else right else it's a odd number else right else it's a odd number which means we we need to multiply the which means we we need to multiply the number by two number by two if we push if we push dot priority q dot num dot priority q dot num times two oh by the way sorry so since times two oh by the way sorry so since i'm maintaining i'm maintaining i need the maximum value from this i need the maximum value from this particular but in python this product particular but in python this product by default it only can give us the by default it only can give us the minimum numbers that's why minimum numbers that's why i need to do a minus i need to i need to do a minus i need to reverse this the signal at the sign reverse this the signal at the sign for this number so that the priority for this number so that the priority will give us the uh the biggest number will give us the uh the biggest number right same thing for this thing i'm also right same thing for this thing i'm also going to going to maintain the minimum dot maintain the minimum dot now the number is num times two right now the number is num times two right that's going to be the that's going to be the so now after this after the uh so now after this after the uh this first while loop here the priority this first while loop here the priority queue queue probably zero right the product of zero probably zero right the product of zero and the minus and the minus right of course minus priority zero will right of course minus priority zero will be be the the biggest not the biggest possible the the biggest not the biggest possible numbers right numbers right for this for this uh for this nums here for this for this uh for this nums here and then all we need to do is that just and then all we need to do is that just that we will just try to uh that we will just try to uh decrease that number right decrease that number right one by one so i'm going to have answer one by one so i'm going to have answer equals the system dot equals the system dot max size and then the uh while the particle is not empty right we have current so the current is what is the uh the minus uh the heap q dot heap pop right because this is going to be the current max so every time when we pop that out right so every time when we pop that out right we'll update we'll update the answer right answer the answer right answer dot is going to be the minimum of the dot is going to be the minimum of the answer answer dot current dot current minus the minimum right minus the minimum right this is the current our current this is the current our current deviation because the current one is the deviation because the current one is the current current maximum and the minimum of course is the maximum and the minimum of course is the current minimum current minimum and then if the current and then if the current divided by two is not empty right divided by two is not empty right it's not it's not zero it don't we know it's not it's not zero it don't we know that the current is odd number that the current is odd number odd number means that there's no way we odd number means that there's no way we can can continue we can decrease our mac the continue we can decrease our mac the current max number anymore right and current max number anymore right and then we can simply do a break here then we can simply do a break here otherwise hip hip dot priority q and then we dot priority q and then we do a minus current divided by two right do a minus current divided by two right and then and then after that we don't forget to max to after that we don't forget to max to update minimum update minimum right minimum is the minimum dot minimum right minimum is the minimum dot minimum current divided by two right current divided by two right and then in the end we simply return the and then in the end we simply return the answer oh here oh here okay if i submit yeah okay so it's passed right so how about the time complexity right so the time complexity i think for this part is pretty straightforward that's just o of n so we can ignore this part so the most significant running times right it's right here i mean the so the way we're defining this we're calculating this thing is like this let's say we have we have n here right so n is the length of of of nums here and is the length the length of of nums since we're doing like this current by since we're doing like this current by two right let's say the two right let's say the the max the max m is max of the m is max of the of the numbers how many i mean how many numbers we will how many i mean how many numbers we will be be they will will be putting into the they will will be putting into the priority queue so we will have at most at most we'll uh uh so for each number so anyway so the so for each number so anyway so the worst case scenario worst case scenario each number will be putting into this each number will be putting into this will be put into this priority queue will be put into this priority queue one time right and for each numbers we one time right and for each numbers we have n have n here right and each number it will be here right and each number it will be decreased decreased decreased i mean by half decreased i mean by half and then it will basically push back to and then it will basically push back to this product queue again so that's going this product queue again so that's going to be what to be what n times log m n times log m right so that's the uh the total numbers right so that's the uh the total numbers the total number of elements the total number of elements we will be pushing back will be pushed we will be pushing back will be pushed into this priority queue because we have into this priority queue because we have we have n numbers we have n numbers and each number can have up to log m and each number can have up to log m i mean new push i mean new push right and then right and then then the uh so the last one is what the then the uh so the last one is what the last one is the last one is the uh within the while loop we have like uh within the while loop we have like the the the heap pop and heap push right and the heap pop and heap push right and each of this will take what will take each of this will take what will take log end time log end time right because the worst case scenario right because the worst case scenario will have n in its priority q will have n in its priority q and then this the uh the hip hop and he and then this the uh the hip hop and he hit push will also both take a log n so hit push will also both take a log n so that's why that's why the total time complexity is this the total time complexity is this it's n times log m times log n right and it's n times log m times log n right and space is what space is just o of n space is what space is just o of n because we will just have this particle because we will just have this particle which would which would take like at most o in space yeah i think that's it i mean i think this problem is pretty tricky because you know the uh we you have to find out the uh how can you how can you fix one side basically right you have to fix either the minimum possible values for all those numbers or the maximum possible values of for all those numbers in this case i use the maximum possible numbers and then once you have that one you can try to decrease you can try to decrease that that max numbers one by one right while maintaining while maintaining the uh the minimum number along the way uh yeah i think that's it for this uh yeah i think that's it for this problem and problem and thank you so much for watching this thank you so much for watching this video guys and stay tuned video guys and stay tuned see you guys soon bye
2024-03-20 10:56:06
1,675
https://i.ytimg.com/vi/n…axresdefault.jpg
LeetCode 1675. Minimize Deviation in Array
fIOZkIH5PZU
hey what's up guys this is jung so today uh let's take a look at lead so today uh let's take a look at lead code problem code problem number 664 stringed printer number 664 stringed printer so this one is a very interesting so this one is a very interesting problem problem so you're given like a stringed printer so you're given like a stringed printer and the printer follows and the printer follows following two special requirements so following two special requirements so the first one is that printer can the first one is that printer can only print a sequence a sequence of the only print a sequence a sequence of the same characters each time same characters each time and second you know at each turn right and second you know at each turn right the printer can print new characters the printer can print new characters at any of the locations and then it will at any of the locations and then it will cover cover the original existing characters which the original existing characters which means that it's going to overwrite means that it's going to overwrite the uh the existing characters the uh the existing characters so and here are some examples right so so and here are some examples right so we have examples we have examples one here right here we have the target one here right here we have the target is aaa is aaa bbb oh sorry and here bbb oh sorry and here you ask your job is to count find the you ask your job is to count find the minimum number of turns the print turns minimum number of turns the print turns so that we can get the uh this input the so that we can get the uh this input the the final answer and in example one here right we have a and bbb so the final answer is two why is that because i mean there are like different uh multiple approaches for this one so the explanation this one gives you is to print the three a's all together and then print b after this right and another option is like to what we print six a's in total and second time we we print three b's starting from here right so this will also give us the uh the the same result here and the example two here right so we have like uh aba right so in this case uh i think it's kind of obvious that it's obvious that so we print three a's first and then the next the next turn we just print one b right in the middle that's why we got uh we got a two here and so there's a hint he says the length of the given stream will not exceed what exceed 100. so actually this one is a very pretty strong hint right it means that you know the time complexity for this problem but okay we can we can just ignore this but okay we can we can just ignore this one for now but one for now but so let's let's think about the strategy so let's let's think about the strategy right right i mean at the first glance this problem i mean at the first glance this problem is i think it's really is i think it's really kind of uh confu a little bit confusing kind of uh confu a little bit confusing and hard to and hard to get the point right because they're like get the point right because they're like different ways right we we can print different ways right we we can print any letters any same sequence of letters any letters any same sequence of letters at any locations at any locations so how can we how can we approach to the so how can we how can we approach to the final answer final answer i mean i think one of the ways i mean i think one of the ways to approach this kind of problem or not to approach this kind of problem or not you know what you know what especially when you don't have any clues especially when you don't have any clues is that you know is that you know maybe try to try to find just the stupid maybe try to try to find just the stupid just the worst way or the stupidest or just the worst way or the stupidest or the most naive way to print the most naive way to print this result so what's the most naive way this result so what's the most naive way to print this to print this the result that is we print the letters the result that is we print the letters one by one one by one right so for example we have we have an right so for example we have we have an aba here so the the first time we pre aba here so the the first time we pre we print a second time we print b we print a second time we print b third time with print a and this will third time with print a and this will always guarantee always guarantee us we can we can print out the final us we can we can print out the final answer right and answer right and but this will not give us the the best but this will not give us the the best the minimum the minimum turns so from there on turns so from there on from here i think the next thing is that from here i think the next thing is that you know you know how can we uh improve this how can we uh improve this to find a better strategy actually i to find a better strategy actually i think the the example two here think the the example two here it's a pretty it's a pretty good example it's a pretty it's a pretty good example that can that can it's kind of obvious to us that you know it's kind of obvious to us that you know is is if we have multiple numbers right if we have multiple numbers right uh multiple like letters uh multiple like letters for have the same letters i think for have the same letters i think the approach is that we we may want to the approach is that we we may want to print those letters first so what i mean is that you know the uh so we have a let's say we have a a xx right then so let's say we have another a here right um yeah so it doesn't really matter like what the others uh letters are at the moment so i'll oh let's take a look at these two letters here so we have two a's so what what's a better strategies other than print the letters what uh one by one is this what is right we'll try to print all a's here right we'll try to print all a's here because in this case we can cover right because in this case we can cover right we can cover we can cover the uh basically we can get two a's the uh basically we can get two a's in one turn and then the remaining parts in one turn and then the remaining parts is that we just give it to the uh is that we just give it to the uh and then the next one the next one will and then the next one the next one will try to print the try to print the the remaining parts whatever whatever it's left right what's what average left right in the middle and then we have another parts here that's that's the remaining parts we also need and at this moment i think for i think and at this moment i think for i think it's it's we can define like a dp here right so we can define like a dp here right so the dpij the dpij means from means from i to j i to j the minimum turns right the minimum turns right print print from i to j the minimum turns what's the minimum turn to print the the so so for the state transition function so so for the state transition function right the uh you know right the uh you know so this one is obviously the the most so this one is obviously the the most important one so which means that you important one so which means that you know we have a dpij know we have a dpij equals to what equals to the uh i let's say that i let's say that here we have a k right i j here we have a k right i j k minus 1 k minus 1 plus d p k plus 1 to 2 j the second part is kind of obvious right because we have we need to print them anyway that's that's the k plus 1 to j so for the first part um so what k minus 1 is also obvious but y i right y i not right i think some some people some some right i think some some people some some of you may have the question is that you of you may have the question is that you know know okay since our maybe our our strategy is okay since our maybe our our strategy is to print to print uh this aaa first right and then we'll uh this aaa first right and then we'll try to print try to print the the middle one so why not the the middle one so why not have like a dp of i plus one k minus one have like a dp of i plus one k minus one and then plot and then plot plus one right so that's gonna be uh plus one right so that's gonna be uh maybe and that's another valid state maybe and that's another valid state transition function transition function but that's not percent but that's not percent true so why why is that because you know true so why why is that because you know let's say we have like okay yeah here's let's say we have like okay yeah here's a good example a good example we have a aaa let's say from a to eight we have a aaa let's say from a to eight they're they're like they're all a's so let's say the uh like they're all a's so let's say the uh the those four axes there are they're the those four axes there are they're all a's all a's so let's we have i and j here right so let's we have i and j here right so if we're using like this kind of dp i so if we're using like this kind of dp i plus one plus one right i plus one k uh right i plus one k uh k minus one and then we do a we do a k minus one and then we do a we do a plus one plus one in the end so we have this one basically in the end so we have this one basically we're seeing okay we're assuming we're we're seeing okay we're assuming we're going to print two eighths two eight going to print two eighths two eight that's gonna take one turn and then that's gonna take one turn and then we're gonna try to print we're gonna try to print the the middle ones right but either the the middle ones right but either keep doing this a here so what we have keep doing this a here so what we have we will have instead of we will have instead of one here we'll have like maybe three one here we'll have like maybe three because actually for all a's because actually for all a's the what's the gonna be down so for the what's the gonna be down so for that's gonna be one because all we need that's gonna be one because all we need is to is to print it once because we can cover up print it once because we can cover up all these kind of scenarios all these kind of scenarios of sorry other letters but if this our of sorry other letters but if this our state transition function is something state transition function is something like like dpi plus 1 k minus 1 plus 1 dpi plus 1 k minus 1 plus 1 basically that's not always the case no basically that's not always the case no it makes sense you know if the uh if the it makes sense you know if the uh if the number is something number is something if the if the the lighters in the middle if the if the the lighters in the middle is something like a b is something like a b c d d a i'm sorry c d d a i'm sorry b b d c right so if that's the case b b d c right so if that's the case you know so this i plus 1 k minus 1 plus you know so this i plus 1 k minus 1 plus 1 1 seems fine right but that's but seems fine right but that's but but that's only covers some some cases but that's only covers some some cases but for not not all cases but for not not all cases that's why we cannot define a state that's why we cannot define a state transition function like this transition function like this because we have like this kind of uh aaa because we have like this kind of uh aaa case okay so case okay so that's why the way we're defining the that's why the way we're defining the state transition function is that you state transition function is that you know it's like this so we're not considering that plot plus one because we don't know we don't know if that will be an additional turn for sure or not so what we what we can say is that you know since this a and a they are the same right so to to print from i to j is equivalent to print from i sorry from i to k is equivalent to print from because you know it's kind of obvious because you know it's kind of obvious right because we have another a right because we have another a next to k minus one if we take like next to k minus one if we take like let's say let's say three three times to print from i to k three three times to print from i to k minus one minus one so we should also extend we should also so we should also extend we should also print another a print another a until k because this a and a they're the until k because this a and a they're the same so we same so we should like uh cover this a i mean should like uh cover this a i mean as well that's what these are like the as well that's what these are like the the dpi k the dpi k minus one means you know since we're minus one means you know since we're defining this defining this uh state transition function like in uh state transition function like in this way and we can this way and we can cover this case right as you you guys cover this case right as you you guys can see here right so can see here right so to print the print this a to a is to print the print this a to a is equivalent equivalent it's the same as to print this a to to it's the same as to print this a to to this a this a and then this one is the same as from to and then this one is the same as from to this a to to this a and then this a to to this a and then to here to here to to here to here to to to here right and in the end to to here right and in the end we only have one that's why this state we only have one that's why this state transition function works and yeah i think that's basically going to be our state transition function and this this part is kind of obvious only the only thing the only thing we need to be careful is that you know k minus one might be uh greater than j right so let's say if the a is in the end right so if x so if if here if we have a here so then then there's not there's nothing uh next to a here so this this part should be zero right so we can just simply do a check yeah and that's basically the state transition function and like i said you know that's only the scenario when we have like a matching letters with the same i here that then we can use this state transition function right what if there's no a's at all what if there's nothing to be to be matched with a how how to handle that case right because here we're saying that okay we're we're saying we have we have a k somewhere uh okay i like after i hear after i hear there's a k so that we can uh we can split this dp but what if there's no there's no another a at all then what's gonna be that how about that one so for that one we're going to be a 1 plus or i plus 1 sorry i plus i plus one two to j sorry i plus i plus one two to j so this one means that you know the uh so this one means that you know the uh if there's if there's no uh matching letters for the eye no uh matching letters for the eye sliders sliders then we we have no other options but to then we we have no other options but to print these sliders print these sliders by itself so print by printing the by itself so print by printing the letters by itself letters by itself we have one right and the remaining we have one right and the remaining since we're only printing these one since we're only printing these one letters letters the remaining the remaining string is the remaining the remaining string is from i plus one to j yeah so that's basically the final stage transition function here cool so and so we have n right equals cool so and so we have n right equals the length of s here the length of s here and then we're going to define a dp and then we're going to define a dp right so dp right so dp since we're getting the minimum i'm since we're getting the minimum i'm going to initialize everything to this going to initialize everything to this uh to the max system maximum uh to the max system maximum for it's going to be a a two for it's going to be a a two dimensional uh array here right dimensional uh array here right and oh i think one one thing i i didn't and oh i think one one thing i i didn't have to mention that have to mention that is that there are some base cases is that there are some base cases so the base case is like if there's only so the base case is like if there's only one letters one letters right it doesn't really matter what right it doesn't really matter what letter it is so it's going to be always letter it is so it's going to be always one turn to print that letter one turn to print that letter that's why that's why we can initialize that's why that's why we can initialize some some basic cases here basically from i basic cases here basically from i from from 0 to n here we can always from from 0 to n here we can always initialize the dp initialize the dp i to i with to the value 1 so means that i to i with to the value 1 so means that you know to print each letter you know to print each letter separately we always need one turn separately we always need one turn okay so basically that's okay so basically that's we have a we have already handled all we have a we have already handled all the length equals the length equals equals to one case now we can basically equals to one case now we can basically start start looping through from length too looping through from length too okay oh by the way so okay oh by the way so the this looping the outer loop is the the this looping the outer loop is the length is a common technique length is a common technique if we want to uh loop through the uh if we want to uh loop through the uh all the combinations for like the range all the combinations for like the range i i to j basically from the outer loop to j basically from the outer loop is the uh is the length for the is the uh is the length for the for the string i and j and then the for the string i and j and then the inner loop we can simply do a we can inner loop we can simply do a we can simply simply loop through i from n minus loop through i from n minus l plus one that's going to be all the l plus one that's going to be all the possible possible uh locations for i with the length with uh locations for i with the length with the length the length l and then we can easily calculate l and then we can easily calculate j gonna be i plus l j gonna be i plus l minus one okay minus one okay and like i said so the first case is the and like i said so the first case is the first one is to print first one is to print print ice letter separate separately so so if that's the case we're gonna have like two for j equals to l plus sorry dp i plus one j and then we plus one i mean like like i mean like i said you know we can we we can check if there's anything uh matching the ice ladders uh and then we can have like if outs but another way of doing this is like we're always assuming we have we can print this letter separately that can cover that case so later on we can just use this one to compare to get as a base case to get the the minimum result so now the next thing is that for k in range of i plus one sorry i couldn't hear what you said and so here the reason i do i i plus one and so here the reason i do i i plus one is because let's say we have is because let's say we have a here right so we have another one a here right so we have another one since we have already considered the uh since we have already considered the uh to print the isolator separately case to print the isolator separately case now the next one like i said we need to now the next one like i said we need to find another matching ace find another matching ace after a right other than a here that's after a right other than a here that's why we have to start from why we have to start from this is i right that's why we need to this is i right that's why we need to start from i plus one start from i plus one and we stop from to the j and we stop from to the j so if the ice i is equal to the sk so if the ice i is equal to the sk then we just do the state transition then we just do the state transition function function dpi j is going to be a minimum of dp dpi j is going to be a minimum of dp i j dp i j dp i k minus 1 right i k minus 1 right plus dpr plus dpr k plus 1 j right k plus 1 j right but like i said since the k plus 1 could but like i said since the k plus 1 could be greater than j here be greater than j here so we can sim we can simply have like a so we can sim we can simply have like a if else track here so which means that if else track here so which means that uh we do this if j is greater than k uh we do this if j is greater than k right else zero yep and so here in the end we simply return the dp 0 to n minus 1. that's our meaning for the entire string what's the minimum turns we need to print yep so let's try to run the code yep so let's try to run the code so this will accept it let's submit so this will accept it let's submit oh yeah this there's a special case oh yeah this there's a special case which means that which means that um if not s right so we simply return um if not s right so we simply return zero zero yep um yeah so it passed and yeah i mean for the time complexity i think i thought i think we have already uh i'll talk about that it's going to be a 12n cube because we have a three nested four loop here um yeah i think that's pretty much for this problem you know i mean i think to be honest this one is pretty it's gonna be a little bit tricky to come up with the state transition functions right and also uh you have to be you have to be inside for exciteful enough to to notice that you know we have a different scenarios and also how can you uh do this state transition function so that you can handle this like uh all a cases yeah they're like a bit several corner cases you you need to you need to cover and yeah just to recap right so we we start we start with trying to build the strings uh like naively by uh printing the letters one one by one and then along the way we we figure out if we have a two letters that are are the same so we we should print all them together that's that's uh dp i j equals to dpi k minus one case uh dp i j equals to dpi k minus one case and then the this the second part is and then the this the second part is it's all kind of obvious it's all kind of obvious and and another common technique is for and and another common technique is for this kind of this kind of state uh problem is that you know for state uh problem is that you know for for dpi and j for dpi and j we always uh gonna we always uh gonna basically tr try all the possible uh basically tr try all the possible uh uh split points right you know on this uh split points right you know on this uh uh in this range and then we try to split in this range and then we try to split them into two parts them into two parts and then among others about all those and then among others about all those possible splits we'll either get a possible splits we'll either get a minimum or a maximum so in the end we'll minimum or a maximum so in the end we'll just need to just need to return the dp from start to to the end yeah cool i think that's pretty much i want to talk about for this problem and yeah thank you for watching this video guys stay tuned see you guys soon
2024-03-20 15:41:27
664
https://i.ytimg.com/vi/f…axresdefault.jpg
LeetCode 664. Strange Printer
fDeZNRNmm1Y
That Lakshya Khan Today's List Problem Admit Card Number 90 700 Savre Minimum The Card Number 90 700 Savre Minimum The Latest Word Problems But Most Minimal Is The Minimum Element Of Savre The History Contact Us Given Here For All Facts About Animals And Wonders From Which It Is To Find All The Service Of Governor Thoughts Thoughts Thoughts In In Every Element Has To Be Right Next To Every Element Has To Be Right Next To Not One Element From Side To Side With [Music] 12542 It's 12542 It's First To Understand What You Want To Know First To Understand What You Want To Know 200 Latest 200 Latest Effect Three Years Old Is After All The Effect Three Years Old Is After All The Observer Research Start Reel Vikas December Observer Research Start Reel Vikas December Place Fix Soe Three Layer Pendant Three One Aged Tarzan The Same For For Mouni Mouni Benefit Hai And This Video Back Disha And Dasha Bales Matter Pending Set Up Till Element Superhit Sample Survey More More Suit For The Atharva That suzy add all of them together and in this manner with all the way from the beginning death That suzy add all of them together and in this manner with all the way from the beginning death that do you notice any pattern in the stability updated on that is find a pile real you might see pattern the Can Can Can this example set the latest clock the this example set the latest clock the last row message send a great for all last row message send a great for all disha balance idea and tagged disha balance idea and tagged 400 you see the results problem share button 400 you see the results problem share button oneplus oneplus two plus oneplus oneplus two plus two plus on star plus two plus on star plus 200 oneplus oneplus two might be coming from here 200 oneplus oneplus two might be coming from here And for class 4 is the additional And for class 4 is the additional but some rate is problem relation between hadis dros but some rate is problem relation between hadis dros my latest write to understand what du place all about us the software consulting also service idea and tagged aap article number and jobs which are is so is is so is is so is Is The Number 10 Loop Four Indies Series The Previous Song Again For What Is The Best Place For Abs Envelopes Envelopes 2.25 Subscribe To My Channel Subscribe To My Channel Subscribe To My Channel Switch Off 's Split Sample In at 4 p.m. Wear Look Two In at 4 p.m. how to is the previous less amount of and other results which were getting mirwaiz contributed by all the service under-21 but what about the service thought did after 2 and before unfolding of and improvement friends our is 540 ki and k noddy previous less amount For its 2nd semester adapter to for dam male enhancement minimum amount exploited 5.44 many more shampoo same that is the subscribe 2 years in this forest and understand your mother that and they can probably due to formula of wealth Bhatt of fod result of and is Bhatt of fod result of and is Bhatt of fod result of and is equal to result of two result of two plus equal to result of two result of two plus 4 - 200th comments from forest current 4 - 200th comments from forest current tax to is the end of the previous multiply multiply the current amount I let channel like this I let channel like this one super element came one super element came we define result we define result we define result Character Of Previous And To Subscribe School A Plus I - Index Of Previous Lives Or Equivalent To Any Previous Cases For Here And To That Aap Sonth Or Hair And To Here And Will Be Multiplied By Different Elements Volume This amount results from the previous This amount results from the previous This amount results from the previous minimum balance amount to be minimum balance amount to be Additional Services Minimum Here we get the previous Lewis and Equal Element Wikinews Method of Monotonic Talk on a Sumo Tonic Stock Is We Special Can Talk Over All Elements of Also Also Also Increase In And This Crack Between The Marine Increase In And This Crack Between The Marine The Amazing Strictly Non Decreasing The Amazing Strictly Non Decreasing Order Order I'm Soft And Foreign Information We Can Go To Are I'm Soft And Foreign Information We Can Go To Are Coding Panels And Start Your Day Coding Panels And Start Your Day With Solution Bluetooth Dance Super Walking Dead Solution Beach Sexual To-Do Super Walking Dead Solution Beach Sexual To-Do List Of Previous Loops In Taxes List Of Previous Loops In Taxes List Of Previous Loops In Taxes every index india rep 200 first form and create tarf previous luis are any length office are this gandu se mess are not length initially amphitheaters - 1the means for every element the different previous less indexes guddu minus one main tera buddhu should also in a slice of Result is a result there was born in phir bhi result for every morning depending dad I think so you are reminded in this country is not liked and reminded in this country is not liked and felt s05 default felt s05 default that hindi and water uniform total sum of that hindi and water uniform total sum of result is good to love answer result is good to love answer a love a love a love Distance Guddu Monotonic Do It Suji Monotonic Tag Cloud Calculate The Best Places In Some For That Neetu Run Life Through All The And Listen And Listen That Dainik Vilaval Bhai Loop Insight And That Dainik Vilaval Bhai Loop Insight And Improve Will Run As Long As This Tag Is Improve Will Run As Long As This Tag Is Improve Will Run As Long As This Tag Is condition number one and five one to front on Vivo defined the a talent which included in this element edit of forest at a you slept yr balance side effect stock and strike on length minus one that sex that is great and share my brothers condition Start vape potion morning popping latent adhi element end stop this track is great dane air off side this current element swift everything what we will all the all the writer of the i just just night we element which means i just just night we element which means this is the condition subject this is the condition subject this is the condition subject loop slow state topper on thursday was nav third is point bread current element the current extra is 200 finally they dress hall you should be over will have a list of previous less elements and caused by default vitamin Minus one two judgment switch don't have Minus one two judgment switch don't have Minus one two judgment switch don't have previously this elements which are already a previously this elements which are already a day minimum set the index level day day minimum set the index level day will have - 1st previous index will have - 1st previous index and tell what is left a tour of all above and tell what is left a tour of all above cross the length of the year cross the length of the year nov20 election hair oil length nov20 election hair oil length that end that end that end That And Those Criminal Formula Data Ego And Prevention Tips Time To Get An Election Result Of A Good Result Of The Amazing Eclipse Id That That Dad Glass Of Water Should Support In The World Are Indians In The Previous Loop Latest Current wali hai hua tha kya pata tha and finally Bigg Boss returning the total of 10 result are surat dot s u cleared the exams page and monitor ok shuddh resham ok shuddh resham [music] [music] mein aa typo mein aa typo Pray for Pray for Pray for example test cases example test cases this day walking five lakhs after mid-day that all right it's not working why ok chup vikas abhi 128 motor radhe-radhe gyan sansar should be model of radhe-radhe gyan sansar should be model of india 272 hai yaar seriously model project on Effect of How To Connect With Girls Name Slightly Different Subscribe Thanks Alot First Time With Subscribe Thanks Alot First Time With Me This Point Please Like Subscribe And
2024-03-25 10:33:39
907
https://i.ytimg.com/vi/f…axresdefault.jpg
Sum of Subarray Minimums | O(n) with Monotonic Stack | Dynamic Programming
EKZhEN9P2-I
hey what's up guys this is chung here uh so this is chung here uh so this time uh let's take a look at this time uh let's take a look at another lead code problem 1353 maximum number of events that can be attended right so basically you're given an array of events with the start and end the time and you can attend an event i at any day where the start time i basically if this as a current date if this event is still still in progress right and but remember that you can only attend one event at a particular day here return the maximum number of events you can attend right so obviously this is another segment tree problem right basically you're given like a different segment and you need to do something you need to do something to come up with a result right so usually when you do a segment tree problem you know it's very it's a very common way of doing it you either sort by the start time or stored by the end time right but in this case let's take a look right so what's what does this one what said what's the difference uh about this problem right what's the difference is that you know most of the or the other segmentaries problem as long as you're doing something let's say you're in the middle of this meeting one you cannot do the same you cannot do medium two or meeting three until the meeting one's finished right but in that in this case that's the difference that's the different places here let's say you start from one here right at day day one here but it's day two right okay uh yes day one day two yes okay so from day one you you attend meeting one right and from from day two uh from day two you uh you're but you're still in meeting one right but in this case you can you can jump you can go to meet meeting two as long as you stay at that meeting for one day it doesn't really matter so at meeting at day two here you can join meeting two and at day three you can join uh meeting three so in this case you can jump you can join three meetings uh i'm gonna yeah let's try let's take a look at this this problem okay okay so let's take a look at this example two so let's take a look at this example two here here there's one there's one one and two right event one two and three right one two two and three right one two two three and even four right it's one and two and even four right it's one and two again right right so this is day one right so to right one two right one two three and four right so three and four right so in this case let's say we're on day one in this case let's say we're on day one right where day one we can pick any of right where day one we can pick any of this this even one or even four to uh to attend even one or even four to uh to attend right right and then on day two right let's say on and then on day two right let's say on day two what kind of options do we have day two what kind of options do we have right on day two let's say let's assume right on day two let's say let's assume let's let's let's assume we take that we on day one let's assume we take that we on day one we uh we uh we attend uh event one right and we attend uh event one right and then on day two we have two options here then on day two we have two options here right we have we we can either join we can either attend event two or event 4 right because both of those events they are they're in the range of the in the range of of day 2 right but which one do we want to we want to attend right it's obvious right we want to attend which at the event whichever ends the earliest right i think that's kind of like a greedy uh idea here so every time right so basically since we're going to loop through the uh the days one by one right because we want to know what's the the biggest event we can attend so that's why we need to loop through the days one by one here basically on each day right on each day we check on this day what is the current ongoing ongoing or what in progress meetings right and among those meetings we just get the uh attend the earliest one the no the one that ends the earliest right and then on the on second day on the third on the day three we'll see okay what are the available meetings uh on day in day three right and we just keep doing it because every time we just greedily always attend the meeting that's ends the earliest so that it's kind of intuitive right because we want to end uh attend a meeting that ends first then we can then we have the other we have chance because otherwise if we take the meetings ends er later and then the ones and and earlier might be already finished so that we won't have the chance to take to attend a meeting so that's why every time when we have when we we have we can uh sorry so when we can join the meeting on the day we always try to join the median that ends earliest i mean basically before it's finished right and then for the ones that will be ending later we'll we'll try to join them later on the later day if they finish then that that's fine because we couldn't join those at the same day right um yeah so so first uh since we're going to uh join the meetings one day one day day per day by day right so we need first we need to sort the events by the uh by the start date right and then and then on each day right on each day we'll get all the available meetings when i say available i mean the all the ongoing meetings on this day right and then we'll try to get the ones who ends the earliest how do we do that right we it's we can use in that case we need to sort that those events by the uh by those like available meetings in the in the ascending order right so which which means we will be using a priority queue because in the priority queue the first the first one will be the ones the first one is always the smallest right that's a basically minimum heap right and then every time when we see a new day here we'll add all the available meetings to that priority queue and then we'll just pop that meetings from the top right every time we can pop a medium from the top it means that okay we're turning a new medium right basically then we'll be uh adding our uh final answers by one and in the end we just return that that okay so let me try to okay so let me try to code these things here so first code these things here so first uh like i said first thing is that we uh like i said first thing is that we need to sort need to sort by the uh by the first element right i think if we sort by the first element we don't even need to specify the key here i think we can do a key here lambda lambda x uh x zero right i think the default one will also also sort by the first one but anyway i'll just do this so and like i said uh we'll be uh like looping through each of the day here right so uh i'll try to get total days here total days total days will be the the biggest one total days will be the the biggest one from the end date right that's our total from the end date right that's our total days of all the events days of all the events right it's going to be uh event right it's going to be uh event uh maximum yeah it's going to be array uh maximum yeah it's going to be array here right here right events event sorry event one right events event sorry event one right that'll be the that'll be the end date for event end date for event uh in ring in sorry in events uh in ring in sorry in events right so that that will be our total right so that that will be our total days here we'll just do a uh you know we can do a for loop here uh we can do a for loop to loop through each of the day here right but in in that case we'll be having some uh we'll do we'll be doing some unnecessary uh things here let's say let's say if there's a gap right let's say there's a event one here and then the event two is somewhere here right let's say there's some gap days here right then we'll be uh we'll be keep doing the for loop here uh let's see so instead so what we'll be doing is we'll be using a while loop here so that we can skip some we can fast forward the days right if there's a gap here because we because with a for loop we have to loop the element one by one at least in python so and then we're gonna do we're gonna have a date right day equals to zero and then basically while right while days so let's see what we are doing here we so let's see what we are doing here we are we are oh yeah sorry uh we also need like to create a priority queue priority queue uh this right to store the uh the current uh in improv in progress medians right so basically if right now i'll write this like logic from this here right if the priority q has has some values right and then we just do we know we can we cannot attend the meeting right answer uh from zero right and then we do what we just uh basically we just our append uh the uh we'll just attend that meeting right so when we attend the meetings basically we'll just pop right pop that uh sorry keep hip q dots heap pop right basically will pop that meeting from the queue because that that means the meeting is gone right we don't have to attend it anymore and then we pass answer increase answer return answer here okay the other one before doing that like i s like i what i we discussed we need to add right we need to add all the uh right so basically for the current day right while right while basically for we need to loop through the the event right we don't need to loop through the event by uh if if the start date if the start date is smaller than than the current date and then we know okay the current event is in the has already started right let's see the event date let's see the event date um yeah i think also since we don't want to for each day right we don't want to uh uh look through the event from the beginning right since we look through the event we loop those two events with a sequence then we can have like a index right because because as long as we add this because because as long as we add this event to our priority queue uh there's event to our priority queue uh there's no need for us no need for us to uh to loop through the events to uh to loop through the events again right because it's already in that again right because it's already in that priority queue we know priority queue we know we we have already processed that right we we have already processed that right so that we can have like we need to have so that we can have like we need to have an index of the after an index of the after the next basically the the next the next basically the the next uh event right we can have like index uh event right we can have like index here here index right to have zero instead of zero index right to have zero instead of zero here here that will tell us from the in the next that will tell us from the in the next day right day right we we can only we only need to check we we can only we only need to check from that index from that index of the event right we don't have to go of the event right we don't have to go from the very from the very very beginning here so basically while very beginning here so basically while what about the uh uh the events right the events of index the index of the of the start time right if it's uh smaller before or smaller or equal to the current date right that means uh is in the uh right so we just add priority queues not right so we just add priority queues not priority queue priority queue uh heap q dot heap uh heap q dot heap uh push right and this uh push right and this priority queue sorry this priority queue priority queue sorry this priority queue uh so we'll be adding the uh so we'll be adding the what's that the the end time right what's that the the end time right to this event to this uh priority queue to this event to this uh priority queue that that events uh events uh index and one right and then that's that so we only uh so now after adding this thing here we also need to remove discard all the events have been because remember this priority queue because remember this priority queue only stores for the current day right on only stores for the current day right on the current day what's the the current day what's the in progress events right and then we can in progress events right and then we can ensure ensure we we can if we only store that and then we we can if we only store that and then we know the first one will be the one we we know the first one will be the one we uh uh we want to uh attend right if we don't we want to uh attend right if we don't discard because when we move discard because when we move to the next day it's possible that some to the next day it's possible that some of the events which we have of the events which we have had already been pushed into this had already been pushed into this priority queue may have priority queue may have had already finished right if we leave had already finished right if we leave those those uh finished event in the priority queue uh finished event in the priority queue and then when we try to and then when we try to attend that event if we don't remove attend that event if we don't remove them we might have them we might have end up uh ending attending an event end up uh ending attending an event which had already been which had already been ended right so that's why on the on each ended right so that's why on the on each day day besides adding new available besides adding new available uh events to this like priority queues uh events to this like priority queues we also need to remove right we also need to remove right well that's basically uh while well that's basically uh while uh event sorry well priority queue right uh event sorry well priority queue right the zero well zero is like what the zero well zero is like what if zero has remembered if zero has remembered in the priority queue we stores the end in the priority queue we stores the end event right so if the end event right so if the end event is is smaller right event is is smaller right then the uh than the the current day then the uh than the the current day then current date right that means then current date right that means we uh um um and since this this is the priority and since this this is the priority queue right queue right so p q 0 will always be the smallest so p q 0 will always be the smallest basically the pq 0 will always be the basically the pq 0 will always be the earliest and the time of all the events earliest and the time of all the events in this priority queue that's why we can in this priority queue that's why we can do a while loop right to check do a while loop right to check if any of the queue in this in this if any of the queue in this in this priority queue has already been priority queue has already been has already ended right then we can just has already ended right then we can just pop that thing we can just pop that thing we can just do a what we do uh do a what we do uh uh hip q uh hip q dot hip pop right so basically we just dot hip pop right so basically we just pop that thing pop that thing because that's how we discard the because that's how we discard the scar ended event right scar ended event right so here we're adding a so here we're adding a uh in uh in progress event progress event right um day right i think we need to do some check here so i think we need to do some check here so while well pq right uh sorry while well pq right uh sorry while p q if the priority queue while p q if the priority queue has a value end right and this thing has has a value end right and this thing has it's like otherwise we'll have like a it's like otherwise we'll have like a exception here and here exception here and here uh this thing here while uh this thing here while index right because after we add this index right because after we add this thing here we'll be thing here we'll be basically moving the index by one right basically moving the index by one right and then since we're every time we're and then since we're every time we're moving to the moving to the end in case we're moving this index to end in case we're moving this index to the very last one right so let's do a the very last one right so let's do a well index uh is less than the uh well index uh is less than the uh otherwise if we reach the end that will otherwise if we reach the end that will still plus one the next time this still plus one the next time this event index will be out of bound out of event index will be out of bound out of bound right bound right less than a length length of events and let's see i think this should okay let's see if this will work okay let's see if this will work cool oh sorry yeah this top thing we need to use the pre the passing the the race cool yeah basically this thing works right i yeah basically this thing works right i mean mean it works anyway so the the thing is we it works anyway so the the thing is we we can do some we can do some uh simple improvements here like i said uh simple improvements here like i said uh uh yeah i actually i didn't uh fast forward yeah i actually i didn't uh fast forward these things these things let's say if there is like let's say if there is like um basically if there's a gap right if um basically if there's a gap right if there's a gap which means if the there's a gap which means if the priority queue priority queue is not it's like it's empty right if the is not it's like it's empty right if the priority queue is empty priority queue is empty what do we do we just uh fast forward we what do we do we just uh fast forward we can fast forward this day can fast forward this day to uh to the next available uh to uh to the next available uh to the next available events right to the next available events right basically that would be the next basically that would be the next available event will be the index right available event will be the index right it'll be indexed it'll be indexed with other of the current next next with other of the current next next event right event right will be an index uh sorry events will be an index uh sorry events event index uh of the start right that's event index uh of the start right that's the thing the thing uh here so we also need to check if uh here so we also need to check if index right is smaller than the length index right is smaller than the length of of events and events and and not right basically if there's and not right basically if there's not nothing in the in the priority queue not nothing in the in the priority queue that means that means we got nothing to do on this day right we got nothing to do on this day right so we can we don't so we can we don't we don't we don't need to uh uh fast we don't we don't need to uh uh fast forward a day one by one we can just forward a day one by one we can just fast forward to the next available event fast forward to the next available event but this is like a minor stuff here but this is like a minor stuff here you know it's it's optional i think i you know it's it's optional i think i think this thing still think this thing still should still work yeah it still works it doesn't give us a lot of improvements but this thing is like optional here option so basically basically the the key idea here is that well first we need to loop through uh on each day and on each day we uh we first we use this priority queue to store all the uh the in progress meeting the way we we're doing it because we are the way we we're doing it because we are we're basically we're looking through we're basically we're looking through all the all the other the events starting from that from other the events starting from that from from this current from this current indexes and if that in indexes and if that in event start time start date is event start time start date is smaller it's earlier than the current smaller it's earlier than the current date then we know okay date then we know okay this meeting should be this event should this meeting should be this event should still still be in progress on this day right be in progress on this day right and then besides this one we also will and then besides this one we also will need to discard right the ended events need to discard right the ended events and then once this two step is finished and then once this two step is finished then we know all we have left in this then we know all we have left in this priority queue priority queue are the the candidates right the are the the candidates right the candidates candidates on this day that we can attend right oh so sorry so and this one more thing oh so sorry so and this one more thing is it index it will also make make sure is it index it will also make make sure we'll we'll we won't be attending the previous we won't be attending the previous previously already attended meeting previously already attended meeting in this case right because and in this case right because and we always we only add these things uh we always we only add these things uh once right and every time we attend the once right and every time we attend the meetings meetings we are we pop we pop this meeting we are we pop we pop this meeting basically we remove this basically we remove this attended meeting from this priority attended meeting from this priority queue so that will queue so that will that can make sure that can make sure we're not attending the meetings twice we're not attending the meetings twice right right and then we are basically back to this and then we are basically back to this if statement if statement so now the priority queue was so now the priority queue was will have will store the events will have will store the events that we have which we haven't attended that we have which we haven't attended but uh are still but uh are still in progress and then from all those in progress and then from all those available uh available uh those valid candidates from those candidates we will pick the the ones that will be ending the earliest right then we'll increase the answer by one and in the end we just do a day plus one right and just uh okay cool i think that's pretty much all about this problem yeah okay i hope you guys enjoy this video and thank you so much for watching it and i'll be seeing i'll be seeing you guys
2024-03-21 00:28:05
1,353
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 1353. Maximum Number of Events That Can Be Attended
b937EQjirbw
let's read out the question quickly try to resolve it and put list two in their place the blue and put list two in their place the blue edge and notes in the following figure edge and notes in the following figure indicate the result indicate the result okay [Music] what they do is zeros to five okay is 3 B is 4 list 2 is this 2 2 fine okay I got this 26 seconds so what it said it will there will be so what it said it will there will be three parameters sorry four parameters three parameters sorry four parameters list one and list two so there are two list one and list two so there are two lists to be received will receive a a lists to be received will receive a a and b as an integer value which and b as an integer value which indicates in the list one that indicates in the list one that uh which all notes needs to be removed uh which all notes needs to be removed and and basically needs to be replaced and and basically needs to be replaced with a list two so what it says a to a25 with a list two so what it says a to a25 O from a sorry two to five so it's from O from a sorry two to five so it's from 2 to 5 we need to remove this in this 2 to 5 we need to remove this in this example so answer will and this will be example so answer will and this will be replaced with list two so 0 1 then list replaced with list two so 0 1 then list two two okay this is how it starts so what it says at least one that length by fourth a will be greater than one and less than equals to B list one dot minus one okay a or b a zero or one provider the RMA a or b a zero or one provider the RMA starts list this one foreign foreign it's too big thanks again thanks again A minus A minus one one is is foreign hey hey foreign B is also for less than equal to 4 yes Point third dot next I'll do list two Point third dot next I'll do list two again yeah Dot [Music] 2 0 1 2 or at least 2 then 5. 012 list for example discretion zero one two is two then five two or five zero one any list two then six zero one any list two then six zero one two is two zero one two is two and six oops 61 out of 61 test cases [Music] [Music] thank you thank you [Music]
2024-03-20 10:36:18
1,669
https://i.ytimg.com/vi/b…axresdefault.jpg
Leetcode Problem 1669 Solution | Merge In Between Linked Lists | Explanation in Hinglish
k5XhK94R1Pg
Hello friends today I am solving liquid problem number 222 count complete three problem number 222 count complete three notes Here we are given root of a notes Here we are given root of a complete binary tree and we need to complete binary tree and we need to return the number of nodes in that tree return the number of nodes in that tree a complete binary tree is a tree where a complete binary tree is a tree where um the tree has a two children except um the tree has a two children except the last last level and the second last the last last level and the second last level where the last level are the leaf level where the last level are the leaf nodes with no children at all and the nodes with no children at all and the second last level may have second last level may have um um one or no children at all and one or no children at all and um all the child notes all the leaf um all the child notes all the leaf notes are notes are towards the left as possible so here we towards the left as possible so here we know we can see that that uh root note know we can see that that uh root note here has two children and the SEC and here has two children and the SEC and this is the second last level this level this is the second last level this level has this one has two children this one has this one has two children this one has only one child right and the re all has only one child right and the re all the leaf notes are towards the left as the leaf notes are towards the left as much as possible so uh basically the much as possible so uh basically the left uh tree is uh kind of like always left uh tree is uh kind of like always feel if the right tree feel if the right tree has at least one node has at least one node um um so we need to find now the number of so we need to find now the number of nodes in this tree and what cons the nodes in this tree and what cons the constraint that we are given is that we constraint that we are given is that we need to find in less than o of n time need to find in less than o of n time complexity well complexity well um in of and time complexity which is a um in of and time complexity which is a linear time complexity we could just linear time complexity we could just easily do that by traversing each of easily do that by traversing each of these node one by one using a DFS these node one by one using a DFS solution but since we need to find a a solution but since we need to find a a solution with less than that o of n solution with less than that o of n Which is less than linear time Which is less than linear time complexity so complexity so uh well for that solution to identify we uh well for that solution to identify we need to know uh like need to know uh like features of complete binary tree so let features of complete binary tree so let me just show you here me just show you here in any uh given level at any given in any uh given level at any given height height the root node is in the range water the root node is in the range water repair Edge and root nodes at last level repair Edge and root nodes at last level is is at this is is at this um is included inclusive of um is included inclusive of uh inclusive in this range so at this uh inclusive in this range so at this height height at this height so basically this is at at this height so basically this is at height zero this is our height one and height zero this is our height one and this is at height two this is at height two so in this height the number of notes is so in this height the number of notes is from zero one two two to the power of from zero one two two to the power of two right which is equals to four so two right which is equals to four so basically it's from one to four basically it's from one to four uh these are inclusive uh these are inclusive um um so similarly in this level as well now so similarly in this level as well now we know that if the tree is filled which we know that if the tree is filled which means that in a given level the tree has means that in a given level the tree has all the notes all the notes um nodes so the ha the number of nodes um nodes so the ha the number of nodes in that level is equals to 2 to the in that level is equals to 2 to the power of the height which is here equals power of the height which is here equals to 2 to the power 1 which is equals to 2 to 2 to the power 1 which is equals to 2 right so similarly in this case it's 2 right so similarly in this case it's 2 to the power of 0 which is equals to one to the power of 0 which is equals to one if we had uh one on one more node here if we had uh one on one more node here then the number of nodes here would be 2 then the number of nodes here would be 2 to the power of to the power of um um an H which is the height equals to two an H which is the height equals to two so it would be four so basically what we so it would be four so basically what we need to do is we need to find uh need to do is we need to find uh a tree such that the left a tree such that the left uh uh we need to find um we need to find a tree it could be a sub tree here such that the left the height to the left and the height to the right are equal only in that case um the number of nodes will be equals to the height of that tree node right um so here since the height is not equal so what we do is now we divide our um uh whole problem into sub problems that is we divide our tree into two halves so um now I go to the left half and then find the height the height here is equals to one the height towards this also is equals to one so what I do is um I find the level of these uh of these notes which is equals to one right depth of this node is equals to one um and that and the depth of this node is equals to zero for this sub tree for this sub tree the left depth is equals to one so once I find the depth here um uh I can know the number of nodes here is to the power of n which is equals to two and then since um I'm also taking the root node into consideration this node into consideration so I'll add a 1 here um and in similarly I'm gonna do the same in this case but here the left um left height and the right height is not equal right so I go to the left and then this this becomes my new sub tree and the height here is um equals to zero so 2 to the power of 0 equals to one so the number of note count here is one and here there is no node so it's zero so basically when I return back here I add it I add a 1 to the result um so the total number of nodes here will be close to two and then here I found the total number of nodes equals three I go back here I add a 1 to the result from the left note and from the right node so my total number of nodes is equals to 1 plus 3 plus 2 equals to six here now let me show you a case where um I have uh one One More Level here so suppose I have one more node here then I have a few more notes here so basically these trees are full as well so this sub Dan what I do is for this note Dan what I do is for this note um I found the find the left um I found the find the left um height in the right sub tree height um height in the right sub tree height so to find the height so to find the height um I move towards this note and then I um I move towards this note and then I go downwards so I calculate the number go downwards so I calculate the number of steps so basically I'm Moving Two of steps so basically I'm Moving Two Steps right so this is at height two and Steps right so this is at height two and this is at high two one and this is at this is at high two one and this is at height zero height zero so now to calculate the number of notes so now to calculate the number of notes at height 2 x 2 to the power 2 which is at height 2 x 2 to the power 2 which is equals to four and then uh now I know equals to four and then uh now I know that I have that I have two more parents two more parents okay so I have parent notes Here uh which but uh the number of count is equals to two right so initially if you remember I had um for this level I just did to the power one plus one and that gave me the total number of nodes in this sub tree but for this sub tree where I do to the power 2 which gives me the number of notes here and then only just doing one doesn't give me the total number of notes in this whole foreign so basically I'm gonna change this whole algorithm this whole calculation to 2 to um n plus 1 to the power of h plus 1 um n plus 1 to the power of h plus 1 minus one so what happens here is now my minus one so what happens here is now my height here is two so I do to the power height here is two so I do to the power of 2 plus 1 which is equals to 3 here of 2 plus 1 which is equals to 3 here which gives me a value which gives me a value um 8 and then I subtract a 1 from that um 8 and then I subtract a 1 from that so what I get is a seven so E7 the so what I get is a seven so E7 the number of counts here let's see I have number of counts here let's see I have four notes Here four five six and a four notes Here four five six and a seven yeah seven is the number of count seven yeah seven is the number of count here here so that that this will be the formula so that that this will be the formula that I'm gonna use that I'm gonna use so now let's dive into our code um so what I need is first of all I need to check if the root note is equals to I return a zero I return a zero and then I need to calculate the and then I need to calculate the not height of not height of left sub tree and and left and then cool uh so to calculate the height I cool uh so to calculate the height I actually need a actually need a function height and I pass the node and then I also check if equals no okay if not return a zero return a zero eels uh the height equals to one for eels uh the height equals to one for this node and then for each this node and then for each of the next node I'm just going to pass move to the next node and increment my height so basically for each of the next note I am increasing my height and then finally return my height okay it's basically not the next note but the um yeah so side will be either left or yeah so side will be either left or right right and then finally once I get the and then finally once I get the um height left height so this is um height left height so this is basically the high toes left and the basically the high toes left and the heights towards the right these are not heights towards the right these are not equal here if they were equal height if those were equal then I would return the number of nodes in that sub tree which would be equals to to the power of height plus 1 minus 1 right so what I'm gonna do I'm gonna do here is a bitwise operator so I'm gonna use bitwise operator so I'm gonna use bitwise operator so this bitwise operator will actually this bitwise operator will actually um uh is actually a power of two so um like in bitwise operate in bits one when I move um shift towards the right uh basically um I'm adding a zero so this is equivalent to two right and when it's 100 it's equivalent to the power 2 which is equals to four and so so the number of zeros I add to the bitwise operator is equals to the powers of equivalent to the that many powers of two so I'm just doing that thing here using bitwise operator if not if the height is not equal then um I'm just gonna um do a recursive calls I'm gonna divide the whole uh problem into solve problems so I'm gonna divide this into these two sub problems so the number of counts of this node plus the number of Counts from this sub tree plus a one so this one here is for the root note Plus the number of count of the uh the number of count of the right sub the number of count of the right sub tree will be my final result so tree will be my final result so let's run our code uh okay I just defined this let it's not uh okay I just defined this let it's not good if so talking about the time complexity here um since what I'm doing is I'm only traversing either towards the left or towards the right so my whole uh whole um problem is divided into two every single time so for this note my problem is divided into two right into this half and this half for this one it's divided into two so every time my problem is divided into two so for this one so basically it's log off and for first division for the second division is log off and so in total it's log of n hopefully that was useful helpful thank hopefully that was useful helpful thank you
2024-03-22 10:54:25
222
https://i.ytimg.com/vi/k…axresdefault.jpg
222. Count Complete Tree Nodes | JavaScript | LeetCode Daily Challenge | Detailed Explanation
OnSn2XEQ4MY
everyone welcome back and let's write some more neat code today so today let's some more neat code today so today let's solve a pretty easy and popular question solve a pretty easy and popular question invert binary search tree so all they invert binary search tree so all they tell us to do tell us to do is invert a binary tree and what exactly is invert a binary tree and what exactly does that mean does that mean so let's say that this is our initial so let's say that this is our initial tree tree to invert it is basically what you can to invert it is basically what you can tell tell in the output right so the root stayed in the output right so the root stayed the same but you can see it's two the same but you can see it's two children which were left child two left children which were left child two left or right child seven or right child seven were swapped right so seven is now on were swapped right so seven is now on the other side the other side two has been moved right so basically we two has been moved right so basically we took these took these and then we swapped them and when they and then we swapped them and when they say invert the binary tree it's a say invert the binary tree it's a recursive definition so take a look at recursive definition so take a look at this this subtree right you can see since we moved subtree right you can see since we moved it to this side that's where it is it to this side that's where it is right but notice how even these sub right but notice how even these sub trees trees are are different now right one was are are different now right one was initially on the left and three was initially on the left and three was initially on the right initially on the right but now three is on the left and one is but now three is on the left and one is on the right on the right the exact same thing happened with this the exact same thing happened with this tree right it was moved tree right it was moved over here to the left side but then over here to the left side but then its children were also swapped right so its children were also swapped right so nine nine was moved to the left six to the right was moved to the left six to the right so when they say so when they say invert the binary tree what we're saying invert the binary tree what we're saying is is visit every single node in the tree visit every single node in the tree right right and every time we visit a node take a and every time we visit a node take a look at its look at its two children and swap the positions two children and swap the positions of the children right so in other words of the children right so in other words if we're given a if we're given a tree look at the root node and take its tree look at the root node and take its children and then swap the positions and children and then swap the positions and then then recursively run inver binaries recursively run inver binaries or invert tree on the left subtree and or invert tree on the left subtree and run invert on the right subtree so it's run invert on the right subtree so it's a recursive definition a recursive definition so we can solve this problem with so we can solve this problem with recursion we can do recursion we can do a depth first search whether it's a depth first search whether it's pre-order or post pre-order or post order it doesn't actually matter a depth order it doesn't actually matter a depth first search will first search will allow us to solve this problem allow us to solve this problem recursively so this problem would recursively so this problem would probably be a lot more annoying probably be a lot more annoying if it were iterative but luckily we can if it were iterative but luckily we can do it recursively so do it recursively so we can first check the base case so if we can first check the base case so if the root is null the root is null then we can return null we don't have to then we can return null we don't have to continue continue otherwise what we're going to do is swap otherwise what we're going to do is swap the children the children so we're going to save the left value so we're going to save the left value root.left in a temporary variable then root.left in a temporary variable then we're going to we're going to replace the root.left value with replace the root.left value with root.right root.right and then we're going to replace the and then we're going to replace the root.right value with the left value root.right value with the left value which we know is now which we know is now stored in temp so after we swap the stored in temp so after we swap the nodes nodes all we have to do is now recursively all we have to do is now recursively invert the invert the subtrees so we can invert the left subtrees so we can invert the left subtree subtree and then we can invert the right subtree and then we can invert the right subtree so by doing self.invert tree what we're so by doing self.invert tree what we're doing is making a recursive call to the doing is making a recursive call to the function we're inside function we're inside and once we have swapped the roots and once we have swapped the roots children once we have inverted the left children once we have inverted the left subtree and subtree and inverted the right subtree we know we're inverted the right subtree we know we're finished so then we can return the root finished so then we can return the root so there it is this problem is a so there it is this problem is a relatively short code it's a very good relatively short code it's a very good problem to kind of understand the basics problem to kind of understand the basics of of depth first search and tree problems in depth first search and tree problems in general and it's actually a pretty general and it's actually a pretty popular problem popular problem and if you weren't able to solve this on and if you weren't able to solve this on your first try don't feel too bad take a your first try don't feel too bad take a look at this trivia look at this trivia there was a very good engineer who there was a very good engineer who actually failed this problem in their actually failed this problem in their google interview google interview but his career still turned out pretty but his career still turned out pretty fine so i hope this was helpful fine so i hope this was helpful if it was please like and subscribe it if it was please like and subscribe it supports the channel supports the channel a lot and i'll hopefully see you pretty a lot and i'll hopefully see you pretty soon
2024-03-22 11:01:36
226
https://i.ytimg.com/vi_w…xresdefault.webp
Invert Binary Tree - Depth First Search - Leetcode 226
QLir9JbD6Mw
yo Chuck what the Chuck is up YouTube in this video we're going to be going over leak code 287 find the duplicate number the thing that stands out to me about this problem is the constraints are pretty intense so we start with an array of integers containing n+ one integers in the range of one to n inclusive so what does that mean in English that means if the highest value in our array is four we're going to have five elements in our array so that would look like this so we here we have four as our highest value and then notice we have five elements because of the pigeon hole property which states that if we have X amount of pigeons and there's not enough holes to fill those pigeons then we know we're going to have an intersection or a duplicate value in this case it could be two it could be two On's for instance and the array is probably not going to be sorted as with the problem statement here but just know that there's always going to be a duplicate value likewise if the highest value in our numbered array was five we would have six elements in our array so something like this six elements um we wouldn't actually have a six because remember we're just going to one to n inclusive so that would be where we would slide in our duplicate value okay so that is how the numbering system works here and how that is explained notice also with our constraints we're unable to modify the array of nums so we can't sort this list of numbers to help us find the duplicate that's going to make it a lot harder also we can only use constant extra space which means we can't make make another array to for instance we couldn't just scan our numbers and then push our duplicate into another array for instance and return that uh newly created array so that also makes it quite challenging okay with that said I'm going to show you the trick to this problem there is a definitive trick and let's go over and hop to the code right now all right so you see I've copied the function from the problem and we have a array and it looks like gets duplicated on the value three so how are we going to approach this problem well the way you need to approach it is you need to set a pointer to fast and a pointer to slow so what I'm going to do is just make a variable called slow initially set it to index zero and then also make a pointer called Fast and set that to zero as well the idea behind this problem is you're going to have a slow pointer which traverses your array one node at a time and then you're going to have a fast pointer that traverses two nodes at a time so when I say node I'm just referring to an index of your array so I'm going to make a while loop and I'll set it to some um condition that will always be true and I'm just going to update the values of my pointers in this function so I'll say slow equals nums at slow and then fast will Traverse two nodes whereas slow is just traversing one node fast will Traverse two so notice I'm doing the same thing but then now I'm actually passing the value of that first uh node traversal into my indices or my index and that's going to make me go twice as fast okay and then I'm going to say if slow equals fast I want to break okay let's run this code and I'm actually going to return slow just to see what it is and let me clear this because I was messing around earlier but let me just run this code and it looks like we're coming across three on the number that we meet at let's make sure that fast is also three okay so what does this mean they both equal three but what what does that mean well the the again the slow pointer is traversing one node at a time and the fast pointer is Travers traversing two nodes at a time conceptually it's pretty easy to understand how the slow node is progressing through our array but it might be kind of confusing to understand how the fast uh pointer is traversing so I want to write it out for a [Applause] second so imagine we start at zero with both pointers slow is going to be one at index zero right and then fast is going to be one at index zero but then it's actually going to be two because we're traversing two nodes and that's that nested uh index value we have here so we start at one because we're at index zero with both pointers but fast will actually take the value of that initial um zero index zero and then go to the next one over which is two because two is at index one so that's kind of tricky but you can kind of you can kind of see the logic there so let's keep going so now we're at Value one at slow if I go to index one that's actually two now so I'm going to go to two fast I'm I'm starting at index two which is 01 two that's four and then now I'm going to go to four index four which is three right here so I could say three and then slow I'm starting at index two so 0 one two which is four I'll say four and fast I'm starting at index three which is three again and then I'm going to three which is three so I'm just notice I'm I'm kind of like stuck on three now with the fast pointer and I'm going to start at index 4 with slow so if I go 0er 1 2 3 4 that looks like it's three and then with fast I start at index three so 0 1 2 3 and then three is telling me to go to three again so I'll be at three so 0 1 to three which is also three so at this point they're equal to each other and we're going to break out out of the loop so let's console log that to prove that this actually happened so I'm going log slow and pass in the value of the log slow and pass in the value of the slow and then also fast and pass in the slow and then also fast and pass in the value of fast so if I run this value of fast so if I run this code you can see the logic we just had code you can see the logic we just had it's it's um it's not showing you the it's it's um it's not showing you the last transformation but if I put the last transformation but if I put the console log statement down here you can see where we align right so what's happened here is we've actually created a cycle and or a loop this problem is called Floyd's cycle or you get it's called like the tortoise toris and hair I don't know that's probably not how you spell tortoise but it's it's a known problem where you end up having a loop and these values will keep looping um Forever on each other because there's a the pigeon hole problem like we talked about before where because there's a duplicate value in this um uh length of array remember our max value is four and we have five elements therefore there's going to be a duplicate that duplicate causes a uh loop or a ccle like this so obviously we're breaking at three because that's where they equal each other and if we didn't have that case this would go on for infinity and then would crash our computer right but let's keep going outwards and seeing what would happen if we keep going with these pointers so fast is just stuck in this infinite Loop of 3 3 3 3 3 right with slow I'm at 0 1 to three which is also three so slow actually got caught in the same Loop and the same cycle and this is going to repetitively do three so here's where the magic of this algorithm happens um now we have captured the node where there is a cycle and that is what we need to uh solve this problem so I'm going to make another pointer now called in it and that's also going to be set to zero notice that slow is set to index 3 right it's still set to index 3 Let's Get remove this console log statement so um I'm going to do another while loop same idea I'm going to have a condition that's always going to be true and it's always going to be firing now I'm just going to copy this slow code or the slow logic which traverses just one Noe at a time remember fast traverses two slow just traverses one and then I'm going to do the same thing for in it and I'm just going to Traverse one node at a time and I'm going to say if slow equals init break okay now if I return slow what happens we get our duplicate value right so this is pretty much the answer to the problem but what is what is happening here and why does this work okay so you got to understand that slow the first Loop we did was just to determine the node in which there is our cycle we want to find where the cycle starts and that is at index 3 as we've established in it is just starting like slow did initially and working through the array so let's walk the dog and see it should be pretty easy because they it should be pretty easy because they both are traversing one note at a time both are traversing one note at a time so it's not really that confusing to see so it's not really that confusing to see what value they become but let's say what value they become but let's say we've got three and zero at the start so we've got three and zero at the start so if I go to index 3 that's 0 1 2 3 that's if I go to index 3 that's 0 1 2 3 that's three and it's just going to go three three and it's just going to go three forever right within it we start at forever right within it we start at index index one and then index one is two and then 2 one and then index one is two and then 2 0 1 2 looks like it's 0 1 2 looks like it's four and four is 0 1 23 4 which is three four and four is 0 1 23 4 which is three and here we have our connection where and here we have our connection where they both meet right so the interesting they both meet right so the interesting thing about Floyd's thing about Floyd's algorithm is that it basically knows algorithm is that it basically knows that if you start at the uh node which that if you start at the uh node which is the cycle and then you have another is the cycle and then you have another pointer start at at the beginning of the pointer start at at the beginning of the node list they're eventually going to node list they're eventually going to hit each other because remember this is hit each other because remember this is a loop where um slow is is stuck on on a loop where um slow is is stuck on on three forever it's it's just looping on three forever it's it's just looping on three So eventually in it is going to three So eventually in it is going to cross paths and collide with the slow cross paths and collide with the slow like imagine the uh a graph where two like imagine the uh a graph where two lines intersect that's the same idea lines intersect that's the same idea here so this problem is um has a Time here so this problem is um has a Time complexity of O of n it's linear complexity of O of n it's linear time but the constraints of this problem time but the constraints of this problem make it so you you pretty much uh have make it so you you pretty much uh have to use this algorithm this this problem to use this algorithm this this problem is tailored for you to use Floyd's is tailored for you to use Floyd's algorithm which I think is kind of algorithm which I think is kind of unfair because if you were never exposed unfair because if you were never exposed to this chances are you're probably not to this chances are you're probably not going to solve this in linear time of O going to solve this in linear time of O of n so that is the problem itself I of n so that is the problem itself I hope you guys enjoyed this video if you hope you guys enjoyed this video if you found it valuable please be sure to like found it valuable please be sure to like And subscribe again it might be kind of And subscribe again it might be kind of conceptually confusing to understand conceptually confusing to understand this logic at first but just know that this logic at first but just know that that first while loop is just to grab that first while loop is just to grab the location or the node or the index of the location or the node or the index of the start of the loop and then the magic the start of the loop and then the magic of Floyd's algorithm is that now that we of Floyd's algorithm is that now that we know the start of the loop we can know the start of the loop we can Traverse one note at a time with both Traverse one note at a time with both pointers and they'll actually end up pointers and they'll actually end up hitting each other truly incredible okay hitting each other truly incredible okay thanks for watching guys I will see you thanks for watching guys I will see you in the next one
2024-03-22 14:17:03
287
https://i.ytimg.com/vi/Q…axresdefault.jpg
Leetcode 287 - Find the Duplicate Number JavaScript
4GWP-3SqYz8
hello everyone welcome to my youtube channel channel and the question for today is pacific and the question for today is pacific implanting water flow implanting water flow all right so what we have over here is all right so what we have over here is so what we have over here is the so what we have over here is the question question where in which given a matrix m cross n where in which given a matrix m cross n of non negative integers representing of non negative integers representing the height of the the height of the each unit in the continent like pacific each unit in the continent like pacific ocean what ocean what touches the left and the top edges that touches the left and the top edges that is the is the left and the top edges is the pacific left and the top edges is the pacific and the atlantic ocean touches the and the atlantic ocean touches the right and the bottom edges so here we right and the bottom edges so here we have have atlantic and here we have pacific all atlantic and here we have pacific all right right and in between the cells that are given and in between the cells that are given that are given as a height all right that are given as a height all right so water can flow in four directions and so water can flow in four directions and so what is the main reason for the so what is the main reason for the heights given is heights given is that the water can throw from one height that the water can throw from one height to another only if it's equal to another only if it's equal or lower all right yeah only if it's equal or lower that is a very important condition over here so let us look at this like this is specific and this is atlantic ocean and these are the heights that are given to us in a form of an 2d matrix and water can only flow from uh height that is you know uh that is bigger to lower because water can flow from only high to lower late not low to high rate so that's the same thing that we that what that is given in the question as well so water can flow from uh height that is bigger then to smaller one and yeah so and it can flow in only four directions not technically it can flow in up down left or right direction all right so if we find the list of the coordinates where water can flow to both pacific and atlantic ocean so we have to find the coordinate from if we uh you know place some water drop or something like that over there the water will flow to both the oceans all right the pacific as well as the atlantic ocean we have to given the coordinates all right we are not given their heights but we have to return the coordinates all right so coordinates because coordinates are unique height can be you know repetitive so our answer would be you know wrong in the case that that's why the question is design like we have to return the coordinates all right so one note given over here is that the order of return coordinate does not matter so basically it doesn't matter uh it's not like we have to return the electro graphically smaller one or like that so we have just to return the coordinates and both m and n are less than 150 so the maximum size could be 150 all right so yeah that's the question over here and let's see the example over here that's given to us and in this example what it's given to us that these coordinates so what is zero four zero four is zero zero one two three four and zero so this coordinate already if we place water at this point definitely if it's at higher end it will flow to this and it will flow through this so it can flow to both oceans all right and the other coordinate that is given and the other coordinate that is given to us to us is so 1 3 is so 1 3 so it is one thirty okay so it is one thirty okay zero one three that is seven all right zero one three that is seven all right so water can flow to this side so water can flow to this side and this side and it can flow to both and this side and it can flow to both oceans like oceans like this it touches this and it touches this this it touches this and it touches this all right so that's the main all right so that's the main thing over here okay and also let because the they have encircled the points so for this one why is this point is included because the water can flow from here to this ocean and from here to this ocean all right so up down left right all right and only the heights which are lower than that all right not the higher height all right so yeah so why this point is not in our answer guys because the height is 3 and all the adjacent sides are like say we it can flow this side but it can't float this side because all the heights are greater than that it's five four four so it cannot flow from three to five or three to four all right so that's why it's not included in another it's not like we have to give a path from that particular point we have to give up points from where if we you know throw some water it will meet both the oceans so that's why 3 is not included in our answer over here and it's not marked like this so yeah i hope this example is clear to everyone and there are no constraint given so we will assume that these are general constraints because they have written some constraint in the these only that the numbers are non-negative that is they are positive and the size are less than 150 and the order it doesn't matter so it can be zero as well because it's not mentioned in the constraint we will cover this test case as well if mentioned in the constraint that the minimum range from the mrn would be from 1 to 150 then we can we can skip the part of having a null matrix but it's not specified over here so we will assume that we can get a null matrix all right so yeah that's the question i hope it's clear to everyone and a basic hint for this question would be a graph approach alright because a matrix is a kind of a graph only and yeah so and we have to find you know these that these are like connected in a way so it would be a graph question only and let's see how we are going to solve it so let's see the approach for this so let's see the approach for this question question and yeah this is the question and we and yeah this is the question and we will see the approach with the help of will see the approach with the help of an example first an example first and it would be much more clear how we and it would be much more clear how we are going to solve it all right are going to solve it all right so this is an example over here so what so this is an example over here so what we we do is simply the way we have to locate do is simply the way we have to locate the points the points from which we start and we reach the from which we start and we reach the both oceans both oceans and and we can only move from and and we can only move from uh and we have to give the point from uh and we have to give the point from which we start all right which we start all right not the path from the points that's a not the path from the points that's a very very uh basic thing that should be cleared uh basic thing that should be cleared while we while we write the code for this question so the write the code for this question so the idea here would be idea here would be not to start from the points but not to start from the points but to start from the ocean all right and as to start from the ocean all right and as we as i discussed earlier we as i discussed earlier it's similar it's a graph like question it's similar it's a graph like question so it's it's a graph like question so so it's it's a graph like question so basic graph traversals algorithm can be basic graph traversals algorithm can be used over here used over here all right so that shouldn't be any all right so that shouldn't be any concern concern so what to use so we can use both bfs so what to use so we can use both bfs and dfs and dfs uh i'll implement bfs because it's uh i'll implement bfs because it's it's much of a iterative solution than a it's much of a iterative solution than a recursive one and very recursive one and very easy to understand sometimes people have easy to understand sometimes people have difficulty in dfs because it's a difficulty in dfs because it's a recursive solution recursive solution but that doesn't concern it that can the but that doesn't concern it that can the main concern is the main concern is the approach that we will be use using approach that we will be use using to solve this question all right so as i to solve this question all right so as i said earlier we will not start from the said earlier we will not start from the point but we will start from the ocean point but we will start from the ocean what i mean by that is that given a what i mean by that is that given a matrix like this matrix like this we have over here is i think a pacific we have over here is i think a pacific is there is there an atlantic is here right so what we do an atlantic is here right so what we do is is that because these point can directly be that because these point can directly be covered covered with the ocean because these points can with the ocean because these points can cover the cover the atlantic and these points uh sorry these atlantic and these points uh sorry these points points are specific and these points in cover are specific and these points in cover atlantic now atlantic now we have to find the common points all we have to find the common points all right so right so the approach that was given to us in the the approach that was given to us in the question that question that we we have to go from higher tile higher we we have to go from higher tile higher high tile to lower time all right high tile to lower time all right as we are using the backward approach or as we are using the backward approach or the opposite approach the opposite approach so what we will be doing is we will be so what we will be doing is we will be going from going from lower height to higher right all right lower height to higher right all right to find out the points to find out the points and what we are going to do is we are and what we are going to do is we are taking these two points taking these two points from the in our queue and we're gonna from the in our queue and we're gonna apply bfs at them apply bfs at them and we're gonna find the points and we're gonna find the points similarly we are going to do similarly we are going to do the same thing keeping in mind the the same thing keeping in mind the points will only be added to the queue points will only be added to the queue or i have the at the list where we are or i have the at the list where we are storing them storing them only we then be visited only and only only we then be visited only and only then when they then when they move to a point which is higher than move to a point which is higher than them not lower than them all right them not lower than them all right so because this condition was when so because this condition was when we move from point to ocean all right we move from point to ocean all right point to ocean now we are moving from point to ocean now we are moving from ocean to the point we are using the ocean to the point we are using the this approach ocean view point all right this approach ocean view point all right so so this super this thing uh which we we this super this thing uh which we we would be would be keeping in our mind all right after keeping in our mind all right after suppose we have got some values then we suppose we have got some values then we will select for the will select for the common one all right now let's try to common one all right now let's try to solve this question and let's see solve this question and let's see what we can get all right so yeah i have marked over here with this blue at the passage equation point because here is the pacific ocean and we can move from suppose three point to this point and this point because it's of equal or higher length already similarly we can move from this point this one this point and this point we cannot move from this point to this point because it is of low length not this one can be covered from here so yeah these are all the points that are covered from the pacific similarly i have done here for atlantic because these are the point that touches the ocean so this can be covered directly from now we will apply our algorithm because it's a higher right we can cover it it said lower we cannot cover it all right now we have the now what we have to do we have to find the only the common points all right how did our algorithm be opposite that we check from every point it would have taken a lot of time this algorithm now saves the time and cuts our complexity even to you can say half from the algorithm where we traverse every point all right now after that we can have the common point so here i have marked the common points with yellow so these are the common points and at the end what we have to do we have to just return the coordinates all right so i hope this approach is very much clear it's a very easy approach what we are using here we are just doing the opposite we are going from ocean to the points and we calculate both the points from atlantic as well as specific and at the end we return the common points because only the common points can let us do both the oceans if we start from them all right and if we start from any other point we cannot get to those and we either get to pacific one or at least we cannot get to both of them so only the common points will get all right so yeah this is the approach we are going to use for every you know every traversal like for for pacific and fraud atlantic we will be maintaining two queues for visited like that because we don't want to go in a infinite loop if we don't know what points we have visited and what we points we are about to is it all right so we are going to maintain a queue for both of them separately and i hope this approach is clear to everyone and it would be much more clearer if you have still got some doubts it would be much more clearer when we see the code for this question all right so now let's see the code for this question yeah so these are the points because we can move in a specific coordinate so i have taken these points in as my directions and this is a general principle if we solve any problem for traversal as well we keep the points where we can move inner array initially and we apply our algorithm so this is general the number of laws number of columns these are nothing this is our main function which will which which have the coordinates all right so and we have to return a doubly linked uh list arraylist all right integer value all right so we have put a check for zero because if it's an empty array or it's zero then we simply return empty as the answer because we have to return an error list so that's why we have written an empty release we have haven't returned values like null or 0 because the the return now we have taken the number of rows and number of columns like that now here we have maintained two queues one for pacific and one for atlantic because we are applying bfs approach over here so we have we are using queues had it been dfs approach we have been using star alright bfs approach and now we are adding every point that covers the pacific ocean and the atlantic ocean alright how we are adding them because uh these are the points that will cover the pacific and these are the point that will cover the atlantic so we have we have applied a loop like that because at all these point we will begin our bfs approach all right because these points will be initially set to the queue and a bfs would be applied so how many nodes are with how many values are visited we don't care we just cared for the common ones that are visited by both all right so what we do is we uh initially offer these points for pacific and these points and landing that is done over here and now we have employing our uh deployed our bfs code which is written over there that's basic simple logic bss code and after that when the result will be uh covered in both where basically are the coordinates that are true because i have taken a boolean that will jump yeah to its visited and false if not visited and we will and at the end we'll compare the common ones so i have the traverse hole of the array if both of them are true that means they are visited in both the loops that is they are visited by pacific and that as well as atlantic so yeah i will pick that one and add it to my final answer and at the end i will return that value all right now let's see the code for the uh bfs approach all right so here is the code that we have used for the bfs approach all right so it's a simple code we have taken a matrix for determining whether it's visited or not and it's for the same number of rows and columns that is of initial method and yeah this is a simple bfs code while the queue is not empty we will simply pop the element and yeah we will mark it true and we will go in the directions and we will check that if if the point doesn't you know exceeds the matrix if if it doesn't exceed the metric then we continue and if it hadn't been visited then also we continue and yeah now we only and only at those points that we move from lower to higher because we are moving from ocean to the point we are checking for lower height to higher right had it been the opposite had it been we have been checking from the points to the ocean then we have uh just simply reverse this check all right and at the end if all these conditions are satisfied if because we are covered over here then what we do is we add it into our final queue and at the end we return our regional because when the cube will be empty and that means we have to reverse every point and yeah and the visited array are the boolean reachable array or the visited array uh reachable in this case would be set uh initially values will be set to true or else all right i hope this driver function or the bfs code is also clear to everyone as you can see it's accepted so if you as you can see it's accepted so if you have any doubt regarding this question have any doubt regarding this question or you have any doubt you can ask me in or you have any doubt you can ask me in the comment section the comment section and if you like this video please like and if you like this video please like it it and subscribe to my youtube channel for and subscribe to my youtube channel for more such videos more such videos thank you for watching bye
2024-03-22 11:01:40
417
https://i.ytimg.com/vi_w…xresdefault.webp
Pacific Atlantic Water Flow | LeetCode March Challenge
rN3r4_NE_y4
Hello Hello All Activities Problem Darkness to Conscience Bill to Ignore Actually a to Conscience Bill to Ignore Actually a Problem Problem Number to Take Down I'm Forever 125 Given Magical Number What I'm Forever 125 Given Magical Number What is the Magical Number Magical Numbers of is the Magical Number Magical Numbers of Positive Anti-Aging Effects Divisible by Positive Anti-Aging Effects Divisible by Either A and B Either A and B Either A and B NDA Big Tits Milk and Bones When We Want to Consider Difficult Number of Whom You Want to Give U Don't U Find and Magical Amazing Question An Answer Is Tubelight Model Celery Number One Word You Can Decide 123 The 1431 123 The 1431 123 The 1431 Notice For And The Cockroach 1262 Subscribe Important Question Unauthorized In The World That Aaj Yadav Action Is Basically Subscribe Active Number Delete Number Number Number Number [ Music] Music] Number Number Number Subscribe Similarly E Number Number Number Subscribe Similarly E Ki A Yeh Tube Baby Vihada MB Sweater Ki A Yeh Tube Baby Vihada MB Sweater Previous Video subscribe The Video then subscribe to the [Music] That Mi Plus m20 But Now You Will Have to Work Out Na Way UP and Country in the World Is What They Are Looking For Na subscribe Not Exactly Not Exactly Not Exactly subscribe I want to find out what do you want to have a function which music festival all the function which music festival all the best blonde 1669 macro in a best blonde 1669 macro in a that talent to be long long as they celebrate this long knows very well known that talent to be long long as they celebrate this long knows very well known in the in the name name name [Music] Video then subscribe to the Page That This Model Also Not Subtraction Business S Per Department Me Patience You Can Be Positive Water Absorption And Take Long Long Speech On Programmed instructions subscribe and subscribe the inter range long long long and share and subscribe will subscribe to difficult binary search tree which is made na dharo rok laka di hai point arrested No Limit of the World No Limit of the World No Limit of the World [Music] Subscribe to the channel and subscribe this Video plz Divide Divide Subscribe to Pimp Target Thursday Will Actually A Pimp Target Thursday Will Actually A That She Will Do Half Change Model Do Subscribe The Channel Please subscribe and subscribe the To Person Hundred To Person Hundred To Person Hundred Percent Call Member Short and Simple C Plus Percent Call Member Short and Simple C Plus Plus Solution of But Not Problem Thing Just Plus Solution of But Not Problem Thing Just Like This Important Relationship in To-Do Like This Important Relationship in To-Do List Now Research Away Joe Asaf Thank You So Much List Now Research Away Joe Asaf Thank You So Much By
2024-03-22 17:29:53
878
https://i.ytimg.com/vi/r…axresdefault.jpg
Leetcode 878(Hard) Nth Magical Number : Simple C++ Solution
_VVMtquSLek
good morning everyone welcome to my YouTube channel and for this video let's YouTube channel and for this video let's talk about the subsequent problem to the talk about the subsequent problem to the Sudoku problem so for this problem we Sudoku problem so for this problem we have to actually come up with our own have to actually come up with our own like Sudoku server so we will look at like Sudoku server so we will look at two approaches for doing this problem two approaches for doing this problem here is the problem statement and as here is the problem statement and as usual I want you guys to try this on usual I want you guys to try this on your own before we look at our solution your own before we look at our solution together like the traditional approach together like the traditional approach for solving this kind of problem like so for solving this kind of problem like so this problem is similar to uh that end this problem is similar to uh that end Queens problem I don't know if you have Queens problem I don't know if you have encountered that problem but they are encountered that problem but they are exactly the same like though and so the exactly the same like though and so the first time I try this I use Backtrack on first time I try this I use Backtrack on my own but I actually um encounter a my own but I actually um encounter a really nice way of solving this problem really nice way of solving this problem I think from MIT course like a few years I think from MIT course like a few years ago and just want to share that with you ago and just want to share that with you so in the description I will have a link so in the description I will have a link to that to the professor's paper so to that to the professor's paper so backtracking as you know we try pretty backtracking as you know we try pretty much we try every single number and then much we try every single number and then if that doesn't work we backtrack we go if that doesn't work we backtrack we go to our previous step and then we undo to our previous step and then we undo our you know the changes that we made our you know the changes that we made and basically we are doing like so this and basically we are doing like so this for using backtracking on this the time for using backtracking on this the time complexity will be like enormous like it complexity will be like enormous like it is very huge and especially when you are is very huge and especially when you are working on say a very difficult Sudoku working on say a very difficult Sudoku typically that means we don't have that typically that means we don't have that many you know numbers like shown in many you know numbers like shown in those like our stoku those like our stoku that in that case the number of times we that in that case the number of times we have to do backtrack can get really have to do backtrack can get really really big so let's first look at the really big so let's first look at the traditional way of doing this kind of traditional way of doing this kind of kind of problem so as you know here is kind of problem so as you know here is the code I put this backtrack variable the code I put this backtrack variable here so that when you run this we can here so that when you run this we can see how many times our code actually had see how many times our code actually had to do the backtrack and you can see that to do the backtrack and you can see that so basically we'll be iterating from so basically we'll be iterating from like this guy zero comma zero all the like this guy zero comma zero all the way to 8 comma a and then we iterate way to 8 comma a and then we iterate move to the right and then see that this move to the right and then see that this guy is empty so we try all the belly guy is empty so we try all the belly number say from one to nine and we number say from one to nine and we notice that so in this case the first notice that so in this case the first number would be one to four we try number would be one to four we try number four into here and then so they number four into here and then so they will be here so for e in range of one will be here so for e in range of one through ten so that there'll be one through ten so that there'll be one through nine and then in this case we through nine and then in this case we check if it is valid or not so the first check if it is valid or not so the first value number in this case would be what value number in this case would be what think this one will be two or actually think this one will be two or actually this one will be one so we put one here this one will be one so we put one here and then we check and then we do we run and then we check and then we do we run this recursive function again that's the this recursive function again that's the main idea for this kind of problem but main idea for this kind of problem but as you can see this one is very slow as you can see this one is very slow right I if even if you use this code for right I if even if you use this code for the liquid problem you will still pass I the liquid problem you will still pass I think few years ago when I used like think few years ago when I used like code very similar to this code very similar to this I was able to pass but it was rather I was able to pass but it was rather slow and I think right now it might be slow and I think right now it might be even slower because the code typically even slower because the code typically has like it adds more new test case so I has like it adds more new test case so I don't know how this would slow down but don't know how this would slow down but this code works so there is no problem this code works so there is no problem with this however there is a way to with this however there is a way to speed this up so there is a way to speed this up so there is a way to optimize this code and let's look at the optimize this code and let's look at the second approach oh also I just want to second approach oh also I just want to emphasize that you know we have this emphasize that you know we have this like inner block so we have about this like inner block so we have about this three by three plug here three by three plug here so we can call this zero one two three so we can call this zero one two three four five six seven eight and let's say four five six seven eight and let's say if you are working on this block like if you are working on this block like this guy and you want to know which this guy and you want to know which block remember we have to check like block remember we have to check like this inner block to see if the numbers this inner block to see if the numbers are if the numbers are valid or not in are if the numbers are valid or not in this case if you are say here then you this case if you are say here then you would have to then we'll be working on would have to then we'll be working on this block right and then the way I do this block right and then the way I do that is you you use this guy so sector that is you you use this guy so sector Type X sector top y so you're between Type X sector top y so you're between three times I like this division by three times I like this division by three so basically in this case let's three so basically in this case let's say let's see if you try seven comma six say let's see if you try seven comma six so I is 7 so we'll get three times that so I is 7 so we'll get three times that three times two that will be six and three times two that will be six and then we would get three times two the so then we would get three times two the so they will get a six so UB six comma six they will get a six so UB six comma six right here and then notice that we can right here and then notice that we can do this so for that we add set top X and do this so for that we add set top X and the set top X plus three so we'll be the set top X plus three so we'll be iterating from here to here and the same iterating from here to here and the same thing from here to here that will be thing from here to here that will be given by set top y comma set top y plus given by set top y comma set top y plus three three so tests for this code and there's so tests for this code and there's really not much to do and then we have really not much to do and then we have on our like like this we have if I is on our like like this we have if I is equal to negative one then we exit we equal to negative one then we exit we return true and then we do exit return true and then we do exit um I think that's pretty much it so um I think that's pretty much it so let's look at the second approach this let's look at the second approach this is our second approach but this is is our second approach but this is optimized how so the previous approach optimized how so the previous approach is how computers tries to solve this is how computers tries to solve this problem right but then for us human we problem right but then for us human we do a slightly different way right if you do a slightly different way right if you if we say if we look at this we can if we say if we look at this we can cross out so we know that this one has cross out so we know that this one has to be one because when this is one when to be one because when this is one when one is here then this guy for this row one is here then this guy for this row we cannot have one here when one is here we cannot have one here when one is here this row cannot have one here obviously this row cannot have one here obviously you cannot you can also not have one in you cannot you can also not have one in this column one in this column but for this column one in this column but for now we only care about this inner block now we only care about this inner block and then we look at this one again and and then we look at this one again and we notice that this column we notice that this column cannot have one so you look at this and cannot have one so you look at this and we see that well all these blocks are we see that well all these blocks are you know invalid for one and then this you know invalid for one and then this one is already taken this is already six one is already taken this is already six so that means this one that one has to so that means this one that one has to be one and then so that's the way of we be one and then so that's the way of we reduce the number of times we have to reduce the number of times we have to run our you know backtrack function run our you know backtrack function let's look at this one so let's look at let's look at this one so let's look at um like really specific example what I um like really specific example what I mean by this so here we so instead of mean by this so here we so instead of trying every possible combination we can trying every possible combination we can determine which numbers are probably determine which numbers are probably that every block like like this guy this that every block like like this guy this one for each inner block we would say one for each inner block we would say like this three by three that's what I like this three by three that's what I mean by Inner block we see which numbers mean by Inner block we see which numbers are available in this case well what two are available in this case well what two three four five seven and nine so those three four five seven and nine so those are the available numbers and then for are the available numbers and then for each inner block we determine which each inner block we determine which numbers are valid in the row and column numbers are valid in the row and column and if we are left with a single number and if we are left with a single number then we can place the number into the then we can place the number into the block so what do I mean by this this block so what do I mean by this this means we will get say row row set column means we will get say row row set column set and then we will be using our python set and then we will be using our python difference function between sets and difference function between sets and then we can just get rid of this like then we can just get rid of this like redundant numbers and then when we are redundant numbers and then when we are left with one number then that number left with one number then that number goes into like here so let's look at goes into like here so let's look at really specific example really specific example see what I mean by this so if you look see what I mean by this so if you look at this 0 comma zero that's the first at this 0 comma zero that's the first empty Block in our in our Sudoku and we empty Block in our in our Sudoku and we notice that so we'll be trying from one notice that so we'll be trying from one through nine and we see that five is the through nine and we see that five is the first available number and that is valid first available number and that is valid because well you may say well how about because well you may say well how about two two comes before 5 but then notice two two comes before 5 but then notice that two is here so we cannot use two that two is here so we cannot use two five is the first value number and then five is the first value number and then so we set that equal to five and then we so we set that equal to five and then we we look at all the other empty cell we look at all the other empty cell empty plug in our inner block this first empty plug in our inner block this first block so we see this guy this guy and block so we see this guy this guy and this guy so those threes are empty and this guy so those threes are empty and then we will store like the coordinate x then we will store like the coordinate x coordinate y coordinate and then the coordinate y coordinate and then the missing number in our in this inner missing number in our in this inner entire block so in that case we have two entire block so in that case we have two eight and nine so this is what I mean by eight and nine so this is what I mean by this and then you will be appending this this and then you will be appending this to some list here like that I will show to some list here like that I will show you in the later code and we noticed you in the later code and we noticed that and then the next step will be that and then the next step will be we'll be looking at this one first zero we'll be looking at this one first zero comma one we check the rows of row zero comma one we check the rows of row zero comma one there will be this row and comma one there will be this row and then those numbers are what one three then those numbers are what one three five six seven and notice that our this five six seven and notice that our this this set and then this set they don't this set and then this set they don't have any numbers in common so there's have any numbers in common so there's nothing we can do we look at The Columns nothing we can do we look at The Columns of zero comma one we notice that this is of zero comma one we notice that this is that's this guy then we have three five that's this guy then we have three five six seven and nine and we have nine as a six seven and nine and we have nine as a common number so this one for this one common number so this one for this one nine disappears so we are left with two nine disappears so we are left with two and eight however the length of this set and eight however the length of this set is not equal to one so we cannot do is not equal to one so we cannot do anything we cannot put any our like we anything we cannot put any our like we cannot make uneducated guess in here so cannot make uneducated guess in here so we move on to the next one there will be we move on to the next one there will be this guy now for this guy same thing we this guy now for this guy same thing we look at the row and then the column we look at the row and then the column we notice that the row of two comma zero it notice that the row of two comma zero it is one four six seven and eight and is one four six seven and eight and eight the number eight is the you know eight the number eight is the you know the common number so a disappears from the common number so a disappears from here so we are left with two and nine here so we are left with two and nine however Columns of two and zero we have however Columns of two and zero we have three four five seven and eight and three four five seven and eight and there is no redundant number right we there is no redundant number right we are looking at this side this set and are looking at this side this set and then we are looking at this set they then we are looking at this set they don't share any common number so the don't share any common number so the length of this is still two and we move length of this is still two and we move on to the next one we have one four six on to the next one we have one four six seven and eight and we notice that eight seven and eight and we notice that eight is the common number so a disappears and is the common number so a disappears and we have two and nine Columns of two we have two and nine Columns of two comma two we have this guy and notice comma two we have this guy and notice that this guy and this guy they have that this guy and this guy they have nine as a common number so we are left nine as a common number so we are left with two with two those the length of this set is equal to those the length of this set is equal to one so we set that equal to 2 and we do one so we set that equal to 2 and we do the same thing for like all these blocks the same thing for like all these blocks right the remaining blocks and this is a right the remaining blocks and this is a lot faster than you know trying all all lot faster than you know trying all all numbers without making like this numbers without making like this educated guess so that's two here educated guess so that's two here and here is the here is the code for and here is the here is the code for that problem so one thing that so this that problem so one thing that so this part is you know we are basically part is you know we are basically trying to find all the missing numbers trying to find all the missing numbers in our inner block and then here this in our inner block and then here this part this is the part where we do like part this is the part where we do like this this part this this part and then this part we are finding the so and then this part we are finding the so we are using this difference function we are using this difference function and then we find the first row row row and then we find the first row row row three which is equal to just which is three which is equal to just which is initialized as a set and then we add all initialized as a set and then we add all the numbers in here the numbers in here and then we use the difference function and then we use the difference function and then we try to you know get rid of and then we try to you know get rid of this redundant number this redundant number we do the same thing in the column and we do the same thing in the column and we try to get rid of redundant number if we try to get rid of redundant number if if it is possible and if our if the set if it is possible and if our if the set left is has a length one then we pop left is has a length one then we pop that and then we set it equal to you that and then we set it equal to you know the the value here so in this case know the the value here so in this case that's what I just did here here this that's what I just did here here this part and then we add this to our this part and then we add this to our this imply one array so why should we do this imply one array so why should we do this well if so we'll be running this we will well if so we'll be running this we will be making this educated guess and then be making this educated guess and then if somewhere in the in down the road if somewhere in the in down the road when our you know this Sudoku server when our you know this Sudoku server uh cannot solve this then we have to uh cannot solve this then we have to undo all the changes that we made right undo all the changes that we made right if you look at the code here if you look at the code here right so this is basically here so we so right so this is basically here so we so when we return then when we exit when we when we return then when we exit when we backtrack right this is the back track backtrack right this is the back track part we have to undo the changes that we part we have to undo the changes that we made before we make the change to e some made before we make the change to e some number then we have to make that change number then we have to make that change back to the like zero so we have to do back to the like zero so we have to do the same thing however in this case it's the same thing however in this case it's slightly more complicated because we slightly more complicated because we have to make unchanged we had to make have to make unchanged we had to make like we have to undo the changes for all like we have to undo the changes for all these like all the changes that we made these like all the changes that we made under this imply one so that's why we under this imply one so that's why we have to store this have to store this all these changes that we made in our all these changes that we made in our imply one array that's the key part and imply one array that's the key part and then if you look at this one I just pull then if you look at this one I just pull this out from some like you know Sudoku this out from some like you know Sudoku app and this is the like the one of the app and this is the like the one of the really hardness problem and if you use really hardness problem and if you use the knife approach like the traditional the knife approach like the traditional backtrack approach the number of times backtrack approach the number of times we have to do the backtrack is nearly 2 we have to do the backtrack is nearly 2 Millions but if we use the second Millions but if we use the second approach then we do roughly 60 000 so approach then we do roughly 60 000 so that's about 33 times faster than our that's about 33 times faster than our Nike backtracking approach I really find Nike backtracking approach I really find this approach really powerful and let's this approach really powerful and let's look at the decode problem here is the look at the decode problem here is the code that is optimized for Sudoku code that is optimized for Sudoku problem problem and it's exactly the same code that you and it's exactly the same code that you just saw and so let's I'm going to run just saw and so let's I'm going to run this this this one should be fine or also I just this one should be fine or also I just want to emphasize that like the want to emphasize that like the pseudocode problem that I that I worked pseudocode problem that I that I worked on the input were just integer but in on the input were just integer but in this case we have a we are given a um a this case we have a we are given a um a string bunch of strings so I didn't want string bunch of strings so I didn't want to like modify too much in this code so to like modify too much in this code so I did I took lazy approach to this so I I did I took lazy approach to this so I basically just you know given this like basically just you know given this like board input I just made everything into board input I just made everything into the integer right and then like this dot the integer right and then like this dot I just change it change I just changed I just change it change I just changed that to zero like this dot you see here that to zero like this dot you see here like the empty block and then when you like the empty block and then when you get the cook so when you use our Sudoku get the cook so when you use our Sudoku server we will modify our board and then server we will modify our board and then we just change the port which is just a we just change the port which is just a bunch of numbers integer back to the bunch of numbers integer back to the string so that's the step that I took I string so that's the step that I took I just didn't want to modify all these just didn't want to modify all these codes so let's run this so this one codes so let's run this so this one should be very fast and if you if you uh should be very fast and if you if you uh you can go to Apple App Store and then you can go to Apple App Store and then try to download say you know Sudoku app try to download say you know Sudoku app and you can try like all those really and you can try like all those really hard problems usually hard problems they hard problems usually hard problems they are you know you are not given many are you know you are not given many numbers to begin with and then you can numbers to begin with and then you can see the difference differences like see the difference differences like really really huge so anyway that's for really really huge so anyway that's for this video and I will have a link down this video and I will have a link down there to the paper that I found very there to the paper that I found very very insightful so that's for this video very insightful so that's for this video and hope you guys have a great day if my and hope you guys have a great day if my video helps you guys understanding this video helps you guys understanding this problem please subscribe to my YouTube problem please subscribe to my YouTube channel and I'll have more interesting channel and I'll have more interesting contents out there for you I will see contents out there for you I will see you next time bye
2024-03-20 09:01:07
37
https://i.ytimg.com/vi/_…axresdefault.jpg
Let's solve any Sudoku Problem with our own Sudoku solver ! (Leetcode 37)
YVRRQF6v0fQ
The Festival My name is Adarsh ​​Mishra This is what you are watching Dress this mark Today we are going to you are watching Dress this mark Today we are going to talk about number of talk about number of Tintin's problem problem problem problem not Gheerat Dahi video on the list You can watch the video that you should not forget to subscribe this channel Subscribe must subscribe, anyone subscribe to that word here so that I can speak to you, here I have been given a system, what I have to do here is that at that time I have to see how many numbers of words are there inside it like I am See, this is the word here, it will See, this is the word here, it will See, this is the word here, it will go from here to here to even if go from here to here to even if you use it in the family after getting war 5508, then please subscribe. If you want to use it, then you have to you use it in the family after getting war 5508, then please subscribe. If you want to use it, then you have to subscribe. Subscribers subscribe to subscribe to subscribe subscribe here. go to the face, then it will go to forever, then the total is go to the face, then it will go to forever, then the total is four, I have put it here and here, it four, I have put it here and here, it is okay, but stop love music is different system, here, here, like like subscribe can be appointed, it can be He is telling me that you will not have STD, its length can be up to 300, it can contain lower case, upper case and digits or it can contain as many punctuation characters as you can see, it is a special item, it If the If the If the species character was of this type after grinding the juice, if it was ever off space, then here we subscribe like we must subscribe here, here this subscribe, for this, It will be spread It will be spread It will be spread here like this and then this remaining empty here like this and then this remaining empty space will also come, so I mean we will space will also come, so I mean we will consider it empty also, so if we are going to have it then consider it empty also, so if we are going to have it then I don't have to do this, for that, Noida I don't have to do this, for that, Noida first, whatever extra space is there from the left side and from the right side first, whatever extra space is there from the left side and from the right side and and and trim them, smile while timing them, first we will use Hussain, after this we will use speed, only then our answer will come when we use the functions in agar, is it surgical, problem in the pattern, on this platform, friends, in this There is no need to print it separately, but it has a There is no need to print it separately, but it has a There is no need to print it separately, but it has a function. If you have function. If you have seen any of our stings before that, you have seen any of our stings before that, you have space. Okay, then whatever is in your mind, first space. Okay, then whatever is in your mind, first remove the prescription. I have remove the prescription. I have removed all the specials before that, which is my skin. removed all the specials before that, which is my skin. removed all the specials before that, which is my skin. going into it, our stomachs are separated on it, some of our weight is separated and kept in the list, the method is written here, should I If If If you do this then its printing is in ABC space, you do this then its printing is in ABC space, BF BF picture send Radhe Maa, I BF BF picture send Radhe Maa, I will use speed, this is done, ABC people will break the given panel will use speed, this is done, ABC people will break the given panel here also soon, so what did I here also soon, so what did I do, I broke it from the middle, did speed, this is do, I broke it from the middle, did speed, this is space and then find out its length. space and then find out its length. space and then find out its length. two, so whose one is yours, so this is a small meaning, okay, there is a function, you can use it and how much time will it take, if you feel stupid then it explains it, travels in the whole list by Gives space, we are Gives space, we are Gives space, we are feeling extra in this but because just feeling extra in this but because just subscribe, it will be taken, so you have the method here, it is our simple you have the method here, it is our simple technique, now we are going to use it here, technique, now we are going to use it here, okay, so the thing here is that okay, so the thing here is that we are stressed. we are stressed. we are stressed. place we will write the code here, now it will be exactly like this that if I tell you that you have written my ABC space difficult something then subscribe to this channel subscribe to this channel here we will That is, before this, as many as you That is, before this, as many as you That is, before this, as many as you subscribe and okay, after this, run it again from here, okay, so we are making all these separately, so in this way you can do this by looking at us, It is being It is being It is being started again that you subscribe this subscribe subscribe the union now subscribe it means house subscribe it means house cannot do subscribe quit will use and by using constant space you are going to use songs person mosque account how many numbers will you do How much more will we provide from this pay, till then we call it account number, words, it is subscribe, if you subscribe, if you take them, then this subscribe is nothing subscribe is nothing like this subscription of mine is here, Okay, I picked up the ginger for Okay, I picked up the ginger for Okay, I picked up the ginger for one more minute, maybe before there was one more minute, maybe before there was even space, okay, then even space, okay, then I remember doing something, it is getting clear I remember doing something, it is getting clear that brother, if you want to get a character on zero index, that brother, if you want to get a character on zero index, if you want a heroine, any if you want a heroine, any character. character. character. a new segment. Okay, so what do you do? Call them, give them an increase, if you want to meet the character on the front, then it means that it is definitely going to be a labor world, isn't it? Good Well, if you are interested, then Well, if you are interested, then Well, if you are interested, then set yours, if you try to find out, if set yours, if you try to find out, if you are interested, you will like start, subscribe here, if you have if you have questions and hate others, our our Ghaghra Write that doing special will last till the end of the Write that doing special will last till the end of the Write that doing special will last till the end of the marriage marriage because why would it be like this then because why would it be like this then first do as first do as many of these and village means I subscribe I I subscribe subscribe and I and I will subscribe ok ok after this see will subscribe ok ok after this see here boat in my head, that's why the boat in my head, that's why the point reached crore on some index, in this we point reached crore on some index, in this we say that say that subscribe and subscribe our channel, here I have written that on the growth index of my sting, Divya is not that, space way Increase Increase Increase that on the truck in the same condition, now write, that on the truck in the same condition, now write, if if today we have something other than Twenty-20 of potatoes, today we have something other than Twenty-20 of potatoes, then we will do a case of that case, we then we will do a case of that case, we can check on them, then I said that for this team, can check on them, then I said that for this team, I have written here if my I have written here if my lying on the eye of space and history, it is lying on the eye of space and history, it is not lying on the eye of any character, there is nothing like that and if there was an option in this then used both of them here, I have used them here, here we have used them, so here you have to type. That and you have to use the space, use the cost, make it simple and if you use the function, then you have to take time which will give you extra, use this piece also and you do not have to use the touch here, that is the thi a jhal jhal thi a jhal jhal thi a jhal jhal jhal
2024-03-22 12:09:56
434
https://i.ytimg.com/vi_w…xresdefault.webp
Number Of Segments In A String | Leetcode Python Solution | Python
ZUvKzWYb3Cg
in this video we're going to take a look at a legal problem called spiral matrix at a legal problem called spiral matrix so given an m times n matrix so return so given an m times n matrix so return all elements of the matrix in a spiral all elements of the matrix in a spiral order so here you can see that we have a order so here you can see that we have a 2d array 2d array and we're basically given a 2d array of and we're basically given a 2d array of matrix and we want to return a spiral matrix and we want to return a spiral spiral order of the um spiral order of the um 2d array in a one directional array 2d array in a one directional array so that's the output and here you can so that's the output and here you can see that we see that we have going from this direction to here have going from this direction to here so first we're going right and then so first we're going right and then we're going down and then we're going we're going down and then we're going left left and then go up and then and then we're and then go up and then and then we're going to continue going to continue the spiral um and here's the spiral um and here's uh you can see here's another example so uh you can see here's another example so we're basically going from we're basically going from uh left to right um down so top to down uh left to right um down so top to down and um right to left and then and um right to left and then um down to up and then yeah basically um down to up and then yeah basically just continue and there will be inner just continue and there will be inner uh elements and we have to it um uh elements and we have to it um traverse as well so here you can see we traverse as well so here you can see we have a little more a little more have a little more a little more bigger to the array bigger to the array so we could so the way how we're gonna so we could so the way how we're gonna solve this problem is basically just solve this problem is basically just just like i mentioned for just like i mentioned for for each iteration we're going to for each iteration we're going to traverse traverse let me change the color real quick let me change the color real quick so for each iteration we're going to go so for each iteration we're going to go from here to here right so basically the from here to here right so basically the left left all the way to the right then we're all the way to the right then we're going to do is we're going to going to do is we're going to basically move down because after we basically move down because after we traverse this part we're just going to traverse this part we're just going to strength strength shrink the array or i should say shrink the array or i should say basically shrink it so that we can just basically shrink it so that we can just only traverse from here only traverse from here all the way to here right so here we all the way to here right so here we just have to traverse from just have to traverse from here to here so in row 2 to row 4 here to here so in row 2 to row 4 right and then once we've done that we right and then once we've done that we also have to shrink also have to shrink the um the the um the um the the um so basically shrink from the array so so basically shrink from the array so that we can only traverse from here that we can only traverse from here to here okay so so basically we're going to here okay so so basically we're going from here to here from here to here and after we've done this we can shrink and after we've done this we can shrink the array so basically we're going to the array so basically we're going to only traverse from row three to row two only traverse from row three to row two okay so after that's done that's our okay so after that's done that's our first iteration first iteration and then we're going to continue to do and then we're going to continue to do this so we're going to this so we're going to um start from here to here after we go um start from here to here after we go from from uh column two to column three and row uh column two to column three and row two two what we're going to do is we're going to what we're going to do is we're going to um start to start um start to start showing the array again so basically showing the array again so basically like these parts of the arrays are all like these parts of the arrays are all gone we're not going to like traverse gone we're not going to like traverse them them again but what we're going to have is again but what we're going to have is we're going to traverse we're going to traverse from from um basically from from um basically uh top to down and and now we're going uh top to down and and now we're going so basically traverse this element right so basically traverse this element right here and then we're going to traverse here and then we're going to traverse from right to left which is right here from right to left which is right here this one this one and then after that's done we don't we and then after that's done we don't we don't have any elements left so we're don't have any elements left so we're just going to return just going to return the elements that are with uh within the the elements that are with uh within the two uh one directional array two uh one directional array so let's try to do this in code i'll so let's try to do this in code i'll show you how we can do this show you how we can do this so our first step is to create our list so our first step is to create our list integer we're going to create a linked list we're going to create a linked list because we don't need to access because we don't need to access um a specific element in the in the one um a specific element in the in the one directional array we're just adding directional array we're just adding the elements onto it so and then we're gonna have our borders so in this case we have our left have our right have our top pepper down so we're going to define our borders right now so top is equal to 0 down is equal to matrix that length minus one so that's the last element in this case this is the top this is the bottom this is the top this is the bottom right this is this is the left this is right this is this is the left this is the right the right okay and now we also have our left okay and now we also have our left have our right which is equal to matrix have our right which is equal to matrix at zero dot length minus one at zero dot length minus one so basically it's the last element of so basically it's the last element of the sub array the sub array and then we're going to do is we're and then we're going to do is we're going to um basically going to um basically we're going to um use a while loop we're going to um use a while loop and then basically what's going to and then basically what's going to happen is we're going to iterate happen is we're going to iterate first starting from the left all the way first starting from the left all the way to the right so let's try to do this to the right so let's try to do this so integer i is equal to so integer i is equal to left but i is less than or equal to the left but i is less than or equal to the right right what we're going to do is we're going to what we're going to do is we're going to add each and every single element onto add each and every single element onto the nums the nums to the list in this case matrix at top and i so we're gonna iterate from the top so top left to the right after that's done we're gonna decrement rash sorry i should say increment top by one because we don't we want to shrink the top um down so that we can be able to move inside so move inside um or spiral um inwards and then what's going to happen is we're going to start to go from the top to down so now we're going from we iterate the top side we don't want to iterate this this element 3 anymore we want to iterate this this element 3 again so we just want to start it from here right so what's going to happen is we're going to starting from so i is equal to top so while i is less than or equal to um then we're gonna do is we're gonna add then we're gonna do is we're gonna add our element our element onto the uh the list onto the uh the list so in this case we're gonna say hi and so in this case we're gonna say hi and then then um and then the right so um and then the right so we're going to iterate from the top to we're going to iterate from the top to down on the down on the on the uh the right so index on the uh the right so index or yeah index right and we're going to or yeah index right and we're going to move right one to the left move right one to the left because now we're done we want to shrink because now we're done we want to shrink the the top side so the top side top side so the top side and the right side and now we're going and the right side and now we're going to move from right to left to move from right to left and once that's done we're going to and once that's done we're going to shrink shrink the down to the down to down we're going to decrement down by down we're going to decrement down by one or i should say one or i should say we're going to shrink the bottom border we're going to shrink the bottom border and then we're also going to eat right and then we're also going to eat right here here and then we're going to shrink the left and then we're going to shrink the left border and that's how we're going to do border and that's how we're going to do this this and then what's going to happen is we're and then what's going to happen is we're going to use a going to use a for loop again so starting from right for loop again so starting from right about right it's bigger than or you go about right it's bigger than or you go to the left what we're going to do is we're going to onto the list onto the list and then we're going to move down by one and then we're going to move down by one so even so even so we're basically move down up so that so we're basically move down up so that we can so basically we're basically we can so basically we're basically decrement down by one decrement down by one and then what we're going to do is we're and then what we're going to do is we're going to iterate from down going to iterate from down to up so iterate from down to up to up so iterate from down to up so like down i is bigger than or equal to top i'm gonna one second so i minus minus so we're gonna add our current element on to the list and then we're just gonna on to the list and then we're just gonna increment left by one so that we can increment left by one so that we can shrink shrink the uh the left border and here what we're trying to do here is we basically have to have a if statement so if left is actually bigger than the right or if right it or sorry if top is actually bigger than yeah bigger than down now we're going to do is we're going to break the for loop right we're going to sorry we're going to break the while loop after each and every single for loop after each and every single for loop and then at the end we're basically just and then at the end we're basically just returning returning numbs okay so now let's try to run the numbs okay so now let's try to run the code code and submit and here you can see we have and submit and here you can see we have our answer our answer so this is basically how we're going to so this is basically how we're going to solve the problem solve the problem using a linear time complexity using a linear time complexity and n is basically big o of n and n is basically big o of n and is the size of the matrix so and is the size of the matrix so basically how many elements in the 2d basically how many elements in the 2d array array and yeah so time complexity is and yeah so time complexity is big o of n
2024-03-20 10:24:12
54
https://i.ytimg.com/vi/Z…axresdefault.jpg
[Java] Leetcode 54. Spiral Matrix [Array #4]
VklULuX4CHE
Had happened Hello Hello friends welcome to my channel today Hello Hello friends welcome to my channel today appointed S tax problem list appointed S tax problem list contest 1000 maximum profit of contest 1000 maximum profit of operating officer appointed 100 gram center operating officer appointed 100 gram center subscribe channel 1234 more compartment subscribe Indian elections will rotate soft operation degree degree and torn Cost ok to Cost ok to Cost ok to liquid and again play karo 4600 customer liquid and again play karo 4600 customer The Video then subscribe to the Page if The Video then subscribe to the Page if you liked The Video then return 2 - 118 religious the provided the ok so let's example customers lots of your drop no passengers subscribe my Subscribe To Election 2012 Requested 6 - 649 Election 2012 Requested 6 - 649 Radhe-Radhe People Left And Subscribe Number Radhe-Radhe People Left And Subscribe Number Of People Is 700 Unknown Looters Have Degraded Unauthorized No Finally Vighn Atithi 6828 To Like Unauthorized No Finally Vighn Atithi 6828 To Like Subscribe Subscribe My Channel Subscribe 71000 Third Option A Great Soul How To Solve This I Love You All The Best Solution And Its Ultimate Solution So Let's Take A Look And Food Sources Of Functions Were Given A Minimum Proportion Maximum Profit Operation Adhir Wa Share The Maximum Profit Operation Adhir Wa Share The Answer Ronit Calculation For The Length Of The Answer Ronit Calculation For The Length Of The Customer Like Subscribe And Customer Like Subscribe And Good Result Is The Final Report And I Good Result Is The Final Report And I Will Explain What This Max 10 Rich And Will Explain What This Max 10 Rich And Doing In Passing Period Crop On Farm Current Doing In Passing Period Crop On Farm Current Generation Middle Aged Generation Middle Aged Generation Middle Aged INDEX VALUE INTO THE RUNNING PROCESS INDEX VALUE INTO THE RUNNING PROCESS VALUE SOUND SHIFT OPERATION AND THE WORLD VALUE SOUND SHIFT OPERATION AND THE WORLD STING OPERATION OK TOW GREATER THAN STING OPERATION OK TOW GREATER THAN FOR DOING IT TOOK ITS CAPACITY FOR DOING IT TOOK ITS CAPACITY CAPACITY WILL DO THE CUSTOMERS SHOULD FOCUS ON THE CAPACITY WILL DO THE CUSTOMERS SHOULD FOCUS ON THE OPERATION SUBSCRIBE THE CHANNEL AND PRESS OPERATION SUBSCRIBE THE CHANNEL AND PRESS The Amazing Maximum Value Is The Current The Amazing Maximum Value Is The Current Profit Will Update You To The Point And Profit Will Update You To The Point And Click On Subscribe Like And Capacity Of Business Option Three Capacity Of Business Option Three Plus Points 75459 Distance Condition Loot Plus Points 75459 Distance Condition Loot Andhe subscribe our Channel and tap On Andhe subscribe our Channel and tap On The Amazing subscribe and subscribe the The Amazing subscribe and subscribe the Channel Channel Channel And The Result Of The Return Of The Day Are Request To Gather Maximum Profit Should Win This They Can See The Solution Accepted They Can See The Solution Accepted And Lips Look At The Best And Part Of What And Lips Look At The Best And Part Of What Happened Was How to Sew Around All the 136 How to Sew Around All the 136 How to Sew Around All the 136 Test Cases Should be Accepted by the Test Cases Should be Accepted by the Institute for Election Thanking You
2024-03-21 14:51:43
1,599
https://i.ytimg.com/vi_w…E/hqdefault.webp
1599. Maximum Profit of Operating a Centennial Wheel | LeetCode | Weekly Contest 208 | Brute-Force
Z29M4Tk1ZaI
Toilet And Asked Questions Remove Duplicate Mandsaur District In This Duplicate Mandsaur District In This Question In Given Or Started List And You Need Question In Given Or Started List And You Need To Remove Dost Element From The To Remove Dost Element From The Reader Kissi Inverter Defeated Indra Leaves Reader Kissi Inverter Defeated Indra Leaves Means Frequency August Month In The Means Frequency August Month In The Intellect Subscribe 1233 65 Subscribe Element Completely Liquid subscribe The and subscribe Quiz Pick Up To Ko Math Hai Aur Ka Veer Notes In Range Of 0230 Volume Start - Hey Zindagi Liquid Ki Bigg Boss Ubal Gaurav Nau Seems Like A Typical Lips Problem Thumb Rule For subscribe and subscribe the Video subscribe to the Page if you liked The subscribe to the Page if you liked The Video then Video then Ek Dum Manipulation Kam Logic Comes Only One Ek Dum Manipulation Kam Logic Comes Only One Day Multiplayer in the Latest and Day Multiplayer in the Latest and Greatest One Should Discord Thursday Greatest One Should Discord Thursday subscribe and subscribe the Channel subscribe and subscribe the Channel Please subscribe and subscribe the Video Please subscribe and subscribe the Video then subscribe to subscribe our Channel subscribe The New Delhi Oscar Ramiro - 02 Classes Specified in Correct Clear Shot Also Something Volume Minimum Owner Alerts for B.Tech Volume Minimum Owner Alerts for B.Tech 3.5 Thursday The Internet subscribe And and subscribe the Lutab School and subscribe the Lutab School Quantum of Previous Word Next 150 Quantum of Previous Word Next 150 Notification Heart Notification Heart Notification Heart The Best To And Loot Loot Loot Enter Gonna Enter 200 Will Reduce File There In Court And Will Increment Now Students And Will Keep You Updated On Tomorrow Morning And Move Ahead Inside Same Intensive Study Shift Please subscribe and subscribe Aaj Kyun Zahar And Observe This Will Help To Aaj Kyun Zahar And Observe This Will Help To Aaj Kyun Zahar And Observe This Will Help To Remove All Notes From The National Remove All Notes From The National Interest Accused Interest Accused Inside Red Ribbon Veer 1000cc Avoid The Video then subscribe to the Page if you this point to and land water quality and this point to and land water quality and current subscribe to the Page current subscribe to the Page current subscribe to the Page The Video then subscribe to the hai pet aur hai did not aur singla list main college dal increase definite anil attached dot to hai main egg points this points no one will be the current egg points this points no one will be the current attractive the current one positive attractive the current one positive Vibration one response to have list Vibration one response to have list subscribe to parts subscribe to parts that a previously pigmented rich and festival it did that a previously pigmented rich and festival it did not agree with oo not agree with oo plant's main lead wave daughter current plant's main lead wave daughter current request to the Video then subscribe to request to the Video then subscribe to subscribe our Channel with oo subscribe our Channel with oo hu is the means hu is the means loot key point loot key point loot key point Subscribe to Subscribe to Connect with Updated on True and Also Connect with Updated on True and Also Live Writer Logic subscribe to the Page Live Writer Logic subscribe to the Page if you liked The Video then subscribe to if you liked The Video then subscribe to the Page if you liked The Video then the Page if you liked The Video then subscribe to subscribe to I Want to Implement IT Progressions I Want to Implement IT Progressions Loop Loop That In The Glorious Day Scores What That In The Glorious Day Scores What Maintenance And The Amazing Spider-Man Per Maintenance And The Amazing Spider-Man Per Loot Vid Oo Loot Vid Oo That I Tribes Of Ko Finish Looks Good Loot WhatsApp Twitter Talk Time Complexity The Time Complexity Of Water Of Instances Of Writing To Completely To Dumb School You Not Dumb School You Not Dumb School You Not Giving Any Extra Space for Creating Giving Any Extra Space for Creating New List and Gautam Gambhir Video New List and Gautam Gambhir Video Conference on Ki Conference on Ki Tanu Watching Video for Kids on
2024-03-20 12:22:22
82
https://i.ytimg.com/vi_w…xresdefault.webp
Remove Duplicates from Sorted List II | Leetcode 82 | Live coding session
Kka8VgyFZfc
given that link twist removed the eighth note from the end of the linked list and note from the end of the linked list and returned his hat how would you do this returned his hat how would you do this this is today's video let's get into it hi everyone my name is Steve today we are going through a little problem 19 a very classic interview question regarding a link to list remove ant node from the end of the list let's take a look at the problem description first given a linked list remove the ants node from the end of the list and return its hat for example were given this linked list 1 2 3 4 5 and the N equals to 2 that means we removed the last second node from the from the end of the list removing the second node from the end of the list the linked list then becomes 1 2 3 5 the second last node is the node with value 4 then there is gap so we return the new hat no given 10 will always be valid the follow-up is could you do this in one pass the reason it's asking this follow-up that is because very straightforward or intuitive solution which is we can do in two passed first pass will just reverse from the very beginning towards the end and then we know the length of this linked list we know how many nodes are there in this singly linked list right and then and the second pass we'll just go towards the last towards the end node from the end of the list and then we just cut it off remember that technique we just discussed in the in the manual about delete a node in that singly linked list in that one we are only given access to the note that needs to be did it remember we talked about usually the technique is that we'll assign the note that needs to be deleted is previous nodes next pointer towards the note that needs to be deleted is successfully that way then know that needs to be debated is good because that's it's not linked to its predecessor anymore so it's good we can use that technique but basically back to the point what I was describing is the brute force are very into solution is to past wise to pass because first pass with Traverse from the start until the end of the mist that's one has we know the total length the second path will go through until total length minus n right then we'll just stop there and then we'll change the pointer that's to pass that's to pass of course that's an acceptable solution is going to be accepted by the LJ but if you get asked the during an interview as a follow-up how the interviewer is asking you how can you do this in one pass well we have done through the problem description already one common technique for these remember that we discussed it in array problems in problems data that are associated with a race we discussed a two-pointer solution right we have a left pointer or right pointer another another common variation of two pointers technique is that we can use a fast and slow pointer that this kind of technique are kind pretty often applies really well for linked list problems so in this problems specifically for this follow-up is asking us to do this in one pass the technique that we are going to apply is the 2.0 topic and we're going to use a slow and fast pointer let's take a look spoke we'll still use this example 1 2 3 4 5 and N equals to 2 let's see when asked by this problem 1 2 3 4 5 5 is the tail node that's it that's the last node and the question is asking us to delete the second node N equals to 2 to leave the second note from the end of the list in this case is full so the end result is going to be 1 2 3 5 as we just saw in the problem description 1 2 3 5 right there hole can we use the 2 pointer technique to solve this problem and just a quick thing which is a pretty standard way is another very common or classic trick is to use a dummy know which comes in super handy so in this case we'll initialize a dummy node say any random value minus 1 for example and then with this dummy dummy node we'll have two pointers one we'll call slope on one first point both of them will start from demeanor and then faster as the name indicates will move fast note first fast no faster stands from Tammy note it moves on one step now it's pointing at the node with value 1 do we need to move fast no slow no at this point we need to move fast note why because we want to keep the distance between slow and fast no the distance between these two notes and a distance of n N equals 2 this n is the number that we would like to see to be deleted that note to be deleted from the end of the linked list so we'll keep moving fast because by now slow and fast the distance between them is only one and the note the end in this question is second is tune so we still will keep moving in right now this the distance between these two notes slow and fast is 2 which matches the end in this question right and then at this point we'll keep moving these two pointers will keep moving both boundaries previously we only moved fast pointer right we keep moving fast pointer until the distance between the slow and fast pointer equals to n at this point we'll keep moving both wineries why let's take a look you'll see that in just a second let's see we move both pointers right so slow what is at dummy at this position right now slow moves towards the right fast also moves towards right so in this way the distance between slow and fast it keeps AB - okay we'll keep moving slow and fast they both move at the same pace at the same time so the distance is no to you we pokey moving what's more then at this point we're going to stop so the break-up condition is fast dot next is now while fast dot next is not now we'll just keep moving why do we stop at this position what can we do at this position now let's go back to the question the question is asking us to give on a linked list remove the earth from the end of the list and return Issa the eighth note from the end of the list so right now the end of the list fast reaches the end of the list and this is the second note from the end of the list which we need to delete remember the tactic we discussed in the video delete node in the linked list which is to cut off this link and assign this link point to the to be deleted notes successor then we're done that's what we're going to do right then this one is gone the note would verify is gone because it's not part of this linked list anymore the link the it's only link to its predecessor is cut off it's gone and we assign the next pointer from its predecessor to this guy's successor right so this one is pointing to this then we're done as beautiful as that that's it then we'll just return this dummy dot next which is this hat that's another use of keeping this demeanor or just because the problem is asking us usually for link list problems is asking us to return the hat of a modified linked list so we just returned a meet our next which is the new hat that's it that's the algorithm very simple and straight for now let's put that into the time complexity for that is just om we just go through this problem we'll just go through this entire linked list when every fast start next which is now which is doing the operation and then we'll just break out that's it space complexity is o one we don't need any extra memory all right now let's put the code into you let's put the algorithm into actual code let's see how we can do that so first well initialize a no no minus one so we will have done that to you and Tammy note tell me no the next is hat that's how we associate the Domino with the given in list and then we'll have a slow note which will start from dummy and a fast note will also start from Demi and then all the trees remember the break-up condition is well as long as fast dot next is not equal to now we just keep moving which is Q movie first we'll move only fast while fast fast our next not equals to now first we only move fast right fast this is the line would just keep assigning fast our next tour is fast so then we keep moving remember in the very initial steps remember in the very net this is the very initial State or keep moving fast will mean fast until a distance between slow and fast is to write that's what we did and then how do we knew that what will I do is that we have will check if and it's smaller than or greater to zero at this point what we'll do is well assign slowed down next to slow only at this point so we'll keep Deborah Duck Creek will keep decrementing in will always keep decrementing in but only when n is smaller than or equal to zero will start moving slow that is at this point when n is smaller than or equal to zero slow the distance between slow and fast starts starts to begin and equal to n so at that point was done moving slow was done within both of them right both of them both of them until at this point faster next which is now then we just break out of this of this while loop right so at this point what do we need to do what we need to do is to assign slows next remember it at this point this link is still there so we that's that's the whole reason that we can reach this note so slow done next dot next we'll assign this one to SLOS next that's what we did well assign this one we get this note first and assign this note towards the next the next pointer of this note that's what we will do here okay and actually we don't need to check whether snow done next is is now or not because the because there's a note here they're given n will always be valid okay let's just do that slow next what a song slow down next but next here in the end will retain is just dummy done next that's it that's the entire algorithm that we'll put into the actual code let's hit submit and see all right accepted 100% it's just a one pass but we use the tactic of two pointers this way this will become a lot clearer and easier and we'll do it only in one pass that's a very common technique when it comes to linked list we use two pointers previously we discussed to use a left and right pointer but here we could use a slow and fast pointer which is super common and popular in linked list questions I hope this video helps you understand this problem and the solution to this problem how can you do it in one pass if you like this video just do me a favor I have that like button that's going to help a lot with the YouTube algorithm and also don't forget to subscribe to my channel I really appreciate it and tap the little bow notification so that each time when I publish a new video you're not going to miss out on anything really appreciate it see you guys in the
2024-03-19 16:16:33
19
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 19: Remove Nth Node From End of List - Interview Prep Ep 58
xYM_-MrFJo0
good evening everyone today we are going to do the daily record challenge of 5 to do the daily record challenge of 5 February 2023 that is question number February 2023 that is question number 438 find all anagrams in a string so 438 find all anagrams in a string so anagrams are basically permutations of a anagrams are basically permutations of a string and we have done this question string and we have done this question yesterday so please check out that video yesterday so please check out that video there will be a minor change in that there will be a minor change in that code because in the previous question we code because in the previous question we have to return true or false whether it have to return true or false whether it is present or not but now we have to is present or not but now we have to return the index of the starting anagram return the index of the starting anagram index of the starting anagrams what I index of the starting anagrams what I mean by that is let's see the example in mean by that is let's see the example in the example the possible anagrams of a b the example the possible anagrams of a b c are so many possible like uh is CBA an c are so many possible like uh is CBA an anagram of it yes so we have to return anagram of it yes so we have to return the starting indexes 0 is the starting the starting indexes 0 is the starting index we will return it then we come index we will return it then we come here then what are the other possible here then what are the other possible anagrams anagrams a b no because there is no e e b and no a b no because there is no e e b and no b a b there is only single B then a b a b a b there is only single B then a b a not possible then BAC is the another not possible then BAC is the another possible anagram possible anagram so that also we have to return 0 1 2 3 4 so that also we have to return 0 1 2 3 4 5 6 so we have to return the starting 5 6 so we have to return the starting index of the anagrams so that is all we index of the anagrams so that is all we have to do and in the previous video we have to do and in the previous video we have seen how to find the permutations have seen how to find the permutations so we will change this code simply and so we will change this code simply and we will get the answer we will use we will get the answer we will use sliding window approach as discussed sliding window approach as discussed yesterday we will apply sliding window yesterday we will apply sliding window we will use two pointers the time we will use two pointers the time complexity will be of of N and space complexity will be of of N and space complexity will be constant of o2c we complexity will be constant of o2c we will just get a frequency of 26. please will just get a frequency of 26. please check out that video for exact logic and check out that video for exact logic and if you have done this permutation and if you have done this permutation and string questions you can easily do this string questions you can easily do this question so see what we have to change question so see what we have to change we simply have to change uh let's see we simply have to change uh let's see what are this S1 is the smaller string what are this S1 is the smaller string now so here what we will do now so here what we will do we will simply copy paste the code and we will simply copy paste the code and we will change our we will change our S1 to p S1 to p s 1 to p and s12p and we will change our s 1 to p and s12p and we will change our S2 to s S2 to s 22s S2 to S and instead of returning 22s S2 to S and instead of returning true we will return our answer let's true we will return our answer let's create a vector answer and whenever our create a vector answer and whenever our total characters were becoming zero that total characters were becoming zero that is we have found the window when we are is we have found the window when we are knowing that this is the window so we knowing that this is the window so we will push our I to our answer and when will push our I to our answer and when we know this is our window we will push we know this is our window we will push I to our answer so that is all you have I to our answer so that is all you have to do just see the previous video and it to do just see the previous video and it is all easy see how these different is all easy see how these different questions are linked it is question questions are linked it is question number 438 this is 567 but both are number 438 this is 567 but both are linked if you can do this question you linked if you can do this question you can read this question can read this question so everything is linked please keep on so everything is linked please keep on practicing so let's just complete this practicing so let's just complete this we will simply write answer dot push we will simply write answer dot push back back hi we will post our answer and we will hi we will post our answer and we will return the answer Vector let's just run return the answer Vector let's just run and check whether it is working or not and check whether it is working or not so yeah it is running let's just submit so yeah it is running let's just submit it so yeah it is accepted so it is as simple as that you just need to form a sliding window approach you will apply a while loop everything else is explained in that video the video will be in the comment section as well please like share and subscribe if you like the video thank you so much for watching bye
2024-03-22 12:24:46
438
https://i.ytimg.com/vi_w…xresdefault.webp
Find All Anagrams in a String| Leetcode 438| C++| Easiest Explanation | Line by Line Code |DSA buddy
6zOTP0OFDYo
hello hello hello hi guys good morning welcome back to a new video and this we welcome back to a new video and this we a problem Leaf similar tree and we're a problem Leaf similar tree and we're going to see two variations of it as an going to see two variations of it as an first standard solution which everyone first standard solution which everyone would know but then a one optimized one would know but then a one optimized one which you may or might not know or might which you may or might not know or might you might get asked in an interview you might get asked in an interview let's see what the problem says it says let's see what the problem says it says that consider all leaves of a binary that consider all leaves of a binary tree from left to right order the values tree from left to right order the values of those leaves form a Leaf value of those leaves form a Leaf value sequence so basically I'll consider all sequence so basically I'll consider all leaves of this binary tree and this will leaves of this binary tree and this will form a leaf order sequence so Leaf order form a leaf order sequence so Leaf order sequence is 6 7 4 9 and 8 so I just want sequence is 6 7 4 9 and 8 so I just want that this is the leaf value sequence of that this is the leaf value sequence of the above binary tree now they are the above binary tree now they are saying that two binary tree are saying that two binary tree are considered Leaf similar if their Leaf considered Leaf similar if their Leaf value sequence which is the above value sequence which is the above sequence is actually the same so if I sequence is actually the same so if I have these two as the binary trees so if have these two as the binary trees so if I want to know that written true if they I want to know that written true if they are Leaf similar or not I have just are Leaf similar or not I have just written true or false then I'll just do written true or false then I'll just do one thing okay I'll just go and find out one thing okay I'll just go and find out what are the leaf nodes get them in one what are the leaf nodes get them in one sequence and then what are the leaf sequence and then what are the leaf nodes of the other tree get also them in nodes of the other tree get also them in other sequence and then ultimately I can other sequence and then ultimately I can simply as you can see I can simply go simply as you can see I can simply go and compare okay it is 6 and compare okay it is 6 7498 it is 674 98 oh yeah for sure they 7498 it is 674 98 oh yeah for sure they are LEF similar so that is the ultimate are LEF similar so that is the ultimate operation which I can do for us now um operation which I can do for us now um one basic thing which you have might one basic thing which you have might have thought of is obviously that I just have thought of is obviously that I just wanted the leaf nodes of this entire wanted the leaf nodes of this entire tree right and also the leaf noes let's tree right and also the leaf noes let's say it is a T1 tree it is a T2 tree I I say it is a T1 tree it is a T2 tree I I want the leaf nodes of this entire tree want the leaf nodes of this entire tree also and just want to put these Leaf also and just want to put these Leaf nodes in a vector I'll put them in a nodes in a vector I'll put them in a vector let's say this is a vector 6 7 4 vector let's say this is a vector 6 7 4 4 9 8 and again 6 7 4 9 8 and then I can 4 9 8 and again 6 7 4 9 8 and then I can just Traverse and compare this Vector just Traverse and compare this Vector okay these Vector value should be should okay these Vector value should be should be same that is I can simple do so what be same that is I can simple do so what I'm simply saying that I'll I'm simply saying that I'll Traverse both the trees now traversing Traverse both the trees now traversing means a simple DFS traverser a simple means a simple DFS traverser a simple traverser that and how a simple Travers traverser that and how a simple Travers looks like okay you you call a recursive looks like okay you you call a recursive function DFS function in which you pass function DFS function in which you pass in the root node ini root node you have in the root node ini root node you have passed base condition is okay if the passed base condition is okay if the node is n simply return and if not then node is n simply return and if not then simply try for left simply try right simply try for left simply try right that is a simple traversal condition now that is a simple traversal condition now no no no no no no no no no now now now no no no no no no no no no now now now in this you can put in any any condition in this you can put in any any condition maybe you want to print something you maybe you want to print something you can print something you want to print can print something you want to print here or here or here it can change it to here or here or here it can change it to in order pre-order post order and all in order pre-order post order and all that stuff so yeah this is a base that stuff so yeah this is a base traversal code piece of code which looks traversal code piece of code which looks like okay great um now both the trees VI like okay great um now both the trees VI D will Traverse and then we get only the D will Traverse and then we get only the Lea noes but what Leaf notes Leaf nodes Lea noes but what Leaf notes Leaf nodes are okay whose left is null whose right are okay whose left is null whose right is null that is simply a leaf node so is null that is simply a leaf node so whenever I am traversing and then if I whenever I am traversing and then if I reach okay let's say I traversed my tree reach okay let's say I traversed my tree okay I'm traversing and then I'll reach okay I'm traversing and then I'll reach to a node so this line of code I will to a node so this line of code I will put here and then I will say that okay put here and then I will say that okay if I have reached my node left is equals if I have reached my node left is equals to like null Ro node right is equal to to like null Ro node right is equal to null then I can simply return that node null then I can simply return that node value return that node value or I can value return that node value or I can simply say just you have the leaf Vector simply say just you have the leaf Vector right I have this Le Vector so simply right I have this Le Vector so simply push back this push back this specific push back this push back this specific node value in my leaf Vector because I node value in my leaf Vector because I have got the leaf vector and that's how have got the leaf vector and that's how I can simply get this code done now as I can simply get this code done now as you can see that uh invers case or you can see that uh invers case or basically in any case I will have to basically in any case I will have to have to travel on all the nodes because have to travel on all the nodes because to reach the leaf node you will have to to reach the leaf node you will have to go onto all the nodes right so for sure go onto all the nodes right so for sure the time is O of n now space is the time is O of n now space is interesting it is actually as you can interesting it is actually as you can see it's a DFS traversal so DFS see it's a DFS traversal so DFS traversal it depends upon the depth or traversal it depends upon the depth or the height of the tree so I know that my the height of the tree so I know that my DFS will go like this it will come back DFS will go like this it will come back it will go like this it will come back it will go like this it will come back it will go like this four it will come it will go like this four it will come back it will go like this so maximum dep back it will go like this so maximum dep is three 1 29 that will maximum depth so is three 1 29 that will maximum depth so I know okay my recursive stack will I know okay my recursive stack will actually be used and also my actually be used and also my leaf because you know now I was making leaf because you know now I was making two new vectors Leaf vectors so that two new vectors Leaf vectors so that leaf space is also used so that's my leaf space is also used so that's my time and space complexity although uh we time and space complexity although uh we will try to optimize this space maybe we will try to optimize this space maybe we can maybe we don't need this extra can maybe we don't need this extra Vector but yeah we'll see let's quickly Vector but yeah we'll see let's quickly have a glance of the code how it will have a glance of the code how it will look like so I initialize two vectors look like so I initialize two vectors leaves one and leaves two these will leaves one and leaves two these will actually store okay leaves one will actually store okay leaves one will store the store the leaves nodes in the sequence of 31 and leaves nodes in the sequence of 31 and leaves two same for 32 now I'll simply leaves two same for 32 now I'll simply call my DFS saying start from root one call my DFS saying start from root one with this Vector As Leaves one I'll pass with this Vector As Leaves one I'll pass this vector by address saying okay push this vector by address saying okay push back the NES as you can see exact same back the NES as you can see exact same tree traversal condition as we saw above tree traversal condition as we saw above if it is null simply return and just try if it is null simply return and just try for left just try for right and also now for left just try for right and also now the condition which I wanted to add is the condition which I wanted to add is that if both the left and right are that if both the left and right are actually null which means for sure it is actually null which means for sure it is a leaf node so just push back in the a leaf node so just push back in the leaves vector and that's how I can make leaves vector and that's how I can make my leaves Vector for one of the trees my leaves Vector for one of the trees and then the same I'll do for the other and then the same I'll do for the other tree and then I will have leaves one and tree and then I will have leaves one and leaves two ultimately I have to compare leaves two ultimately I have to compare that both the leaves one leaves two are that both the leaves one leaves two are equal and that's how I can simply get equal and that's how I can simply get this Sol now the interview ask you uh this Sol now the interview ask you uh bro can you improve this complexity bro can you improve this complexity you're storing all the leaf nodes right you're storing all the leaf nodes right in a new Vector so why you would need a in a new Vector so why you would need a new Vector the first place you might not new Vector the first place you might not okay great um so what we can do is okay okay great um so what we can do is okay we can okay my ultimate aim was to just we can okay my ultimate aim was to just see that okay the first the first My see that okay the first the first My ultimate aim was to just have a glance ultimate aim was to just have a glance that the first Leaf node should be same that the first Leaf node should be same okay then I'll compare the second Leaf okay then I'll compare the second Leaf node should be same okay great then the node should be same okay great then the third Leaf node should be same okay third Leaf node should be same okay great then the fourth Leaf node should great then the fourth Leaf node should be same okay great then the fifth leaf be same okay great then the fifth leaf node should be same so rather than node should be same so rather than storing I can compare one by one also storing I can compare one by one also but how to do that that's great um but how to do that that's great um simply earlier your operation was done simply earlier your operation was done by recursion now do the operation by by recursion now do the operation by yourself push that node in the stack yourself push that node in the stack okay I'll push my node three let's say okay I'll push my node three let's say it is for my it's a stack one for the it is for my it's a stack one for the tree one stack two for the tree two so tree one stack two for the tree two so firstly I push my root nodes in my tree firstly I push my root nodes in my tree then as soon as as soon as I enter my then as soon as as soon as I enter my stack I'll remove the top node I'll push stack I'll remove the top node I'll push the right okay I'll push the right I'll the right okay I'll push the right I'll push the left I'll push the left and I I push the left I'll push the left and I I I just keep on repeating that I just I just keep on repeating that I just keep on repeating that okay then I'll keep on repeating that okay then I'll remove the top node okay I'll remove the remove the top node okay I'll remove the top node see this is removed now this is top node see this is removed now this is removed the top node then I'll push the removed the top node then I'll push the right okay then I'll push the left okay right okay then I'll push the left okay then I'll again remove the top node okay then I'll again remove the top node okay I'll again remove the top node okay in I'll again remove the top node okay in my hand right now I have six I have my hand right now I have six I have removed that but I have six as the top removed that but I have six as the top node then I have left sorry I have right node then I have left sorry I have right no I don't I have left no I don't oh so no I don't I have left no I don't oh so it is a leaf node okay if it is a leaf it is a leaf node okay if it is a leaf node so simply return that stop your node so simply return that stop your stack right now stop your stack right stack right now stop your stack right now and simply whatsoever you had last now and simply whatsoever you had last just return that so you return the six just return that so you return the six okay so in this first iteration from okay so in this first iteration from stack one you have returned the six okay stack one you have returned the six okay let's go to stack two and perform the let's go to stack two and perform the first iteration okay again top remove first iteration okay again top remove from the top okay remove from the top from the top okay remove from the top push the right okay push the right then push the right okay push the right then push the left okay push the left okay push the left okay push the left okay sorry this is not okay push the left now sorry this is not okay push the left now again remove from Top remove the Top again remove from Top remove the Top push the right okay push the right and push the right okay push the right and then push the left okay push the left then push the left okay push the left and then now I just simply okay again and then now I just simply okay again remove from the top okay remove from the remove from the top okay remove from the top but see whenever I remove I actually top but see whenever I remove I actually maintain that in some variable again maintain that in some variable again check the right oh I don't have the check the right oh I don't have the right check the left oh I don't have the right check the left oh I don't have the left also okay no worries so this is a left also okay no worries so this is a leaf node okay Leaf node was six only so leaf node okay Leaf node was six only so now this stack one at the first cration now this stack one at the first cration will return six he will also return six will return six he will also return six so I can just say and compare oh bro it so I can just say and compare oh bro it is a six so yeah for sure it was a same is a six so yeah for sure it was a same Leaf not is matching then I'll again Leaf not is matching then I'll again I'll again have to continue I again have I'll again have to continue I again have to continue okay then I'll as you to continue okay then I'll as you remember last time my stack had two so remember last time my stack had two so I'll just say okay the stack top get two I'll just say okay the stack top get two remove that remove okay remove okay remove that remove okay remove okay removed then right side push okay right removed then right side push okay right side push four left side push left side side push four left side push left side push seven then okay remove from stack push seven then okay remove from stack okay removed right side nothing left okay removed right side nothing left side nothing oh it's a leaf node so side nothing oh it's a leaf node so seven was our Leaf node okay great seven was our Leaf node okay great although I remove this I should remove although I remove this I should remove this from here so now seven is from Leaf this from here so now seven is from Leaf is my leaf node okay that is a return is my leaf node okay that is a return from this here itself a seven I'll from this here itself a seven I'll remove from the stack right nothing left remove from the stack right nothing left nothing oh seven is also from the leaf nothing oh seven is also from the leaf node great it is also a leaf node so node great it is also a leaf node so simply my this Leaf node is also simply my this Leaf node is also matching okay then continue so you will matching okay then continue so you will see now I just show you with the see now I just show you with the reference of code also so you will see reference of code also so you will see that firstly I pushed my root node as that firstly I pushed my root node as you remember I pushed my root node in you remember I pushed my root node in the very beginning right when this is the very beginning right when this is done then I just check okay until my done then I just check okay until my stack is empty as you can see until my stack is empty as you can see until my stack has anything what I'm doing is I'm stack has anything what I'm doing is I'm simply calling my this function DFS simply calling my this function DFS although although it's return a DFS although although it's return a DFS function but is it is not a recursive function but is it is not a recursive function it is not a recursive function function it is not a recursive function it is actually a simple function it is it is actually a simple function it is not a recursive function right um it's a not a recursive function right um it's a simple function which will actually just simple function which will actually just check okay what is the top of the stack check okay what is the top of the stack it will just check okay top of Stack I it will just check okay top of Stack I will get that and store in a variable will get that and store in a variable let's say node then I will check Its let's say node then I will check Its Right child as you remember I checked Right child as you remember I checked right child I checked his left child if right child I checked his left child if any of them is there I'll just push them any of them is there I'll just push them and then and then I'll just check okay and then and then I'll just check okay okay if it is not there both of them okay if it is not there both of them then I can simply just do one thing okay then I can simply just do one thing okay bro um simply remove that uh or as in bro um simply remove that uh or as in like just say okay it's like just say okay it's a just simply return that and say it's a a just simply return that and say it's a leaf node so if I just visualize you leaf node so if I just visualize you with the example itself same this you with the example itself same this you remembered so I'll just meize with this remembered so I'll just meize with this the example S1 and S2 and piece of code the example S1 and S2 and piece of code dry running that so you you saw that I dry running that so you you saw that I had in the very beginning I had to to had in the very beginning I had to to push I had to push my root nodes okay push I had to push my root nodes okay root nodes I pushed three and three root nodes I pushed three and three again it will be same exactly same it's again it will be same exactly same it's just for you to compare the code three just for you to compare the code three and three I pushed now I just simply and three I pushed now I just simply call my until my stack is empty while my call my until my stack is empty while my stack is empty as you can see my stack stack is empty as you can see my stack is not empty it is having values so I is not empty it is having values so I just call this first function which is just call this first function which is saying okay stack one use you pass the saying okay stack one use you pass the stack one to the recursive Bic to a stack one to the recursive Bic to a function called as DFS again it's not a function called as DFS again it's not a recursive function it's just the same recursive function it's just the same naming convention which I followed now naming convention which I followed now it should return it should return the it should return it should return the leftmost current leftmost element of the leftmost current leftmost element of the leaf how it will return return it will leaf how it will return return it will go into this function again this will go into this function again this will also keep on going until until I have also keep on going until until I have something so firstly I'll get the node something so firstly I'll get the node so I just stored in my node my node so I just stored in my node my node value is three I removed I removed okay value is three I removed I removed okay my my my node value is three I I remove my my my node value is three I I remove that from my stack I if the left if I that from my stack I if the left if I have a right child as you can see as you have a right child as you can see as you can see I I remove that from start I had can see I I remove that from start I had I had a right child right okay I'll push I had a right child right okay I'll push that I'll push that I'll push that again that I'll push that I'll push that again if I have a left child yeah I have also if I have a left child yeah I have also five so I'll push that also I'll push five so I'll push that also I'll push that also then I'll check okay if my that also then I'll check okay if my both of them are null which means no bro both of them are null which means no bro uh both both are actually there none of uh both both are actually there none of them are null okay simply then continue them are null okay simply then continue continue while equal true okay if it is continue while equal true okay if it is continue then from the top of stack top continue then from the top of stack top is five okay remove that then check Its is five okay remove that then check Its Right check its left okay right I'll Right check its left okay right I'll check two left I'll check six okay right check two left I'll check six okay right is there left is there great then again is there left is there great then again is it is both the Childs null both child is it is both the Childs null both child oh it's not null okay cool simply oh it's not null okay cool simply continue top of the stack six see continue top of the stack six see whenever I'm saying top I actually am whenever I'm saying top I actually am saying it is top assigning that to a saying it is top assigning that to a node so right now six is the node value node so right now six is the node value same uh right and left um okay no right same uh right and left um okay no right no left okay no worries if uh right and no left okay no worries if uh right and left both are null return the node okay left both are null return the node okay yeah it is both are null so I'll simply yeah it is both are null so I'll simply return the node which was actually six return the node which was actually six so now from this this DFS for stack one so now from this this DFS for stack one it returned the number six and the same it returned the number six and the same way I will perform the operation on way I will perform the operation on stack two and as you remember it will stack two and as you remember it will also return the six so so you will see also return the six so so you will see that it will six it will be six if that it will six it will be six if they're not matching at any point of they're not matching at any point of time I can simply return false else I time I can simply return false else I can simply say that yeah it is matching can simply say that yeah it is matching now keep on continue while your stack is now keep on continue while your stack is not empty so it will start removing not empty so it will start removing other elements let's say it will remove other elements let's say it will remove two and then it will push my 4 and 7 4 two and then it will push my 4 and 7 4 and 7 then it will it will remove seven and 7 then it will it will remove seven it will put my note as seven and then it will put my note as seven and then you will see that seven has no child so you will see that seven has no child so it will be returned as a next Leaf node it will be returned as a next Leaf node and and that's how you can simply Solve and and that's how you can simply Solve It ultimately your both the stacks It ultimately your both the stacks should be empty ultimately your both should be empty ultimately your both Stacks should be empty because here I'm Stacks should be empty because here I'm saying that until my both the stacks are saying that until my both the stacks are non empty only then perform the non empty only then perform the operation so ultimately my both the operation so ultimately my both the stacks should be should be empty so for stacks should be should be empty so for sure I'll simply say that if it is both sure I'll simply say that if it is both the SS are empty I can simply return my the SS are empty I can simply return my answer now with this my time is still o answer now with this my time is still o ofn because I I will still have to go ofn because I I will still have to go onto all of my nodes but my space is onto all of my nodes but my space is actually of H only because now I'm only actually of H only because now I'm only using my cursive stack and I'm not using using my cursive stack and I'm not using I'm not I'm not again I'm not using any I'm not I'm not again I'm not using any Leaf Vector again um if you are allowed Leaf Vector again um if you are allowed to modify although it is not recommended to modify although it is not recommended to allow the input like to modify the to allow the input like to modify the input tree itself but if you're allowed input tree itself but if you're allowed to modify the input tree then what you to modify the input tree then what you can also do is you can try to build can also do is you can try to build something like this and with this you something like this and with this you would not be needing any extra space would not be needing any extra space Also so it is fun is also possible but Also so it is fun is also possible but we are never recommended to modify the we are never recommended to modify the input so yeah that is and for easy input so yeah that is and for easy question I think that is pretty much it question I think that is pretty much it I hope that you you guys got it that how I hope that you you guys got it that how we can use stack to actually reduce the we can use stack to actually reduce the space and much it's much more easy to space and much it's much more easy to visualize visualize cool bye-bye
2024-03-22 16:38:12
872
https://i.ytimg.com/vi/6…axresdefault.jpg
872. Leaf-Similar Trees | 2 Ways | Better - Optimal | Trees
_VWEotukbNc
hey everybody this is larry this is day nine of the leco nine of the leco april daily challenge hit the like april daily challenge hit the like button hit the subscriber and join me on button hit the subscriber and join me on discord let me know what you think about discord let me know what you think about today's forum today's forum uh vertifying an alien dictionary uh vertifying an alien dictionary um yeah some another classes there uh um yeah some another classes there uh but yeah but yeah i'm gonna find an alien dictionary so i i'm gonna find an alien dictionary so i you should do this live so it's a little you should do this live so it's a little bit slow fast forward 2x skip ahead bit slow fast forward 2x skip ahead watch another video whatever you need to watch another video whatever you need to do so okay let's see in the do so okay let's see in the indian language they have english indian language they have english letters for them letters for them in possible different order order of the in possible different order order of the alphabet is some permutation okay you're alphabet is some permutation okay you're given given the order of the alphabet return true of the order of the alphabet return true of the given words are sort of like the the given words are sort of like the graph of the in this alien language graph of the in this alien language okay okay so that's not so bad we just okay okay so that's not so bad we just have to see if it's sorted have to see if it's sorted we have a lookup table uh essentially in we have a lookup table uh essentially in an order and then we just an order and then we just um we can look for it one by one um um we can look for it one by one um so the cool thing is that we can only i so the cool thing is that we can only i mean you only need to look at adjacent mean you only need to look at adjacent um adjacent words because of the um adjacent words because of the transitive problem i know that transitive problem i know that it seems like if you're in kamsa and uh it seems like if you're in kamsa and uh and you'll probably notice that a lot of and you'll probably notice that a lot of not not mafi people say translated probably just mafi people say translated probably just say cool to sound cool say cool to sound cool but this is an actual thing of transit but this is an actual thing of transit probably where probably where where okay if a is bigger than b and b where okay if a is bigger than b and b is bigger than is bigger than c then a is bigger than c right um uh c then a is bigger than c right um uh if the transit property holds and this if the transit property holds and this is true um and is true um and and in a way um and in a way um you know and because this ordering is you know and because this ordering is going to be going to be uh you know the probably holds for uh you know the probably holds for transit probably so that means that we transit probably so that means that we only have to check only have to check that a is bigger than b and that b is that a is bigger than b and that b is bigger than c or bigger than c or if you want to put it another way uh if you want to put it another way uh which or w which or w sub 1 is bigger than w sub 2 is bigger sub 1 is bigger than w sub 2 is bigger than so you only have to look at than so you only have to look at adjacent words for that reason so they adjacent words for that reason so they don't have to do n square comparison don't have to do n square comparison so in this case n is 100 so it's not so in this case n is 100 so it's not that bad but uh but yeah that bad but uh but yeah um and then we look at two adjacent um and then we look at two adjacent words and then we check to see if the words and then we check to see if the word that's earlier word that's earlier is lexographically smaller or earlier is lexographically smaller or earlier than the word that is in later so that's than the word that is in later so that's basically basically all we have to do so let's um let's get all we have to do so let's um let's get let's do it let's do it i think there is some um implementation i think there is some um implementation of you know thank yous about this but uh of you know thank yous about this but uh but we can do it so but we can do it so let's do let's look up is to go to let's do let's look up is to go to whatever whatever for um index character for um index character in enumerate order we want to set lookup of c as we go to index so basically what this does is that it gets to the um get the rank if you will of the character and then we put it in a lookup table so that we could look at it all one time i think uh this is 26 characters we can actually even do better than that we can actually just um you know have a no have an array of 26 elements but i'm gonna do it this way for now because you would have to manipulate uh ascii and you know stuff like that um but so to keep it simple i'm gonna do in the hash table uh but this hash table of course is gonna be at most 26 characters so yeah um and then now we just have to go for you know for word um let's just say word one word two in sip of words word sub once uh this is a a python shorthand to get adjacent words uh so every pair of adjacent words um it's actu i to say it's common-ish in python so we haven't seen it um i'll get used to it a little bit because it does come in handy and at least in context in in uh in production code maybe it's a little bit more sketchy but i think it's still okay because these are all uh iterators so they don't actually take that much more space um but anyway like if you're worrying about it uh okay so now we have to go if uh let's just say let's just have a you know one is greater than row two uh then we return force it's first step we have to return yep and then otherwise if we go past all of them we return true and this is greater or equal i guess you want to be precise because actually no that's true i think grade is fine because if it's equal then it's it's okay though i don't know that it's yeah i mean then it doesn't violate the condition okay so yeah so definite we declare grade one grade two uh with one with two and then yeah and then now we just look counter by character yeah um yeah um i mean we can definitely do is the same i mean we can definitely do is the same trick where we get character trick where we get character you know in word one with two and then you know in word one with two and then if see if the lookup of c1 is greater if see if the lookup of c1 is greater than lookup of than lookup of c2 we return true c2 we return true right because basically now we're doing right because basically now we're doing a two pointers algorithm and we have to a two pointers algorithm and we have to make sure that we go for the cases make sure that we go for the cases because because that's not enough um otherwise if lookup that's not enough um otherwise if lookup is is less than lookup of c2 um then we're less than lookup of c2 um then we're going to already return true oh sorry going to already return true oh sorry we're going to return force we're going to return force um otherwise it's z quotes then we keep um otherwise it's z quotes then we keep going and then at the right and what going and then at the right and what does this mean right well the does this mean right well the the two cases or three cases one is the two cases or three cases one is uh you know well what happened here is uh you know well what happened here is that that the word is the same up to the min of the word is the same up to the min of the two words the two words uh the length of the two words and then uh the length of the two words and then now the three cases one is word one is now the three cases one is word one is longer longer where two is longer or they're all equal where two is longer or they're all equal size their equal size then size their equal size then it is force or if word two is longer is it is force or if word two is longer is force force so we just have to this is true if so we just have to this is true if length of word one length of word one is greater than length of word two um i is greater than length of word two um i think that's the case think that's the case that's why we have to write test and that's why we have to write test and double check um but yeah double check um but yeah so now we just have to put in more test so now we just have to put in more test cases this looks good but cases this looks good but uh one thing i would also say when uh one thing i would also say when you're you're testing especially in you're you're testing especially in competition you know one thing to notice competition you know one thing to notice is that is that this output is in binary right it's true this output is in binary right it's true of force of force it's boolean and what i mean by that is it's boolean and what i mean by that is that sometimes you can get that sometimes you can get quote-unquote lucky and it matches your quote-unquote lucky and it matches your answer even though it answer even though it is a wrong answer so you have to be is a wrong answer so you have to be careful about it this actually careful about it this actually those one of the cases that i would have those one of the cases that i would have etched um etched um but yeah but this looks okay so let's but yeah but this looks okay so let's give it a submit give it a submit and cross fingers cool and cross fingers cool uh yeah let's what is so what is the uh yeah let's what is so what is the complexity of this right complexity of this right well this for loop is going to be o of well this for loop is going to be o of n uh where n is the number of words n uh where n is the number of words because because you know you could think about it as you know you could think about it as just having two pointers and they move just having two pointers and they move uh they move together so that's going to uh they move together so that's going to be of uh be of uh n uh in terms of number of loops n uh in terms of number of loops and then this greater function just also and then this greater function just also linear linear in the length of the word so that's in the length of the word so that's going to be you know each word is going to be you know each word is or each character in each word will be or each character in each word will be looked at at most twice looked at at most twice once to compare to the word before and once to compare to the word before and another time to compare to the word another time to compare to the word after after so in that case you can kind of do the so in that case you can kind of do the summation or amortized or whatever summation or amortized or whatever to get to say that this is linear and to get to say that this is linear and the size of the input the size of the input where the size of the input is just it's where the size of the input is just it's not just n not just n it's the number of characters right um it's the number of characters right um where n may be the number of words but where n may be the number of words but the number of characters is roughly n the number of characters is roughly n times m if you want to call it that times m if you want to call it that where m is the length of the longest where m is the length of the longest word word but the words have different lengths but the words have different lengths which is why the phrasing is very which is why the phrasing is very precise precise um so and it's linear in the size of the um so and it's linear in the size of the input and of course input and of course as i mentioned before this is constant as i mentioned before this is constant because there's only 26 characters because there's only 26 characters you could also say it's off alphabet if you could also say it's off alphabet if you will be in you will be in that it is you know with the uh or that it is you know with the uh or all of the size of the alphabet which is all of the size of the alphabet which is all of alpha maybe all of alpha maybe which you know letter you want to use which you know letter you want to use where where where alpha is the length of the where alpha is the length of the alphabet so if you have you know alphabet so if you have you know uppercase now it's 52 characters or so uppercase now it's 52 characters or so forth right in weird order forth right in weird order um so yeah uh so this so everything's um so yeah uh so this so everything's gonna be linear time gonna be linear time uh do i use any space no i mean other uh do i use any space no i mean other than this this is constant space than this this is constant space so yeah linear time constant space and so yeah linear time constant space and that's all i have that's all i have uh let me know what you think hit the uh let me know what you think hit the like button hit the subscriber and drama like button hit the subscriber and drama and discord hope y'all have a great and discord hope y'all have a great weekend weekend and uh yeah stay good stay healthy to and uh yeah stay good stay healthy to good good health and to good mental health i'll health and to good mental health i'll see you tomorrow see you tomorrow bye bye
2024-03-25 12:12:56
953
https://i.ytimg.com/vi/_…axresdefault.jpg
953. Verifying an Alien Dictionary - Day 9/30 Leetcode April Challenge
rKnD7rLT0lI
everyone welcome back and let's write some more neat code today so today let's some more neat code today so today let's solve the problem flatten binary tree solve the problem flatten binary tree into a linked list we are given the root into a linked list we are given the root of a binary tree and we want to flatten of a binary tree and we want to flatten it so that it turns into a linked list it so that it turns into a linked list not necessarily a true linked list not necessarily a true linked list because you know this data structure because you know this data structure obviously is made up of tree nodes obviously is made up of tree nodes binary tree nodes where each node has binary tree nodes where each node has two pointers a left pointer and a right two pointers a left pointer and a right pointer but they want us to condense it pointer but they want us to condense it into a linked list where we're not into a linked list where we're not really making use of the left pointer really making use of the left pointer right for each right for each left pointer of each node it's just left pointer of each node it's just pointing at null the right pointer is pointing at null the right pointer is what we're actually going to be using what we're actually going to be using which is going to assemble all of these which is going to assemble all of these nodes into nodes into a linked list so this isn't too a linked list so this isn't too difficult to do but there is a catch the difficult to do but there is a catch the ordering of the linked list should be ordering of the linked list should be the same as the pre-order traversal of the same as the pre-order traversal of the binary tree now this isn't as bad as the binary tree now this isn't as bad as it sounds this is actually going to make it sounds this is actually going to make things really easy for us and let me things really easy for us and let me tell you why we know that a binary tree tell you why we know that a binary tree like this one is you know a recursive like this one is you know a recursive definition right a node a node a root definition right a node a node a root node like this one could have children node like this one could have children and then its children are basically also and then its children are basically also trees themselves right this is a sub trees themselves right this is a sub tree the left sub tree and this is the tree the left sub tree and this is the right subtree when they say it needs to right subtree when they say it needs to be the same as the pre-order traversal be the same as the pre-order traversal the linked list needs to be the same as the linked list needs to be the same as the pre-order traversal what they mean the pre-order traversal what they mean is if we want to flatten this entire is if we want to flatten this entire tree the root node is going to go first tree the root node is going to go first right because pre-order traversal uh right because pre-order traversal uh processes the root node first so good processes the root node first so good thing is we don't have to make any thing is we don't have to make any changes to the root node then changes to the root node then uh you know what is going to come next uh you know what is going to come next uh in our linked list to the right we uh in our linked list to the right we want to do the pre-order traversal right want to do the pre-order traversal right so we want to process the entire left so we want to process the entire left subtree meaning we want to flatten the subtree meaning we want to flatten the entire left subtree uh first right we entire left subtree uh first right we want to flatten this entire right want to flatten this entire right subtree and then stick it right in the subtree and then stick it right in the middle over here right in between the middle over here right in between the root node and in between the right child root node and in between the right child so once we flatten this thing it's going so once we flatten this thing it's going to go to go in between in between and then a pre-order traversal then will and then a pre-order traversal then will process the entire right subtree so then process the entire right subtree so then basically we want to flatten the entire basically we want to flatten the entire right subtree in this case the entire right subtree in this case the entire right subtree is already flattened right right subtree is already flattened right it's made up of two nodes and it's it's made up of two nodes and it's already flattened because there's no already flattened because there's no left child for any of the nodes here so left child for any of the nodes here so it's already flattened so really in this it's already flattened so really in this case our job is to flatten the left sub case our job is to flatten the left sub tree stick it in here and then we're tree stick it in here and then we're done but okay how do we flatten the left done but okay how do we flatten the left subtree it's a recursive definition subtree it's a recursive definition right so we're going to apply the exact right so we're going to apply the exact same recursive algorithm here uh as we same recursive algorithm here uh as we would on the root node so okay in order would on the root node so okay in order to flatten this tree first we have to to flatten this tree first we have to process the first node okay this it's a process the first node okay this it's a root node so it's not going to change root node so it's not going to change right pre-order traversal this node goes right pre-order traversal this node goes first it's going to stay exactly where first it's going to stay exactly where it is then we're going to flatten the it is then we're going to flatten the left sub-tree uh it's already flattened left sub-tree uh it's already flattened it's just a single node right so this it's just a single node right so this node is going to go now that it's flat node is going to go now that it's flat and it's going to go it's going to be and it's going to go it's going to be stuck in between here the three is going stuck in between here the three is going to go to go here and then here and then the right subtree here is also going to the right subtree here is also going to be flattened it's already flattened so be flattened it's already flattened so no changes are going to be made here so no changes are going to be made here so really we're going to get rid of this really we're going to get rid of this node and instead have a three node and instead have a three uh over here right so this is what the uh over here right so this is what the flattened is gonna look like then once flattened is gonna look like then once we're done with that this is gonna get we're done with that this is gonna get stuck in between here as you can see in stuck in between here as you can see in the output uh that's you know that's the output uh that's you know that's what happened so all of that hopefully what happened so all of that hopefully that logic that general recursive logic that logic that general recursive logic of this algorithm makes sense it of this algorithm makes sense it basically follows a pre-order traversal basically follows a pre-order traversal now the only challenge that we're gonna now the only challenge that we're gonna have is when we do have is when we do uh flatten the left subtree right over uh flatten the left subtree right over here you can see we flattened it and here you can see we flattened it and then we stick it in here how are we then we stick it in here how are we going to stick that flattened subtree or going to stick that flattened subtree or that linked list here well of course the that linked list here well of course the root node which over here you can see root node which over here you can see initially it's pointing you know at its initially it's pointing you know at its right child but we want to disconnect right child but we want to disconnect that pointer we want it not to point at that pointer we want it not to point at its right child anymore instead we want its right child anymore instead we want it to point to its a left child over it to point to its a left child over here right because we want to stick this here right because we want to stick this in between so we're going to reassign in between so we're going to reassign the right pointer uh you know to be the right pointer uh you know to be it's a little bit messy as i'm drawing it's a little bit messy as i'm drawing it now right but it now right but uh you know cross this pointer out and uh you know cross this pointer out and then stick that right pointer to then stick that right pointer to actually point here and then we want to actually point here and then we want to change the left pointer and have it change the left pointer and have it actually point to actually point to null right because the left pointer null right because the left pointer should always be null so that's what should always be null so that's what we're going to do to the root node and we're going to do to the root node and so the last thing we want to do is the so the last thing we want to do is the end of the linked list right the end of end of the linked list right the end of the left subtree the left subtree it should be pointing at this node over it should be pointing at this node over here right it should be pointing at the here right it should be pointing at the right child of the root node so the only right child of the root node so the only thing we're going to have to remember is thing we're going to have to remember is to actually get to actually get as we're doing this algorithm as we're doing this algorithm recursively we're going to make sure recursively we're going to make sure once we once we have flattened the once we once we have flattened the entire left sub tree we have to return a entire left sub tree we have to return a pointer to the last node or rather the pointer to the last node or rather the tail of the linked list if we have the tail of the linked list if we have the tail of the linked list then we can tail of the linked list then we can connect that pointer over to the right connect that pointer over to the right child of the root node which is what we child of the root node which is what we want to do because in the output you can want to do because in the output you can see right this uh you know this linked see right this uh you know this linked list the left child linked list has to list the left child linked list has to be connected to this which is the right be connected to this which is the right child linked list right this is the child linked list right this is the right sub tree the right flattened right sub tree the right flattened linked list so in order to do that we linked list so in order to do that we have to make sure that we return the have to make sure that we return the tail of the linked list so that we can tail of the linked list so that we can actually connect these pointers so actually connect these pointers so that's the main idea of the algorithm we that's the main idea of the algorithm we are going to do it recursively because are going to do it recursively because that's kind of the easiest way to logic that's kind of the easiest way to logic through it but you can do it iteratively through it but you can do it iteratively as well using a stack to traverse the as well using a stack to traverse the entire tree but since we are traversing entire tree but since we are traversing the entire tree uh the overall time the entire tree uh the overall time complexity is going to be big o of n complexity is going to be big o of n anywhere n is the number of nodes the anywhere n is the number of nodes the memory complexity since we're doing it memory complexity since we're doing it recursively we're going to have a call recursively we're going to have a call stack for the memory it's going to be stack for the memory it's going to be the memory is going to be a big o of h the memory is going to be a big o of h where h is the height of the tree uh you where h is the height of the tree uh you know worst case h ends up being n but know worst case h ends up being n but yeah so that's the time velocity now we yeah so that's the time velocity now we can get into the code okay now let's get can get into the code okay now let's get into the code so they do say that this into the code so they do say that this function actually doesn't need to return function actually doesn't need to return anything all we need to do is actually anything all we need to do is actually just modify the input tree that we're just modify the input tree that we're given so we'll be given a tree node it given so we'll be given a tree node it could be null it could not be null we could be null it could not be null we don't have to return anything but i'm don't have to return anything but i'm going to actually inside this function going to actually inside this function define another recursive function called define another recursive function called dfs we'll be doing the same thing with dfs we'll be doing the same thing with this function we'll be passing in the this function we'll be passing in the node so this dfs is what's going to node so this dfs is what's going to flatten flatten the tree flatten the root tree and the tree flatten the root tree and return return the list tail right because we do want the list tail right because we do want it to return something that's the main it to return something that's the main reason i'm defining another function reason i'm defining another function rather than just using this root rather than just using this root flattened function because this flattened function because this function is not supposed to return function is not supposed to return anything but here we do want to return anything but here we do want to return something because we do need to return something because we do need to return the tail values as always with tree the tail values as always with tree traversals if the input is null so traversals if the input is null so meaning if we're given an empty tree or meaning if we're given an empty tree or a null a null node then we can just return none node then we can just return none uh reason we're returning none is uh reason we're returning none is because can't flatten an empty tree so because can't flatten an empty tree so the tail of the empty tree is just going the tail of the empty tree is just going to be null to be null now is actually getting into the now is actually getting into the recursive case and you know before we recursive case and you know before we even finish the function i always just even finish the function i always just write the recursive case and just assume write the recursive case and just assume that it's going to work so when we run that it's going to work so when we run dfs of course we want to run dfs or dfs of course we want to run dfs or rather our flattened algorithm on the rather our flattened algorithm on the left subtree first and then we want to left subtree first and then we want to run it on our right subtree so assume run it on our right subtree so assume that this dfs call is going to flatten that this dfs call is going to flatten the subtrees what is it going to return the subtrees what is it going to return it's going to return the tail right so it's going to return the tail right so if we flatten the left subtree then if we flatten the left subtree then we're going to return the left tail so we're going to return the left tail so let's assign that and if we flatten the let's assign that and if we flatten the right subtree we're going to return the right subtree we're going to return the right tail now last thing we need to do right tail now last thing we need to do is actually connect our uh half you know is actually connect our uh half you know our linked lists right so we're at the our linked lists right so we're at the we're at a certain node we're at the we're at a certain node we're at the root node right we have a left uh linked root node right we have a left uh linked list that's been flattened and a right list that's been flattened and a right length list that's been flattened and length list that's been flattened and remember we want to connect them now remember we want to connect them now only edge case you have to remember is only edge case you have to remember is what if one of these lists is empty what if one of these lists is empty what's going to happen if both of them what's going to happen if both of them is empty then we don't need to do is empty then we don't need to do anything right if the right list is anything right if the right list is empty we still need to take the left empty we still need to take the left list and then you know move it over to list and then you know move it over to the right side if the left side is empty the right side if the left side is empty but the right side is not empty we have but the right side is not empty we have flattened the right side but we don't flattened the right side but we don't have to do anything because it's already have to do anything because it's already on the right side of the root right and on the right side of the root right and the left is already null so we don't the left is already null so we don't have to do anything so the only case have to do anything so the only case where we are going to do where we are going to do a uh insert operation is if the left a uh insert operation is if the left tail is non-null right that's the only tail is non-null right that's the only case where we actually have to do the case where we actually have to do the insert now this pointer manipulation can insert now this pointer manipulation can get a little bit abstract so feel free get a little bit abstract so feel free to draw out a picture if you want but to draw out a picture if you want but we're basically going to be following we're basically going to be following what i did in the drawing so what i did in the drawing so remember we have a left tail and we want remember we have a left tail and we want the next pointer of that left tail to be the next pointer of that left tail to be assigned to the current right child of assigned to the current right child of the root right so root dot the root right so root dot right so this is basically uh inserting right so this is basically uh inserting you know attaching the left you know attaching the left linked list attaching it to the right linked list attaching it to the right linked list and we also have to make linked list and we also have to make sure that the root is also attached to sure that the root is also attached to the left linked list so we have to say the left linked list so we have to say root dot left b or root dot root dot left b or root dot is gonna be set to uh is gonna be set to uh root dot left right because this is the root dot left right because this is the tail of the linked list right but we tail of the linked list right but we want the roots right pointer to be at want the roots right pointer to be at the beginning of the left linked list the beginning of the left linked list and what's going to be the beginning of and what's going to be the beginning of the left linked list it's just going to the left linked list it's just going to be the left child itself feel free to be the left child itself feel free to refer back to the drawing or you know refer back to the drawing or you know draw it out yourself if you need to for draw it out yourself if you need to for this this and remember the last thing we need to and remember the last thing we need to do is the root we want to make sure that do is the root we want to make sure that its left pointer is set to null uh right its left pointer is set to null uh right so we're going to do that last obviously so we're going to do that last obviously we're going to say root dot left is we're going to say root dot left is equal to equal to null because you know we have to do it null because you know we have to do it last because we we are using the last because we we are using the root.left's original value in this root.left's original value in this statement up above right and statement up above right and the reason why this line goes second is the reason why this line goes second is because we're reassigning root.right and because we're reassigning root.right and we are actually using root.write in the we are actually using root.write in the line up above so this order that i wrote line up above so this order that i wrote these three lines of code is not random these three lines of code is not random we had to do it this way because we had we had to do it this way because we had to use the original values of the to use the original values of the pointers before we ended up changing pointers before we ended up changing them but this is basically it this is them but this is basically it this is the entire insert operation and then the entire insert operation and then setting the left to null and we're only setting the left to null and we're only going to be doing that if the left uh going to be doing that if the left uh link the left tree is non-null right and link the left tree is non-null right and it's instead of even using left.tail we it's instead of even using left.tail we could even just say root.left is could even just say root.left is non-empty you know if this makes more non-empty you know if this makes more sense sense either one is fine i believe okay and either one is fine i believe okay and remember the last thing remember this remember the last thing remember this dfs is supposed to flatten and it's dfs is supposed to flatten and it's supposed to return the list of the tail supposed to return the list of the tail or you know the the tail of the list so or you know the the tail of the list so what is that gonna be isn't it true that what is that gonna be isn't it true that the the right tail you know the right sub tree's right tail you know the right sub tree's tail is gonna be the tail of the entire tail is gonna be the tail of the entire linked list or the entire tree like linked list or the entire tree like isn't that true that makes sense right isn't that true that makes sense right the the right tree's tail is gonna be the the right tree's tail is gonna be the entire tail but what if the right the entire tail but what if the right tail is null what if the right sub-tree tail is null what if the right sub-tree was empty then what's the tail gonna be was empty then what's the tail gonna be okay in that case the tail is going to okay in that case the tail is going to be the left tail right but what if the be the left tail right but what if the left the right subtree and the left sub left the right subtree and the left sub tree were empty so these tails happen to tree were empty so these tails happen to be null in that case the tail is going be null in that case the tail is going to end up being whatever the root is to end up being whatever the root is right because the root is the only node right because the root is the only node it doesn't have any left or right it doesn't have any left or right subtrees so this is the order if one if subtrees so this is the order if one if this is null then we'd return this if this is null then we'd return this if this is null then we return this you this is null then we return this you know you could write some if statements know you could write some if statements uh depending on what language you're uh depending on what language you're using but at least in python a little using but at least in python a little easy and neat way to write this code out easy and neat way to write this code out is to do with boolean so uh you know is to do with boolean so uh you know just put an or in between each of these just put an or in between each of these and the reason this works is because the and the reason this works is because the way python evaluates it is if this ends way python evaluates it is if this ends up being non-null then up being non-null then last will be assigned to the right tail last will be assigned to the right tail if it is null if it is null then it'll look at the next value and then it'll look at the next value and say okay is this null if it's non-null say okay is this null if it's non-null then this is what's going to be assigned then this is what's going to be assigned to last if both of these are null then to last if both of these are null then this one will definitely be non-null this one will definitely be non-null and this one will be assigned to last so and this one will be assigned to last so and then we can just return and then we can just return last so it's you know kind of an last so it's you know kind of an intuitive way for me at least in a intuitive way for me at least in a concise way to write this out so that's concise way to write this out so that's how i'm going to do it you could do with how i'm going to do it you could do with conditionals if you want and then all we conditionals if you want and then all we really need to do is call the the really need to do is call the the flattened function the dfs function flattened function the dfs function passing in the root node we don't have passing in the root node we don't have to return anything because remember our to return anything because remember our root function flattened doesn't require root function flattened doesn't require us to return anything so just calling us to return anything so just calling this function is good enough okay and this function is good enough okay and actually just got a quick typo so in actually just got a quick typo so in this line for some reason i wrote left this line for some reason i wrote left tail dot next when we actually want the tail dot next when we actually want the right pointer of left tail right because right pointer of left tail right because we're actually using the right pointers we're actually using the right pointers so sorry about that i hope that you so sorry about that i hope that you caught it and it wasn't too confusing caught it and it wasn't too confusing but otherwise let's run the code and it but otherwise let's run the code and it does work as you can see on the left does work as you can see on the left side it is a linear time algorithm it side it is a linear time algorithm it looks like the time complexity isn't looks like the time complexity isn't super efficient for whatever reason but super efficient for whatever reason but i don't pay too much attention to that i don't pay too much attention to that so i hope that this was helpful if it so i hope that this was helpful if it was please like and subscribe it was please like and subscribe it supports the channel a lot consider supports the channel a lot consider checking out my patreon where you can checking out my patreon where you can further support the channel if you'd further support the channel if you'd like and hopefully i'll see you pretty like and hopefully i'll see you pretty soon thanks for watching
2024-03-21 10:48:52
114
https://i.ytimg.com/vi/r…axresdefault.jpg
Flatten Binary Tree to Linked List - Leetcode 114 - Python
eVS33j13PWY
Hello Hi Everyone One Second Welcome To My Channel And Were Solving Another Important Channel And Were Solving Another Important Problem 30 Followers Have Already Like A Problem 30 Followers Have Already Like A Dasham Related Problems Like Subscribe Dasham Related Problems Like Subscribe My Channel Problem World Tour Of My Channel Problem World Tour Of Declaration Page Numbers From Subscribe And Declaration Page Numbers From Subscribe And All The Number Selected List Number 151 All The Number Selected List Number 151 Target What We Can Do Target What We Can Do Target What We Can Do Target 100th Candidate Fennel Mingle Target 100th Candidate Fennel Mingle Triplet 200 Run Extra for Life Oil Dry Triplet 200 Run Extra for Life Oil Dry ginger 20 - Wash Element Canon Laid Loop Also ginger 20 - Wash Element Canon Laid Loop Also Unlimited From Plus One to Nuvve Nuvve Nuvve Unlimited From Plus One to Nuvve Nuvve Nuvve and Third Loop from This Will Help to and Third Loop from This Will Help to Generate All Know One Generate All Know One Generate All Know One the appointed elements from we need to table from the subscribe from left to right in the subscribe from left to right in the Thursday acidification is from Thursday acidification is from infinity and compare subscribe if infinity and compare subscribe if you liked The Video then subscribe to you liked The Video then subscribe to Target I will also keep available Target I will also keep available Result will hold dialogue amid busy subscribe to subscribe Video Subscribe Carefully subscribe to subscribe Video Subscribe Carefully Subscribe 123 Number 90 Something Like Subscribe 123 Number 90 Something Like 100MB Don't Worry About the Values ​​Will 100MB Don't Worry About the Values ​​Will Not Not Quetta and Solution Show What We Can Do for Quetta and Solution Show What We Can Do for Solving Solving Solving Number One Adhoi Nuvve Nuvve Na Bhoole Aur Subscribe Ho Jayenge Is From The Start And And So Will Be Plus One Plus One K From This Is From - No What Do We Need To Find Out Which Will Win Within Himself Is Closed Within Himself Is Closed Within Himself Is Closed Down That This World Will Run Arrested Down That This World Will Run Arrested After District Will Check The Same Condition With After District Will Check The Same Condition With Bravery Defiant Reckoning Appointed And Will Have Two Bravery Defiant Reckoning Appointed And Will Have Two Point To Point Approach Subscribe Point To Point Approach Subscribe And Share And Minus Plus Minus One Plus Two Subscribe Abhinav Bhaiya Target Vansh Smart Is Point Sunao Award You Will Meet - 3 Results Of Middle Know How To The Point Will See A Disc Friends Hum Kalyan Samiti In Which Is Lungi Target Achieve What You Want To Increase The Current Affairs 28 Shoulder That How To Increase Btu Increase Time Increase This Loop Target Subscribe Now Increase This Loop Target Subscribe Now Increase This Loop Target Subscribe Now To Receive New Updates - 4 Plus One Subscribe - 30 - - Verb - New Delhi - 110 I Urgently Need To Update Our Samvida Debit The Receiver Pimples Page 16 Updated On That [ __ ] This Is Vote Against Nitish Check Subscribe Subscribe subscribe my channel and this I need to define jaayenge is is from that i plus one and k is from and minus then subscribe to The Amazing Subscribe That That That humor answer hindi result very agile scrum liquid compile and was given test according to wrong answer overhead instituted of - vishesh-2010 subscribe can we minus that agency near death experience let's trial summit to to to complexity of this code APN severe running a very easy language and spare some places a very easy language and spare some places in Bihar during various in Bihar during various demands met a fierce fighting back log demands met a fierce fighting back log subscribe and subscribe the Channel subscribe and subscribe the Channel thanks for
2024-03-19 15:42:03
16
https://i.ytimg.com/vi/e…axresdefault.jpg
3Sum Closest | Leetcode 16 | Two Pointer | Google Facebook Amazon
xHOe7AYAFfg
hello everyone welcome to clash encoder so in this video we will see the so in this video we will see the question that is swap nodes in pairs so question that is swap nodes in pairs so this is a linked linked list based this is a linked linked list based question and it has been asking a lot of question and it has been asking a lot of interviews for many companies interviews for many companies for the fang also and for other for the fang also and for other companies as well so this is a medium companies as well so this is a medium level question so let's see the problem level question so let's see the problem statement then we will see how to solve statement then we will see how to solve this and different techniques and then this and different techniques and then at last i will show you the code for at last i will show you the code for this problem in c plus plus so let's see this problem in c plus plus so let's see the problem statement so given a linked the problem statement so given a linked list swap every two adjacent nodes and list swap every two adjacent nodes and return its head so it is saying that we return its head so it is saying that we are given a linked list so linked list are given a linked list so linked list is one then one is pointing to so it has is one then one is pointing to so it has a value and a pointer so which is a value and a pointer so which is pointing to the next element one to two pointing to the next element one to two and two to three and three to four and and two to three and three to four and we have to swap every two adjacent nodes we have to swap every two adjacent nodes so we have to swap the nodes in pairs so so we have to swap the nodes in pairs so that is two will be swapped with one that is two will be swapped with one three will pitch five through four so three will pitch five through four so you can see the output will be two one you can see the output will be two one four and three so these two elements are four and three so these two elements are swapped and these two elements are swept swapped and these two elements are swept so and return its head so head will be so and return its head so head will be now swapped head will be two so two will now swapped head will be two so two will be set with one and it will become the be set with one and it will become the head so we have to return the head and head so we have to return the head and you must solve the problem without you must solve the problem without modifying the values in the list node modifying the values in the list node that is the nodes themselves must may be that is the nodes themselves must may be changed so that it is changed so that it is their question is that we cannot change their question is that we cannot change the values so we cannot change the value the values so we cannot change the value in this node by changing it with two and in this node by changing it with two and this with one so we have to change the this with one so we have to change the actual nodes or swap the actual nodes actual nodes or swap the actual nodes and change the links between them to and change the links between them to give this output of the swapped nodes give this output of the swapped nodes and let's see the constraints on this and let's see the constraints on this problem so it says that the number of problem so it says that the number of the nodes in the list is in range 0 to the nodes in the list is in range 0 to 100 and node value will be from 0 to 100 100 and node value will be from 0 to 100 so this won't be any useful for the so this won't be any useful for the value uh this you can simply we will value uh this you can simply we will actually we don't need this constraint actually we don't need this constraint so let's see so i can think of one case so let's see so i can think of one case actually you can see we have to swap the actually you can see we have to swap the elements in pair so if what if we get elements in pair so if what if we get the odd link please this is for the even the odd link please this is for the even so for even you will have every so for even you will have every you will have each element for every you will have each element for every element that means you will have a pair element that means you will have a pair equal number of pairs but if you have equal number of pairs but if you have you can see the let's see these cases so you can see the let's see these cases so in this case you can see we are given an in this case you can see we are given an empty link list so we will simply return empty link list so we will simply return empty and for this one so it is odd case empty and for this one so it is odd case so we will simply done one so that means so we will simply done one so that means that if we are given a number of uh that if we are given a number of uh number of nodes in a linked list is odd number of nodes in a linked list is odd then we will swap the even number of then we will swap the even number of elements but the odd will remain as it elements but the odd will remain as it is so what i am trying to say is if we is so what i am trying to say is if we are given one two and three so there are are given one two and three so there are three elements so we will swap one and three elements so we will swap one and two but we will leave three as it is so two but we will leave three as it is so output will be two one and then three so output will be two one and then three so that would be one of the case so let's that would be one of the case so let's see how we can solve this question and see how we can solve this question and also if uh the interval when interval also if uh the interval when interval tells you or tell you this problem or tells you or tell you this problem or ask you this problem then if he may not ask you this problem then if he may not tell uh that uh tell uh that uh you cannot change the values then you you cannot change the values then you can start the problem by saying that you can start the problem by saying that you can actually change the values in the can actually change the values in the nodes without swapping them so you can nodes without swapping them so you can start with that problem then he will start with that problem then he will give you the constraint that you cannot give you the constraint that you cannot change the values but you will have to change the values but you will have to change the links or the actual nodes change the links or the actual nodes also have the actual nodes so then you also have the actual nodes so then you will start with the problem the actual will start with the problem the actual solution so let's find out how we can solution so let's find out how we can solve this so i have made this solve this so i have made this representation so you can see this is representation so you can see this is our input one two three and four these our input one two three and four these are the pointers one is one two and this are the pointers one is one two and this is the output that we want two should is the output that we want two should point to one one should point to four point to one one should point to four and four should point to three so let's and four should point to three so let's see how we can do this so actually see how we can do this so actually if you see how we can make this output if you see how we can make this output so we will have to process nodes so we will have to process nodes in pairs so if you see we will we cannot in pairs so if you see we will we cannot start the uh processing the linked list start the uh processing the linked list as one linked list so we will have to uh as one linked list so we will have to uh process first two nodes we have to process first two nodes we have to change the links between two and one and change the links between two and one and this will also involve actually changing this will also involve actually changing the link between the third node also the link between the third node also which will not be swapped in this pair which will not be swapped in this pair because the new node should point to the because the new node should point to the next node otherwise this link will be next node otherwise this link will be lost this two pointing to three if we lost this two pointing to three if we swap this one and do so let's see how we swap this one and do so let's see how we can do that so if you have solved a can do that so if you have solved a reverse link list so you may get the reverse link list so you may get the idea of how to solve this but if you see idea of how to solve this but if you see now what we have to do is we have to do now what we have to do is we have to do three steps so first we have to swap the three steps so first we have to swap the link between two and one so we have to link between two and one so we have to change this to here and this one should change this to here and this one should point to three so it should point to point to three so it should point to three so this is a simple thing that we three so this is a simple thing that we have to do but for doing that if you see have to do but for doing that if you see so if we do this so we can we will lose so if we do this so we can we will lose the uh we will lose the pointer to two the uh we will lose the pointer to two actually the pointing at the node actually the pointing at the node pointing to head basically we need the pointing to head basically we need the head also so what we can do is we can head also so what we can do is we can simply create a new dummy node which simply create a new dummy node which will point to the head so this is a will point to the head so this is a dummy node which will point to head and dummy node which will point to head and i will tell you the solution which will i will tell you the solution which will be simpler one we can simply use two be simpler one we can simply use two pointers to solve this problem first we pointers to solve this problem first we will create a header node new node dummy will create a header node new node dummy node you can say and we will keep we node you can say and we will keep we will make a new pointer which is will make a new pointer which is previous pointer which will point to previous pointer which will point to this header node and we will make a this header node and we will make a current pointer which will point to the current pointer which will point to the actual or the original head node this is actual or the original head node this is our current pointer so now our current pointer so now first step will be our first step will first step will be our first step will be to change the pointer between the be to change the pointer between the previous node to the two because this previous node to the two because this needs to be head so at last we will not needs to be head so at last we will not return this dummy node we will return return this dummy node we will return dummy dot next which will return the dummy dot next which will return the actual header or the actual linked list actual header or the actual linked list so let's see so first we have to swap or so let's see so first we have to swap or we have to change or cut this link and we have to change or cut this link and make it point to two so this previous make it point to two so this previous should 2.2 because 2 will be the should 2.2 because 2 will be the starting of the new linked list or what starting of the new linked list or what we have to return the output so to do we have to return the output so to do that this you can see the current is 1 that this you can see the current is 1 to 1 so previous should point to current to 1 so previous should point to current snags so this this previous next which snags so this this previous next which should point to currents next so our should point to currents next so our first step will be to cut this link so first step will be to cut this link so we can simply will do previous dot next we can simply will do previous dot next should point to currents next then again should point to currents next then again now we have to do the next step because now we have to do the next step because basically we change this pointer so one basically we change this pointer so one is also one two two and previous is also is also one two two and previous is also pointing to two so we don't need this pointing to two so we don't need this link so you know that in the output one link so you know that in the output one should point to three not the should point to three not the not in the output but in the first app not in the output but in the first app one should point to three because we one should point to three because we will have to change this to pointer to will have to change this to pointer to one two should point to one in the one two should point to one in the output so we need to uh some node which output so we need to uh some node which should point to three to maintain this should point to three to maintain this as a single linked list not break the as a single linked list not break the links so let's see how we can do that so links so let's see how we can do that so basically if you see previous is basically if you see previous is pointing to 2 and 2 is pointing to 3 so pointing to 2 and 2 is pointing to 3 so we need the 1 we need the 1 2. 3 so 2. 3 so how we can do that so basically if you how we can do that so basically if you see previous next is 2 and 2's next is see previous next is 2 and 2's next is three so we can simply change the link three so we can simply change the link by changing this currents next so by changing this currents next so currents next should point to this currents next should point to this previous next dot next so then this link previous next dot next so then this link will uh become so this there this would will uh become so this there this would be the new link so now we don't need be the new link so now we don't need this link will be this thing will break this link will be this thing will break so you can see this link will break so you can see this link will break so now we have done two steps we have so now we have done two steps we have changed the pointer from previous to two changed the pointer from previous to two and then one to three so now we need and then one to three so now we need this to this this is useless now you can this to this this is useless now you can see two is point three and one is also see two is point three and one is also pointing to three so we need to point to pointing to three so we need to point to one so see we can simply do that but you one so see we can simply do that but you can see can see by changing the link uh using same pre by changing the link uh using same pre previous uh previous pointers next that previous uh previous pointers next that is two and two's next which is this link is two and two's next which is this link should point to current so this will should point to current so this will point to current now our linked list point to current now our linked list will become like previous previous this will become like previous previous this is this is previous 2 2 is pointing to 1 is this is previous 2 2 is pointing to 1 and 1 is pointing to 3 and then 3 is and 1 is pointing to 3 and then 3 is pointing to 4 so this now this is the pointing to 4 so this now this is the previous here is our previous here is our current so this is the first step now we current so this is the first step now we have to again perform this step to have to again perform this step to reverse this links these links as well reverse this links these links as well so for that we can simply do that we so for that we can simply do that we will have to simply change the pointers will have to simply change the pointers this we will we have to do this all this this we will we have to do this all this in a loop so let me also write the steps in a loop so let me also write the steps so i will copy the steps also so it will so i will copy the steps also so it will now let's see the this steps and see uh now let's see the this steps and see uh run it on dual dry run on this example run it on dual dry run on this example so first we will create uh so i have not so first we will create uh so i have not written that step but we will create a written that step but we will create a dummy node which whose next will point dummy node which whose next will point to the original node that we will have to the original node that we will have to return as output so dummy node will to return as output so dummy node will point to 2 at the end of this loop so point to 2 at the end of this loop so that we have to return so we will create that we have to return so we will create a dummy node which will point to 1 and a dummy node which will point to 1 and we will create new pointer that is we will create new pointer that is previous pointer and point it to the w previous pointer and point it to the w node first and then the current will node first and then the current will point to the head node you can see this point to the head node you can see this will point to the head node so now when will point to the head node so now when we start this loop so you can see we start this loop so you can see current is not equal to null and current current is not equal to null and current next is not also not equal to null so next is not also not equal to null so current next is also not not null and current next is also not not null and this is also not known and why we are this is also not known and why we are checking these two conditions as i have checking these two conditions as i have already told this is for the even case already told this is for the even case and this is for the odd number of nodes and this is for the odd number of nodes if there are number of node so current if there are number of node so current is not null but currents next is null so is not null but currents next is null so there that means that one is there but there that means that one is there but two is not there so we cannot swap two is not there so we cannot swap single element so we will simply turn single element so we will simply turn one one so so this loop will actually not return so so this loop will actually not return and this is also the base case so before and this is also the base case so before writing this condition you will have to writing this condition you will have to check if the head is null then simply check if the head is null then simply return the head if that's next is also return the head if that's next is also null then also simply return the head so null then also simply return the head so we will if there is we will if there is no element then return head if there is no element then return head if there is a single element then also return the a single element then also return the head because we cannot swap null element head because we cannot swap null element or we cannot swap a single element so or we cannot swap a single element so let's continue the trident so you can let's continue the trident so you can see these conditions are satisfying so see these conditions are satisfying so over while loop will run so previous over while loop will run so previous next will point to current snags so next will point to current snags so previous next is this so this link will previous next is this so this link will break and it will point to current stack break and it will point to current stack so current sects is 2. so now it is so current sects is 2. so now it is pointing to two so now in this next step pointing to two so now in this next step you can see the currents next will point you can see the currents next will point to previous next next so previous next to previous next next so previous next next is you can see previous next is two next is you can see previous next is two and two's next is three so this link and two's next is three so this link will break currents next this link will will break currents next this link will break so we will simply break this thing break so we will simply break this thing and it will point to and it will point to three so you can see we have done two three so you can see we have done two steps so we have broken this link and steps so we have broken this link and one is pointing to three and previous is one is pointing to three and previous is pointing to two now we will follow the pointing to two now we will follow the third step to point the 2 to 1 because 2 third step to point the 2 to 1 because 2 is also going to 3 and 1 is also 0.23 is also going to 3 and 1 is also 0.23 which is not useful so now we will which is not useful so now we will remove this link and you can see remove this link and you can see previous next next so which is previous previous next next so which is previous nexus 2 and 2's next was 3 so we will nexus 2 and 2's next was 3 so we will make this to 0.21 so now we have done make this to 0.21 so now we have done these steps now our output is you can these steps now our output is you can see previous see previous and it is pointing to 2 2 is pointing to and it is pointing to 2 2 is pointing to 1 and 1 responding to 3 1 and 1 responding to 3 and three is pointing to four sorry for and three is pointing to four sorry for the unwriting so yeah so zero is the unwriting so yeah so zero is pointing to a two and you can see we pointing to a two and you can see we have successfully swapped these two have successfully swapped these two nodes and we will have to continue doing nodes and we will have to continue doing this for all the other nodes while the this for all the other nodes while the condition is true so to do that what we condition is true so to do that what we have to do you can see these two steps have to do you can see these two steps are for in are for in actually incrementing the pointers so actually incrementing the pointers so this previous should point to now the this previous should point to now the current so crown current is one as you current so crown current is one as you know current was pointing at one so know current was pointing at one so previous should come at one okay this previous should come at one okay this will come at one and the current will go will come at one and the current will go to currents next which is three current to currents next which is three current wise is here wise is here and now it will point here so now you and now it will point here so now you can see now uh you here you can see the can see now uh you here you can see the previous is at one and this current is previous is at one and this current is at three now same steps will occur now at three now same steps will occur now one will start pointing to four which is one will start pointing to four which is currents next previous will start currents next previous will start pointing to four pointing to four and then the uh this four will start and then the uh this four will start pointing to three and first of all we pointing to three and first of all we will break the link basically currents will break the link basically currents next which is three four so three will next which is three four so three will actually start pointing to previous next actually start pointing to previous next next which is null here so three next which is null here so three this pointer will point to null because this pointer will point to null because three is three is at a last element so this is not at a last element so this is not pointing anywhere you can see in the pointing anywhere you can see in the output so it will be becoming null in output so it will be becoming null in this condition this 3 will point to this condition this 3 will point to nothing so it will become null so it nothing so it will become null so it will break now will break now we have to now point this 2 is 4.4 you we have to now point this 2 is 4.4 you can see and 3 is null so now to point can see and 3 is null so now to point this four to three this is the condition this four to three this is the condition you can see this is the step previous you can see this is the step previous next previous next dot next so which is next previous next dot next so which is uh once next four and fours next which uh once next four and fours next which is null and will now point to current is null and will now point to current current is on three so four will start current is on three so four will start pointing to three and at last we will pointing to three and at last we will get our output you can see uh uh sorry get our output you can see uh uh sorry this is not the uh this will be two one this is not the uh this will be two one and yeah two one four and three and at and yeah two one four and three and at last when this loop ends we will simply last when this loop ends we will simply turn previous next as the output so our turn previous next as the output so our output will be previous next so uh the output will be previous next so uh the time complexity actually for this will time complexity actually for this will be o of n because you will be simply be o of n because you will be simply traversing the linked list one time so traversing the linked list one time so the time complexity will be of n and the the time complexity will be of n and the space complexity will be o often it will space complexity will be o often it will be constant because we are not uh be constant because we are not uh creating any new linked list so we are creating any new linked list so we are simply swapping the links and we are simply swapping the links and we are creating just a constant or you can see creating just a constant or you can see just a new pointer so which is counted just a new pointer so which is counted as constant so it will be same for any as constant so it will be same for any length of the linked place so let's see length of the linked place so let's see the code i hope you understand this so the code i hope you understand this so let's see the code support will be in c let's see the code support will be in c plus plus plus plus so i've already written the code so i so i've already written the code so i will explain you so it will be similar will explain you so it will be similar to the algorithm that i have shown the to the algorithm that i have shown the steps so you can see so this is our steps so you can see so this is our function in which we have to write the function in which we have to write the code so here we are given the head so it code so here we are given the head so it is of type is of type list node which is having two values list node which is having two values value and the next pointer so now we value and the next pointer so now we will check if head is not head is null will check if head is not head is null or heads next is null so these two or heads next is null so these two conditions are for these two cases you conditions are for these two cases you can see the base cases are already can see the base cases are already provided in the question so if it is provided in the question so if it is null so we will simply return the head null so we will simply return the head which will be null only and if there is which will be null only and if there is a single element then we will simply a single element then we will simply turn the head also again help because we turn the head also again help because we cannot swap the simple a single element cannot swap the simple a single element so you can see now we will create two so you can see now we will create two point uh this new first of all we will point uh this new first of all we will create a dummy node so this new head is create a dummy node so this new head is a dummy node so it will point to uh it a dummy node so it will point to uh it will yeah here you can see this previous will yeah here you can see this previous so previous will point to new head as i so previous will point to new head as i told in this step so uh yeah told in this step so uh yeah so here you can see previous is pointing so here you can see previous is pointing to the first it was it is pointing to to the first it was it is pointing to this dummy so it we have initialized it this dummy so it we have initialized it to a dummy node and the current will to a dummy node and the current will point to head so head is one so current point to head so head is one so current spanning to one so now we have to start spanning to one so now we have to start our loop while current and current our loop while current and current snakes is there so this is for the even snakes is there so this is for the even case and this is for the odd number of case and this is for the odd number of nodes case now we will follow over three nodes case now we will follow over three steps first we will break the pointer or steps first we will break the pointer or we will make the previous point to the we will make the previous point to the currents next so this pointer will start currents next so this pointer will start pointing to two which is once next pointing to two which is once next currents next and then we will break the currents next and then we will break the link between this current next and we link between this current next and we will make it point to the three which is will make it point to the three which is two's next or you can say previous next two's next or you can say previous next next so it will point to three now and next so it will point to three now and now again we as we have to now again we as we have to as we have to change this two and ones as we have to change this two and ones pointer also so we will make this two pointer also so we will make this two point two one so that is that can be point two one so that is that can be done by previous next next which is uh done by previous next next which is uh previous next two and two is next is uh previous next two and two is next is uh this link was broken and it was made we this link was broken and it was made we made it two point two one which is made it two point two one which is current then again we have to continue current then again we have to continue for other nodes as well so we will for other nodes as well so we will increment our pointers in each iteration increment our pointers in each iteration of these two so previous will come to of these two so previous will come to current position and current will go to current position and current will go to the next element and again the same the next element and again the same steps will start and at the last we will steps will start and at the last we will simply turn this dummy node this was the simply turn this dummy node this was the dummy node so we don't have to return dummy node so we don't have to return this so we will return dummies next so this so we will return dummies next so now let's submit this question so we'll now let's submit this question so we'll also provide the code in the description also provide the code in the description so i will highly recommend you to first so i will highly recommend you to first solve this problem yourself and quote it solve this problem yourself and quote it and then if you are not able to then you and then if you are not able to then you can go through the solution and then can go through the solution and then write the solution yourself again so you write the solution yourself again so you can see it was submitted successfully can see it was submitted successfully and you can see it is faster than 50 of and you can see it is faster than 50 of the solutions and it took less memory the solutions and it took less memory than seven point six percent of the than seven point six percent of the solutions so i hope you like this video solutions so i hope you like this video and this was a iterative solution and if and this was a iterative solution and if you want me to make the solution for the you want me to make the solution for the recursive uh way then yeah please write recursive uh way then yeah please write down in the comment section i will also down in the comment section i will also make the video for the recursive make the video for the recursive solution thank you for watching guys do solution thank you for watching guys do like subscribe and like share this video like subscribe and like share this video with your friends thank you for watching
2024-03-19 18:07:10
24
https://i.ytimg.com/vi/x…axresdefault.jpg
SWAP NODES IN PAIRS | ITERATIVE SOLUTION | LEETCODE-24
ZLKtohU3YpE
hello and welcome back to the cracking fang youtube channel today we're going fang youtube channel today we're going to be solving lead code problem 1361 to be solving lead code problem 1361 validate binary tree nodes you have n validate binary tree nodes you have n binary tree nodes numbered from 0 to n binary tree nodes numbered from 0 to n minus 1 where node of i has minus 1 where node of i has two children left child of eye and right two children left child of eye and right child of i return true if and only if child of i return true if and only if the given nodes form exactly one valid the given nodes form exactly one valid binary tree binary tree if node i has no left child then left if node i has no left child then left child of i will equal negative 1 and child of i will equal negative 1 and similarly for the right child similarly for the right child note that the nodes have no values note that the nodes have no values note that the nodes have no values and note that the nodes have no values and then we only use the node numbers in then we only use the node numbers in this problem which just makes this this problem which just makes this question even more annoying question even more annoying so so let's look at some of the examples that let's look at some of the examples that lead code provides us and think about lead code provides us and think about whether or not this is a valid binary whether or not this is a valid binary tree tree so in this question as we can see this so in this question as we can see this is a valid binary tree why well there's is a valid binary tree why well there's only one root only one root each each um you know node has only one parent and um you know node has only one parent and it has at maximum kind of two children it has at maximum kind of two children so this is a valid tree so this is a valid tree this one however is not a valid tree why this one however is not a valid tree why well this node three has two parents two well this node three has two parents two and one we can only have one parent for and one we can only have one parent for a node so this is not a valid tree a node so this is not a valid tree what about this one this looks like it what about this one this looks like it could be a valid binary tree but notice could be a valid binary tree but notice that this direction here is that this direction here is bi-directional which means that we bi-directional which means that we essentially have a cycle in our tree essentially have a cycle in our tree here and you're not allowed to do that here and you're not allowed to do that typically in trees you have you know a typically in trees you have you know a parent which has a left and a right parent which has a left and a right pointer but you don't have a pointer up pointer but you don't have a pointer up to the parent so this is not a valid to the parent so this is not a valid tree tree so so this question is more of a question of this question is more of a question of building your binary tree which is the building your binary tree which is the first step of this question first step of this question is to actually you know build the tree is to actually you know build the tree or at least build or at least build whatever you can of it because we'll see whatever you can of it because we'll see that there's a lot of edge cases here so that there's a lot of edge cases here so we're going to try to build the tree and we're going to try to build the tree and the second is going to be to validate the second is going to be to validate whether or not our tree is actually whether or not our tree is actually valid valid and there's going to be three edge cases and there's going to be three edge cases that we want to watch out for the first that we want to watch out for the first edge case is going to be cycles right edge case is going to be cycles right this is the case where this is the case where a child points to its parent and then a child points to its parent and then the parent points the child obviously we the parent points the child obviously we can't have that the second thing we want can't have that the second thing we want to watch out for is actually going to be to watch out for is actually going to be multiple multiple uh multiple roots oops multiple roots uh multiple roots oops multiple roots right what if there's just another node right what if there's just another node kind of like 2 floating out here and kind of like 2 floating out here and it's not connected to anything obviously it's not connected to anything obviously this is not a valid tree because you this is not a valid tree because you have multiple nodes that could be the have multiple nodes that could be the root of our tree so this 2 isn't root of our tree so this 2 isn't connected to anything and therefore we connected to anything and therefore we want to watch out for that so we want to want to watch out for that so we want to make sure essentially starting from make sure essentially starting from whatever we think the root of our tree whatever we think the root of our tree is we want to make sure that we can is we want to make sure that we can actually visit all the nodes in the tree actually visit all the nodes in the tree that we have given to us and if we can't that we have given to us and if we can't visit all of them then that means that visit all of them then that means that there's one kind of just floating in there's one kind of just floating in space space and and therefore it's not a valid tree and the therefore it's not a valid tree and the last thing we want to watch out for is last thing we want to watch out for is going to be multiple going to be multiple uh parents whoops parents uh parents whoops parents and obviously this is this case here and obviously this is this case here where three has two parents which is not where three has two parents which is not allowed this isn't a graph so we can allowed this isn't a graph so we can only have one parent for each node only have one parent for each node and the only node that's allowed to have and the only node that's allowed to have no parent is going to be whatever our no parent is going to be whatever our root note is because obviously the root root note is because obviously the root does not have a parent it is the entry does not have a parent it is the entry point into our tree so that's what we point into our tree so that's what we want to do we want to build the tree and want to do we want to build the tree and then we want to validate it and we want then we want to validate it and we want to watch for these three things as we go to watch for these three things as we go through through it's it's quite a meaty problem this question is quite a meaty problem this question is more about the edge cases and how you more about the edge cases and how you handle them as opposed to the actual handle them as opposed to the actual logic logic actually validating the tree isn't that actually validating the tree isn't that bad it's just making sure that all three bad it's just making sure that all three of these things are you know not of these things are you know not violated that makes this question violated that makes this question annoying it's more of technically annoying it's more of technically difficult to implement than it is difficult to implement than it is actually conceptually so let's go to the actually conceptually so let's go to the code editor and type this out it is code editor and type this out it is quite a long and meaty question so we're quite a long and meaty question so we're gonna break it down line by line i'll gonna break it down line by line i'll see you in the editor okay we are in the see you in the editor okay we are in the editor and we need to write the code for editor and we need to write the code for this remember that we essentially need this remember that we essentially need to build a binary tree and validate to build a binary tree and validate whether or not it's valid given the whether or not it's valid given the criteria that we have criteria that we have so so we don't have the time in an interview we don't have the time in an interview setting to actually code up you know a setting to actually code up you know a binary tree class and then a binary tree binary tree class and then a binary tree node class and all that nonsense um so node class and all that nonsense um so what we're going to do is we're going to what we're going to do is we're going to mimic a binary tree by simply using a mimic a binary tree by simply using a dictionary to mock the binary tree and dictionary to mock the binary tree and what we're going to do is we're going to what we're going to do is we're going to have two dictionaries have two dictionaries one storing the relationship between one storing the relationship between parent to children and then we're going parent to children and then we're going to have children to parent so that way to have children to parent so that way we know all of the relationships in our we know all of the relationships in our tree tree so so what we want to do is define those two what we want to do is define those two dictionaries so let's do that so we're dictionaries so let's do that so we're going to say going to say parent to children parent to children we're going to say collections dot we're going to say collections dot default dict list and obviously it's a default dict list and obviously it's a list as the value because a parent can list as the value because a parent can have multiple children and then we're have multiple children and then we're going to have child to parent and this going to have child to parent and this is going to be a dictionary is going to be a dictionary and that's what we need to do so now we and that's what we need to do so now we actually need to build the graph so actually need to build the graph so remember that n represents the you know remember that n represents the you know each individual node and then left child each individual node and then left child of i guess i of i guess i where i is one of these n nodes will where i is one of these n nodes will represent the you know left children for represent the you know left children for that node and then the right children that node and then the right children for that node for that node so we're gonna say four node in range of so we're gonna say four node in range of n n so we need to build our graph uh sorry so we need to build our graph uh sorry our tree we're gonna say that left is our tree we're gonna say that left is going to equal to whatever left child going to equal to whatever left child of node is of node is and then we're gonna say the right child and then we're gonna say the right child is going to be whatever right child of is going to be whatever right child of node is node is now remember that a node can have you now remember that a node can have you know an empty left or right child so we know an empty left or right child so we need to account for that so we're going need to account for that so we're going to say if left does not equal to minus to say if left does not equal to minus one and remember minus one is if the one and remember minus one is if the node node uh has no left child uh has no left child we're going to say okay if there's a we're going to say okay if there's a relationship then we need to say that relationship then we need to say that parent parent so the parent of our node is sorry the so the parent of our node is sorry the parent is the node and the child is parent is the node and the child is obviously this left so we're going to obviously this left so we're going to add to our parent to child relationship add to our parent to child relationship we're going to say the node is the we're going to say the node is the parent and we're going to append to it parent and we're going to append to it that we have that we have you know a left child you know a left child now what we need to do is we need to now what we need to do is we need to actually double check that the parent actually double check that the parent is not already is not already part of the part of the child to parent dictionary for you know child to parent dictionary for you know this node left here because if we have this node left here because if we have that then we have a cycle so that then we have a cycle so we're going to say we're going to say oops uh let me not mess up my oops uh let me not mess up my indentation here we're going to say indentation here we're going to say if left not in child to parent if left not in child to parent we're going to say child we're going to say child to to parent parent of left of left equals node and what this is doing is equals node and what this is doing is making sure i think i said cycle earlier making sure i think i said cycle earlier sorry disregard that essentially what sorry disregard that essentially what we're doing is we're checking if this we're doing is we're checking if this node is not already in the child to node is not already in the child to parent dictionary if it's already in parent dictionary if it's already in there that means that this node left there that means that this node left has another parent and we're in this has another parent and we're in this case here where a node has multiple case here where a node has multiple parents which obviously isn't valid so parents which obviously isn't valid so if the node is already in the child to if the node is already in the child to parent dictionary that means that it parent dictionary that means that it already has another parent and therefore already has another parent and therefore we have two parents that's not allowed we have two parents that's not allowed so if it's not in there that's fine we so if it's not in there that's fine we can add it to the dictionary but if it can add it to the dictionary but if it is in there then we simply need to is in there then we simply need to return false because we have the case return false because we have the case where we have a multiple parent where we have a multiple parent situation and that's not allowed situation and that's not allowed so we're going to do the same thing for so we're going to do the same thing for the right node we're going to say if the right node we're going to say if right does not equal to -1 so basically right does not equal to -1 so basically if the right child exists then we need if the right child exists then we need to reflect that in the parent to child to reflect that in the parent to child dictionary dictionary so parent children so parent children of node we're going to append that right of node we're going to append that right child and again we need to make sure child and again we need to make sure that this node right doesn't have that this node right doesn't have multiple parents we're going to make multiple parents we're going to make sure that this node here is its only sure that this node here is its only parent so we're going to say if right parent so we're going to say if right not in not in child to parent child to parent we're going to say child to parent we're going to say child to parent of right is going to equal to the node of right is going to equal to the node otherwise we have the case where again otherwise we have the case where again we have multiple parents that's not we have multiple parents that's not allowed we're going to return false so allowed we're going to return false so at this point we have built our tree at this point we have built our tree and we have taken care of the case of and we have taken care of the case of multiple parents multiple parents here we can be sure that here we can be sure that at least the case of multiple parents is at least the case of multiple parents is taken care of so we don't have to worry taken care of so we don't have to worry about that going forward now what we about that going forward now what we need to do is make sure that there's no need to do is make sure that there's no nodes kind of just floating in space nodes kind of just floating in space unconnected to anything else for example unconnected to anything else for example like we say we had this like we say we had this tree here which is valid but what if tree here which is valid but what if there was a node like four just floating there was a node like four just floating out in the distance here then this would out in the distance here then this would not be a valid tree because all of the not be a valid tree because all of the nodes are not connected and now we have nodes are not connected and now we have like two roots the four could be a root like two roots the four could be a root and the zero could be our root so and the zero could be our root so therefore we need to check that only one therefore we need to check that only one node in our graph node in our graph actually has no parent actually has no parent so what we're going to do is we need to so what we're going to do is we need to figure out what our root candidate is figure out what our root candidate is because that's where we're going to because that's where we're going to start our start our search through the final you know graph search through the final you know graph to make sure that we can actually visit to make sure that we can actually visit all the nodes so we're going to say all the nodes so we're going to say root candidate root candidate is going to be none is going to be none and we're going to be double checking and we're going to be double checking that we can actually that we can actually visit uh sorry that there's only one visit uh sorry that there's only one node that doesn't have a parent because node that doesn't have a parent because we can't have multiple routes right we can't have multiple routes right so we're going to say four node so we're going to say four node in in range of n range of n we're going to say if node not we're going to say if node not oops not in child oops not in child child to parent child to parent basically basically if the node is not in child dependent if the node is not in child dependent which means that this node doesn't have which means that this node doesn't have a parent remember that the root node is a parent remember that the root node is the only node that's allowed to not have the only node that's allowed to not have a parent so if the current node that a parent so if the current node that we're working with is not in the child we're working with is not in the child to parent mapping that means it's a to parent mapping that means it's a potential candidate for root candidate potential candidate for root candidate but not so fast we need to make sure but not so fast we need to make sure that root candidate is actually none that root candidate is actually none because if there's another node that because if there's another node that could be the root then therefore we have could be the root then therefore we have found two nodes with no parents and found two nodes with no parents and therefore we have two nodes that could therefore we have two nodes that could be the root and that's not a valid tree be the root and that's not a valid tree so we're going to say if not so we're going to say if not root candidate that means that we root candidate that means that we haven't already found a root candidate haven't already found a root candidate so we can say root so we can say root candidate is going to be equal to our candidate is going to be equal to our node otherwise if we've already found a node otherwise if we've already found a root candidate and now we found another root candidate and now we found another node that doesn't have parents node that doesn't have parents we have to return false because that we have to return false because that means that there's two potential root means that there's two potential root candidates and that's not allowed so candidates and that's not allowed so we're going to return false here we're going to return false here so at this stage so at this stage we have essentially found a root we have essentially found a root candidate but turns out we haven't candidate but turns out we haven't actually found a root candidate because actually found a root candidate because it's possible it's possible that that there is no root candidate so we there is no root candidate so we actually need to check actually need to check if if root root can can candidate is none candidate is none basically if we weren't able to find a basically if we weren't able to find a root candidate for some reason then we root candidate for some reason then we need to return false need to return false so so that will take care of finding the that will take care of finding the actual root now what we need to do is actual root now what we need to do is make sure that starting from the root we make sure that starting from the root we can actually visit all the nodes and we can actually visit all the nodes and we don't get caught in some sort of don't get caught in some sort of infinite cycle here infinite cycle here so we want to use a visited set to so we want to use a visited set to basically keep track of the progress basically keep track of the progress through our tree through our tree because remember we're using graphs on because remember we're using graphs on our graph here sorry we're using uh our graph here sorry we're using uh dictionaries so we could potentially get dictionaries so we could potentially get caught in an infinite cycle if we were caught in an infinite cycle if we were using you know just a standard graph using you know just a standard graph so i keep saying graph if we're using a so i keep saying graph if we're using a tree data structure then we'd only have tree data structure then we'd only have the left and right pointers we couldn't the left and right pointers we couldn't go up the tree on accident but since go up the tree on accident but since we're using this dictionary based uh way we're using this dictionary based uh way to represent the tree then to represent the tree then we could accidentally get caught in some we could accidentally get caught in some sort of cycle so we need the visited set sort of cycle so we need the visited set to actually tell us where we've been to actually tell us where we've been otherwise we can just use a standard otherwise we can just use a standard breadth first search traversal breadth first search traversal to actually build this graph tree sorry to actually build this graph tree sorry i keep saying graph i keep saying graph uh we're gonna say q uh we're gonna say q is going to be just a standard uh is going to be just a standard uh q here so we're going to put in the root q here so we're going to put in the root candidate because that's typically how candidate because that's typically how you do a breath first search through a you do a breath first search through a tree you start at the root and then you tree you start at the root and then you just visit all the nodes just visit all the nodes so we're going to say while q so so we're going to say while q so basically while we have something in basically while we have something in process we're going to say that the process we're going to say that the current node is going to be equal to q current node is going to be equal to q dot pop left dot pop left and we're going to say visited dot add and we're going to say visited dot add whatever the current node is whatever the current node is now what we want to do is we want to now what we want to do is we want to visit all of the children from this visit all of the children from this current node so we're going to say for current node so we're going to say for child child in in parent parent to children so the parent node is our to children so the parent node is our current node current node and and we want to visit the two children we're we want to visit the two children we're going to say if child going to say if child uh uh let's see let's see child to parent of node child to parent of node um um does not equal to the current node so does not equal to the current node so basically what we want to do here is to basically what we want to do here is to check whether or not the node that we're check whether or not the node that we're actually going to uh its parent is actually going to uh its parent is actually the current node actually the current node um although i think this might actually um although i think this might actually be be extraneous because we've already checked extraneous because we've already checked for the double parents but i'm just for the double parents but i'm just going to leave this in and i'll double going to leave this in and i'll double check at the end if we actually need check at the end if we actually need this but essentially we just want to this but essentially we just want to make sure that that that our child node make sure that that that our child node here um oh sorry this should not be no here um oh sorry this should not be no this should be child so we want to make this should be child so we want to make sure the child that we're working with sure the child that we're working with its parent is actually the its parent is actually the um um the current node that we're at so we the current node that we're at so we want to make sure that there's that want to make sure that there's that relationship actually exists relationship actually exists uh and if it doesn't if this uh and if it doesn't if this child's parent is pointing to something child's parent is pointing to something else for somewhat weird reason then our else for somewhat weird reason then our graph is the graph our tree is not valid graph is the graph our tree is not valid and we need to return false here like i and we need to return false here like i said this question has so many edge said this question has so many edge cases and so many ways where you can get cases and so many ways where you can get caught in a trap that it's really caught in a trap that it's really annoying and you're gonna have to be annoying and you're gonna have to be very very careful when implementing this very very careful when implementing this if this you know statement if this you know statement uh doesn't fire then we can continue uh doesn't fire then we can continue through processing so we're going to say through processing so we're going to say cue cue the append child the append child and that will basically go through the and that will basically go through the entirety of our tree here and we'll be entirety of our tree here and we'll be able to validate it that way and the able to validate it that way and the last thing that we need to do is we just last thing that we need to do is we just need to return whether or not the length need to return whether or not the length of visited equals to n so basically when of visited equals to n so basically when we did our full traversal through our we did our full traversal through our tree d were we able to visit all of the tree d were we able to visit all of the nodes and nodes and if we weren't able to visit them all if we weren't able to visit them all then something went wrong somewhere and then something went wrong somewhere and this is not a valid tree so let me just this is not a valid tree so let me just run this make sure that i haven't made a run this make sure that i haven't made a syntax error which i seem to have syntax error which i seem to have uh line 13 if uh line 13 if left oh left oh not in not in okay there we go okay there we go and okay cool let's submit this and it and okay cool let's submit this and it works cool uh let me just double check works cool uh let me just double check that we actually need this line here that we actually need this line here because i think we already checked for because i think we already checked for that that uh let me just double check this kind of uh let me just double check this kind of debug it as we go and okay cool so we debug it as we go and okay cool so we don't actually need to check whether or don't actually need to check whether or not the not the the child's parent matches the current the child's parent matches the current node because i think we already do that node because i think we already do that up here making sure that the actual up here making sure that the actual relationship is fine so relationship is fine so um yeah that you can get rid of that um yeah that you can get rid of that line actually or you can leave it in it line actually or you can leave it in it doesn't really matter doesn't really matter um okay cool so um okay cool so what is the time and space complexity what is the time and space complexity for this god-awful problem so for this god-awful problem so to build the graph is obviously going to to build the graph is obviously going to take you know big o of n time where n is take you know big o of n time where n is the number of nodes in the graph the number of nodes in the graph so that is going to be so that is going to be the you know part there the you know part there to find the root candidate we're going to find the root candidate we're going to have to go through a range of n and to have to go through a range of n and again this is going to cost big o of n again this is going to cost big o of n time time and then to perform your and then to perform your bfs through the tree is also going to be bfs through the tree is also going to be big o of n where obviously n is the big o of n where obviously n is the number of nodes in the tree so your number of nodes in the tree so your total run time complexity is going to be total run time complexity is going to be big o of 3 n but we know that big o of 3 n but we know that asymptotically this is the same as big o asymptotically this is the same as big o of n so we just write big o of n of n so we just write big o of n space complexity wise we have these two space complexity wise we have these two dictionaries which basically map the dictionaries which basically map the uh relationship between all of the uh relationship between all of the um um nodes here nodes here and i believe in the worst case and i believe in the worst case what could end up happening and i'm not what could end up happening and i'm not sure on this one is that every node is sure on this one is that every node is connected to every other node in the connected to every other node in the worst case worst case which means that our space complexity which means that our space complexity could be could be in the worst case big o of n squared in the worst case big o of n squared because every node uh would be connected because every node uh would be connected to every single node so it'd be like a to every single node so it'd be like a weird graph structure where like every weird graph structure where like every node is connected to every other node node is connected to every other node and in that case it would be big o of n and in that case it would be big o of n you know n you know n components times n minus 1 connections components times n minus 1 connections we get we get big o of n big o of n uh let's see big o of uh let's see big o of n squared uh space complexity for this n squared uh space complexity for this one because of how complex the graph one because of how complex the graph could potentially be um in that worst could potentially be um in that worst case case so i believe that is your space so i believe that is your space complexity i'm not a higher 100 sure um complexity i'm not a higher 100 sure um i think that would be the worst case i think that would be the worst case where your graph is like connected like where your graph is like connected like that uh if that's not possible then it that uh if that's not possible then it should just be a standard big o of n should just be a standard big o of n um but i think to stay on the safe side um but i think to stay on the safe side i want to say it's big o of n squared i want to say it's big o of n squared where basically each node is connected where basically each node is connected to every other node in the graph to every other node in the graph therefore you get that you know therefore you get that you know big o of n squared space complexity in big o of n squared space complexity in the actual graph the actual graph structure here that you have to store so structure here that you have to store so that's going to be how you solve this that's going to be how you solve this problem problem just to recap because there's a hell of just to recap because there's a hell of a lot you need to do here the first a lot you need to do here the first thing you need to do is build this graph thing you need to do is build this graph graph i keep saying graph i'm sorry it's graph i keep saying graph i'm sorry it's a tree we build the tree here a tree we build the tree here and we want to make sure that each and we want to make sure that each child only has one parent we need to child only has one parent we need to make sure of that make sure of that we need to make sure that there's no we need to make sure that there's no cycles in our graph and we also need to cycles in our graph and we also need to make sure that there's make sure that there's not multiple roots in our graph not multiple roots in our graph so this part makes sure that we don't so this part makes sure that we don't have the have the multiple parents and it also builds the multiple parents and it also builds the tree tree this part makes sure that there's no this part makes sure that there's no multiple roots multiple roots and then this part makes sure that we and then this part makes sure that we can actually visit all of the nodes and can actually visit all of the nodes and don't get caught in some sort of don't get caught in some sort of infinite cycle infinite cycle because if we got caught in a cycle then because if we got caught in a cycle then our because we have the visited set we our because we have the visited set we would break out of the iteration early would break out of the iteration early and we wouldn't actually visit all of and we wouldn't actually visit all of the nodes so the nodes so that is your three things that you need that is your three things that you need to check here to check here be very careful with this problem like i be very careful with this problem like i said there's a lot of edge cases there's said there's a lot of edge cases there's a lot of places you could go wrong a lot of places you could go wrong when solving this problem i would really when solving this problem i would really make sure you understand what each line make sure you understand what each line does and why we need it because does and why we need it because it's very easy to forget this especially it's very easy to forget this especially if you see it in an interview if you see it in an interview uh let's see who asked this question um uh let's see who asked this question um okay it looks like facebook twice but okay it looks like facebook twice but this okay so this question i don't think this okay so this question i don't think it really gets asked too much if you get it really gets asked too much if you get this in an interview this in an interview you know just hopefully you remembered you know just hopefully you remembered build the tree validate it and you want build the tree validate it and you want to look for cycles multiple roots and to look for cycles multiple roots and multiple parents but it seems like it multiple parents but it seems like it barely even got asked and this is like barely even got asked and this is like six months to a year ago and people only six months to a year ago and people only reported facebook twice so reported facebook twice so most likely this question is not being most likely this question is not being asked because of how infrequent it is i asked because of how infrequent it is i would trust this leak code would trust this leak code um um frequency frequency numbers pretty well numbers pretty well um but otherwise yeah just be very um but otherwise yeah just be very careful with this one there's a lot of careful with this one there's a lot of edge cases make sure that you catch them edge cases make sure that you catch them all otherwise you're going to be in for all otherwise you're going to be in for a rough time if your interviewer expects a rough time if your interviewer expects the perfect solution which this question the perfect solution which this question as you can see took me a while to figure as you can see took me a while to figure out so out so that is how you solve validate binary that is how you solve validate binary tree nodes quite an annoying question tree nodes quite an annoying question but really not the end of the world it's but really not the end of the world it's a medium an annoying medium but it's not a medium an annoying medium but it's not that hard that hard if you enjoyed the video please leave a if you enjoyed the video please leave a like and a comment it really helps with like and a comment it really helps with the youtube algorithm if you want to see the youtube algorithm if you want to see more videos like this please subscribe more videos like this please subscribe to my channel i make a ton of leak code to my channel i make a ton of leak code videos and other videos about working in videos and other videos about working in fang so if that interests you please fang so if that interests you please subscribe otherwise thank you so much subscribe otherwise thank you so much for watching have a great day bye
2024-03-21 00:38:21
1,361
https://i.ytimg.com/vi/Z…axresdefault.jpg
VALIDATE BINARY TREE NODES | LEETCODE # 1361 | PYTHON SOLUTION
VK2QbyhC6Lg
try again 47 traveling where he wanted to given an m-by-n matrix are positive to given an m-by-n matrix are positive and girls representing the height of and girls representing the height of each units now in a 2d elevation map each units now in a 2d elevation map compute the volume of water it is able compute the volume of water it is able to trap after waning bottom M and n are to trap after waning bottom M and n are less than 110 the height of each unit less than 110 the height of each unit cell is greater than 2 and less than cell is greater than 2 and less than 20,000 I'm gonna consider this map oh 20,000 I'm gonna consider this map oh yeah so it's like a dirty 3d version or yeah so it's like a dirty 3d version or 2d version of a height map I feel like 2d version of a height map I feel like I've done this before though not this I've done this before though not this one but like I've actually done this in one but like I've actually done this in real life real life because back in the day we're playing because back in the day we're playing with maps hmm Wow M where m is less than with maps hmm Wow M where m is less than an intern ok and each element is less an intern ok and each element is less than 20,000 which you could almost than 20,000 which you could almost discrete nice well but a lot of people discrete nice well but a lot of people like solving this one 861 I should have like solving this one 861 I should have used to bathroom first there but well I used to bathroom first there but well I mean if this is the hardest problem then mean if this is the hardest problem then maybe it is a bad idea maybe it is a bad idea I could we use top yeah so yeah yeah I I could we use top yeah so yeah yeah I haven't been here in the beginning to haven't been here in the beginning to chat look there's an emoji now you know chat look there's an emoji now you know how that I don't know how that works how that I don't know how that works actually bit I don't know how I still actually bit I don't know how I still don't know how to work that I don't don't know how to work that I don't really look into it but I mean really look into it but I mean conceptually this is what I usually conceptually this is what I usually understand I don't think everyone agrees understand I don't think everyone agrees with that but the question is like with that but the question is like what's a queen way of doing it right what's a queen way of doing it right like this could be some weird like like this could be some weird like breadth-first search east of maybe even breadth-first search east of maybe even in pine mm-hmm can you do binary search how does it help better yeah that's like that yeah exactly that's why I'm thinking of in terms of find out that I mean by binary search like can I like you know in step down incrementally yeah but I mean I think like this is also one of those problem where like in the theory is not that hard right but like it's gonna be so many edge cases and like you have to calculate the boundary first and then you have to calculate what's inside and then you have to make sure that all your searches are kind of on the same level it's actually reminds me a little bit of but not and it could not in the easy way like one of those the game go the board game go where you have to like surround them and then get to we move stopped at inside but not really or something like that but uh it's not yeah it's just very hardware matically right like like we could I think like the algorithm point everyone has a general idea like and it's just all about the edge cases I dunno I'm gonna use the bathroom then who if I'm gonna stop this I don't think wait really dad to d1 I guess I should practice that then alright because you never know it means I'm impossible it's just very I think for each I'm just trying to also I think for each I'm just trying to also think a slick way well you know easy to think a slick way well you know easy to implement way to kind of figure this out implement way to kind of figure this out and okay so we could and you talk to me and okay so we could and you talk to me is great and so so we could treat the is great and so so we could treat the boundary as so I think that's what I'm boundary as so I think that's what I'm gonna end up doing no and then just we gonna end up doing no and then just we each one just here what is my how do you each one just here what is my how do you declare a boundary I'm sorry hundred ten declare a boundary I'm sorry hundred ten can I might artists like well what does it mean to be contained when you do it when you're made of a deaf where search it means or the know or Wi-Fi search or just search it means that so you do it especially I knew you like how does it take a count of one as like how does it take a count of one as it just leaks way yeah I mean I'm just it just leaks way yeah I mean I'm just also just trying to think about like also just trying to think about like what does it mean to be contained like how does it know that that's meant to start and just go I guess if it doesn't reach the boundary yeah okay um I think I would just do that and do one on each cell it's a two star 10,000 and linear so that's 10,000 squares I'm a de linear so that's 10,000 squares I'm a de Tolosa Tolosa we have to do so we have to do this like we have to do so we have to do this like yeah I mean it's still only a grammarian okay let's let's figure that out that hmm I'm Richard I guess I'll start by doing something really naive and then figure out how to optimize as I go and I guess as long as it doesn't reach the boundary is it somebody matters I'm consistent yeah I'm pretty screwed 10,000 yeah you're right quiet I need to be quite for a search I was ringing initially deaf research but but 10,000 a oh I wasn't thinking about backside but oh I wasn't thinking about backside but I think you could I mean in your in your I think you could I mean in your in your case you could play do a binary search case you could play do a binary search on the Mac side BAM well maybe try to do on the Mac side BAM well maybe try to do something a little bit clever I think something a little bit clever I think that's the I think one thing is that in that's the I think one thing is that in the example the in example the the lakes the example the in example the the lakes if you will other in the same height but if you will other in the same height but I think that's not actually generate the I think that's not actually generate the case right but you have one that's like case right but you have one that's like well even just this picture you can't well even just this picture you can't see me pointing at it I don't know why I see me pointing at it I don't know why I point at it but uh like on the right point at it but uh like on the right side reviewing it's just like one unit side reviewing it's just like one unit down then it still at the same answer down then it still at the same answer but it's not the same height Oh No looky here you oh yeah I don't I don't know if I could do this on a live interview and that's so I just keep going and this is hard actually I mean I guess and this is hard actually I mean I guess everyone knew that but so I'm at the one everyone knew that but so I'm at the one what is the boundary put a 1/2 DB but 2 what is the boundary put a 1/2 DB but 2 is still high yeah also I just realized that when someone was using the term for Phil that's that's literally maybe a pun yeah I think that's what I'm like trying to think what that means like like you definitely like put in a number and then like okay maybe I need to maybe that's what I need a binary search I can't do I think I'd a missing that n times m I think I'd a missing that n times m times x and x and was up I had some other ideas but right now I'm not sure it's right here you want you want just to co-opt it to me like how do you know that you can also like how do you know that you can also like throw the two and not worry about like throw the two and not worry about it you know that's like a minute huh it you know that's like a minute huh mini ho [Music] maybe I just do the math on the number of cells that underneath and then just assume that this would already be under it okay that's probably that idea not super sold on it to be honest it's one two one two four yeah then then you one two one two four yeah then then you would hit the boundary and then get that would hit the boundary and then get that for search or by first search in my case for search or by first search in my case would just have nothing and then the would just have nothing and then the answer would be probably nothing right just like so no this is not that's the height that you want times space that really max and Q it and so I don't keep track of what I've seen so this will actually just one yeah that's kind of what I'm doing but yeah that's kind of what I'm doing but in a weird different weird way yeah see in a weird different weird way yeah see this yes it's like 1 1 2 1 1 ok let's try to some now I can't find it we'll go over that now I can't find it we'll go over that so I'm just looking to chat and try to so I'm just looking to chat and try to find it okay three two let's see if this find it okay three two let's see if this is pointing it should be zero okay is pointing it should be zero okay that's right mm-hmm some other educators that's right mm-hmm some other educators this is like really tricky they're just this is like really tricky they're just doing one look like that's a twenty doing one look like that's a twenty thousand one that borders and then just thousand one that borders and then just betting in the middle and it see what betting in the middle and it see what happens so definitely my car is that way happens so definitely my car is that way I know just tell me at least one more I know just tell me at least one more case with us wrong and it just happens case with us wrong and it just happens to be way and I shampoo patina meeting to be way and I shampoo patina meeting all the same I should get something that's four times bigger than what it should be okay type a bug in my code I feel like the have the right idea I just don't have I just have to hash this is the same height then we've done this is the same height then we've done it before it before every good good we could work but every good good we could work but they're all different than if this would they're all different than if this would be right put that test as well then okay be right put that test as well then okay maybe not so actually but that could so maybe not so actually but that could so we started adding input so my code is we started adding input so my code is where I Daniel and the fourth one but where I Daniel and the fourth one but not the third one which is fine okay not the third one which is fine okay that is true because I just double count that is true because I just double count some stuff it was some stuff it was [Music] doesn't mean to tell me it is part of the same Sun that is the same height of okay okay and that's the only case where okay that's cool I'll keep that in mind am i confident enough to submit it yet I am i confident enough to submit it yet I mean I think in terms of code it's okay mean I think in terms of code it's okay we receive it once time limited that's we receive it once time limited that's the only concern I have and I'm too lazy the only concern I have and I'm too lazy constructed big text oh well okay I may constructed big text oh well okay I may be an empty away which is fair mm-hmm I be an empty away which is fair mm-hmm I might feel like I've been good about might feel like I've been good about testing that today but maybe not on this testing that today but maybe not on this one cuz how to do whatever about it I mean if this works then I'll explain my solution by the time limits exceed it oh man how close am I huh well 37 to 40 I think this is I think my coat is ready but I need to figure out a way to and hope that if this was an insight and and hope that if this was an insight and this is the Bossman's maybe by I mean - this is the Bossman's maybe by I mean - ends at where n is ten thousand square ends at where n is ten thousand square so yeah like cutting it close so yeah like cutting it close where I was hoping yeah and also made where I was hoping yeah and also made with C past past and maybe it is as fast with C past past and maybe it is as fast enough I don't know it doesn't even tell enough I don't know it doesn't even tell me how cuz usually just have one test me how cuz usually just have one test case it tells you enough hmm so yeah okay so I do have to do something smarter than locate every cell [Music] and this don't athletes my question is yeah so this is like slightly optimized version of of the one what can I do better on this one I mean it Allah made a layer of em so how do you like I'm a mom one how can I tell that three is the true border and apparently I guess I just need to be linear time I guess I just need to be linear time better for sure I would starting today okay well I think maybe the other way to think about it is maybe same thing is what I did on the last one which is instead of thinking about things sticking in them from inside out I could think about things I'm outside in and if I'm trying to your lemonade borders what and I like that one get me how do I walk and I like that one get me how do I walk down to one and maybe set it to the way down to one and maybe set it to the way you move out maybe I would do some scanline thing like we did with 1t trapping waterway okay okay can you do them now that I think about can you do them now that I think about it can you just do the one deed well it can you just do the one deed well thanks I still want to solve it can we thanks I still want to solve it can we decompose this with do I don't think decompose this with do I don't think about having one thing data about having one thing data yeah I can't you just weird topography yeah I can't you just weird topography stuff Chris even though you're in this stuff Chris even though you're in this section section things can be low and then tactics out things can be low and then tactics out okay now Nick you can really the other way to go is just the by mmm I'm just now I'm just trying to by mmm I'm just now I'm just trying to think about how to formulate it hmm but this is how you would do a proof for someone their window but yeah they say my description is that for each so I just do a breadth-first search up to that height and then basically you just take like a cross section of that number which just correct but it was definitely a smaller way so hint nope no hints look normally scissors in my submission look normally scissors in my submission history right so I mean I don't have to history right so I mean I don't have to worry about losing this code fit like worry about losing this code fit like we've got assessment times are crazy I'm just I'm trying to say hey wait a minute I'm telling foam lay down as well well you could buy my way of thinking about it maybe a little bit is that instead of like walking there inside stuff and finding out you know maybe I mark the outsides toughest like not good or something like that and then slowly we'll get to the middle where you just look at it in terms of the borders something like that I'm not saying it that well yeah I'm still trying to wrap my head around what that looks like to be honest so that's why I'm not and we start on the lowest first and like they say this is one start at 1 you know mind you talk it is adjacent you know mind you talk it is adjacent and it's three and four okay well today and it's three and four okay well today we'll we is bigger than just neighbor so we'll we is bigger than just neighbor so and you always get to do it first okay I and you always get to do it first okay I think I have a general idea then please think I have a general idea then please please ask me questions to explain if I please ask me questions to explain if I don't I don't know okay I mean let me don't I don't know okay I mean let me try to hack something up and then I will try to hack something up and then I will try to explain it and keep asking me try to explain it and keep asking me because I have an intuition about it but because I have an intuition about it but I had to really articulate it but okay I I had to really articulate it but okay I don't have to lead it everybody's the don't have to lead it everybody's the beginning parts having that forest fire jeribai I get the first one more glass don't count some corners meet Edison whenever possible now we just go further to test right we now we just go further to test right we got something you do clean up slightly got something you do clean up slightly sometimes but now your CV now because we sometimes but now your CV now because we prioritize by the lowest height if you prioritize by the lowest height if you see any on the border see any on the border you're gonna only see higher Heights you're gonna only see higher Heights especially the beginning but we have a especially the beginning but we have a boy is he safe or no support at some boy is he safe or no support at some expense but we see three okay I think I expense but we see three okay I think I have a better intuition about it too I have a better intuition about it too I had to think about how to replicate it had to think about how to replicate it like like it's one thing to know how to like like it's one thing to know how to figure it out and it is another to like figure it out and it is another to like well by serious form again in like two well by serious form again in like two months how can I figure it out other months how can I figure it out other than just remembering the answer which than just remembering the answer which is helpful but not necessary is helpful but not necessary Nessus sufficient yeah he's my one you it's gonna like that maybe even more by something I'm in the hole no there's the that's where I'll meet white glue me I because then you first time you see it because then you first time you see it time it's everything dad on the outside time it's everything dad on the outside already processed so I just don't the packets which now has an don't the packets which now has an expensive so a full same thing that's all that's missing this one right so one of the two yeah I mean that's what I do yeah I mean that's what I do I mean I vote in a funky way but but I mean I vote in a funky way but but yeah just this equation should only yeah just this equation should only happen if height is bigger than the happen if height is bigger than the height map or lower then I missing one height map or lower then I missing one relax relax someone should hearing some one of these someone should hearing some one of these edges shifted up one one I guess I hit edges shifted up one one I guess I hit up this one happens first so so then up this one happens first so so then this happens first and his hits up this this happens first and his hits up this one so it's seen that okay I think I see why it just a case but I didn't wanna get someone a border or maybe this relaxation is make sense so now it's getting party of one up in here but because just got a party of one so it should be party of three okay that makes way more sense okay how do I fixed Oh Oh [Music] uh yeah I mean I think you caught me about it's doing it yes exactly okay let me see if it works for I click test cases suppose I mean I would say I do like this from I don't 26 minutes ago okay so much faster I'm 26 minutes ago okay so much faster I'm gonna tie this one it's tiring with 26 I gonna tie this one it's tiring with 26 I mean that's to me 20 minutes to do it mean that's to me 20 minutes to do it again so it took me I don't need any I'm again so it took me I don't need any I'm saying yeah how would that explain it no saying yeah how would that explain it no worries and I'm gonna try to make sure I worries and I'm gonna try to make sure I understand it as well so I took actually understand it as well so I took actually a little bit less than an hour which is a little bit less than an hour which is I guess okay but part of if Venus okay I guess okay but part of if Venus okay so yeah so I think the other way I was so yeah so I think the other way I was thinking about it so my own solution was thinking about it so my own solution was one where like we're taking cross one where like we're taking cross section so at every possible and every section so at every possible and every possible point we we try to throw it to possible point we we try to throw it to that height and then some aboard it or that height and then some aboard it or the chorus section then chunks to get the chorus section then chunks to get the answers at that time they made it the answers at that time they made it because that was n times M Squared which because that was n times M Squared which I guess 100 is a little bit big and I I guess 100 is a little bit big and I was hoping that was squeezing maybe in was hoping that was squeezing maybe in see buzzes okay fine not her still well see buzzes okay fine not her still well it'll be pretty tight I mean even now it'll be pretty tight I mean even now I'm pretty tight so well I got away I I'm pretty tight so well I got away I was thinking about is like inside was thinking about is like inside instead of like pinging inside like a instead of like pinging inside like a lake over your cold oh my god this is my lake over your cold oh my god this is my Lake how do i flood fill so then like I Lake how do i flood fill so then like I I don't reach outside I did the opposite I don't reach outside I did the opposite thing we're okay if I'm on the outside thing we're okay if I'm on the outside how do I it's not of what feel per se how do I it's not of what feel per se don't do the words are interesting but don't do the words are interesting but it basically is like okay so we have it basically is like okay so we have stuff from the outside how do we get stuff from the outside how do we get things in right and and the big one things in right and and the big one there is kind of well one is that I used there is kind of well one is that I used to probably cue just so that to probably cue just so that as I think it makes because you can as I think it makes because you can think about it and like okay this is the think about it and like okay this is the level that I'm falling and you start level that I'm falling and you start from the lowest because otherwise it from the lowest because otherwise it gets a little weird gets a little weird maybe no that's the way I talk about it maybe no that's the way I talk about it and then once you get into an int and and then once you get into an int and then I put everything on a border on it then I put everything on a border on it queued in a priority queue so it's queued in a priority queue so it's sorted and then you just keep on going sorted and then you just keep on going through the bottoms until you've reached through the bottoms until you've reached an inner one and in the one is going to an inner one and in the one is going to be the first time because we already be the first time because we already because we already put everything on a because we already put everything on a border in and everything that's not in border in and everything that's not in the border will be a possible hole or the border will be a possible hole or lake a possible place where you could lake a possible place where you could trap the water so that means that if you trap the water so that means that if you so if you're already at at a height in so if you're already at at a height in which something interior is shorter than which something interior is shorter than it meaning meaning that you know you it meaning meaning that you know you haven't seen it yet but it's shorter haven't seen it yet but it's shorter than you know that means that this is than you know that means that this is dam instead uh for that space that's dam instead uh for that space that's inside everything surrounded is at least inside everything surrounded is at least that height right and everything else is that height right and everything else is higher because but almost like a I would higher because but almost like a I would say almost like an induction thing if if say almost like an induction thing if if like I it's very hard for me to kind of like I it's very hard for me to kind of visualize it so please bear with me and visualize it so please bear with me and keep asking questions I you know I have keep asking questions I you know I have patience it's just that no articulation patience it's just that no articulation there's a little trickier but given there's a little trickier but given inside square right the first square inside square right the first square that is going to be you know like I say that is going to be you know like I say relaxed in the sense that is like the relaxed in the sense that is like the BFS but like dice true a type relaxation BFS but like dice true a type relaxation like the first because we do this like like the first because we do this like sorted by height the first cell that is sorted by height the first cell that is going to be the next to two cell that's going to be the next to two cell that's interior that's also shorter it's going interior that's also shorter it's going to be the shortest of to be the shortest of the neighborhood surrounded like the neighborhood surrounded like surroundings that make sense surroundings that make sense think that good stuff but once that's think that good stuff but once that's the case yeah you count that is that the case yeah you count that is that height which is what I forgot to do for height which is what I forgot to do for a little bit but and then you kind of a little bit but and then you kind of also count down as pink one coat on the also count down as pink one coat on the border way creeping in and then you kind border way creeping in and then you kind of keep doing that and you're always so of keep doing that and you're always so if you have an interior cell that that if you have an interior cell that that is lower than you know a surrounding is lower than you know a surrounding height it will always be at least that height it will always be at least that high all right okay I know I'm not high all right okay I know I'm not explain let me see if I could find a way explain let me see if I could find a way to regionalize it okay I'm just like you to regionalize it okay I'm just like you want some ASCII map ASCII boy at least okay so let's say you have something like this right so the first few other versions like okay I'm just going to use it x2 kind of like okay we have to kill all these stuff so we done all the ones and once I clearly know next to stop that a taller way and then now I'm just covering pace a bit we could contrast it instead of me just well you know and then now we do the twos so that this too is okay I want a border that is right so all the tools are kind of just done now and like and everything surrounding is bigger so get that okay this is where it gets interesting is when we once we do - we it doesn't really matter which we get or win in which order even but so let's just go this one right let's say would so now you you're doing this and you're so now you you're doing this and you're like you look around and the next to it like you look around and the next to it is a two-way and in this case this - is a two-way and in this case this - it's obvious lesson three but it means it's obvious lesson three but it means that because that this is the first time that because that this is the first time that the two is being added to the queue that the two is being added to the queue damn instead on a border damn instead on a border - like everything surrounding it is at - like everything surrounding it is at least three wait the stab one kind of least three wait the stab one kind of make sense at that point because if if make sense at that point because if if like like I said it's almost kind of like like I said it's almost kind of like an induction type thing where if if like an induction type thing where if if there was a two in the border then this there was a two in the border then this rep reached already right like that's a rep reached already right like that's a if there's a that's it like in a if there's a that's it like in a parallel universe where this is - this parallel universe where this is - this is actually a - then this would have is actually a - then this would have happened earlier and then this we have happened earlier and then this we have gotten relaxed earlier right and because gotten relaxed earlier right and because that is in the case by you know because that is in the case by you know because we sort it and that's like the order we we sort it and that's like the order we processed them when we have just processed them when we have just demonstrate and with everything that demonstrate and with everything that like if there was a way to get to this like if there was a way to get to this cell that's dent we would have already cell that's dent we would have already happened but because it's the way then happened but because it's the way then that means that everything is now that that means that everything is now that means three is like the the border of means three is like the the border of your current cell so that makes sense your current cell so that makes sense and because of dad well you just kind of and because of dad well you just kind of kind of difference right and since it is kind of difference right and since it is 2 so you have 1 2 the count because this 2 so you have 1 2 the count because this should be hiked worried and then now you should be hiked worried and then now you could say you could think about that is could say you could think about that is like now you're flooding it from 2 to 3 like now you're flooding it from 2 to 3 so you could even effectively change so you could even effectively change this cell to cell today which is kind of this cell to cell today which is kind of what we do without changing the height what we do without changing the height back so I guess you know change to a back so I guess you know change to a height map but we add that to the we height map but we add that to the we push it to the key with that with with 3 push it to the key with that with with 3 instead and now this done and then now instead and now this done and then now this is your new kind of state for the this is your new kind of state for the map and then now yet you also prior to map and then now yet you also prior to curing in some way doesn't really matter curing in some way doesn't really matter what it could be this one it could be what it could be this one it could be this one it you know it's a party key this one it you know it's a party key right like Eddie's in this case it right like Eddie's in this case it doesn't matter maybe another pump doesn't matter maybe another pump because now this is on the border right because now this is on the border right now this is your new map and I say you now this is your new map and I say you do this one then you know that so you do do this one then you know that so you do this one so this one gets processed as this one so this one gets processed as part of like two surrounding things so part of like two surrounding things so then now test case then now test case done and now this is a toy and then done and now this is a toy and then let's say that she's just to tease real let's say that she's just to tease real quick and now you did this one and the quick and now you did this one and the same way you just plus two because now same way you just plus two because now you haven't you know you and a thing and you haven't you know you and a thing and it just plus two to it right and that's it just plus two to it right and that's it and then now you keep on processing it and then now you keep on processing and everything it's already in the and everything it's already in the priority queue I think so so yeah so priority queue I think so so yeah so that's kind of - it's not an explanation that's kind of - it's not an explanation where's a walk-by it's a step-by-step where's a walk-by it's a step-by-step and yeah I mean that's it's like let me and yeah I mean that's it's like let me know that's a okay another explanation know that's a okay another explanation for but uh yeah it's not I mean it's for but uh yeah it's not I mean it's definitely not an easy problem so I mean definitely not an easy problem so I mean I think but I think that like it's just I think but I think that like it's just a very hard part on an interior I don't a very hard part on an interior I don't know if I could do it to be honest know if I could do it to be honest fashion under pressure like now I'm not fashion under pressure like now I'm not really under pressure I mean I got one really under pressure I mean I got one solution that it's not optimal and maybe solution that it's not optimal and maybe in an interview that's what I would have in an interview that's what I would have gone with and that's good enough I mean gone with and that's good enough I mean I I don't know if it's good enough for I I don't know if it's good enough for path but it's good enough for me in that path but it's good enough for me in that like you know that's how I could solve like you know that's how I could solve it and I could explain that part too but it and I could explain that part too but uh yeah sometimes you just get unlucky uh yeah sometimes you just get unlucky and problems if you in an interview I and problems if you in an interview I don't know what to say to that in don't know what to say to that in general even but like sometimes you have general even but like sometimes you have bad day sometimes yep good days and bad day sometimes yep good days and sometimes you're in T really gives you sometimes you're in T really gives you an insane problem sometimes they give an insane problem sometimes they give you something that maybe not even insane you something that maybe not even insane just like yeah something that you're just like yeah something that you're more familiar with familiar where for more familiar with familiar where for whatever reason maybe you study the whatever reason maybe you study the night before and Karen oh lucky yeah I night before and Karen oh lucky yeah I mean sometimes that's part of the mean sometimes that's part of the process I know what to say about that process I know what to say about that before this point yeah so so what is the before this point yeah so so what is the complexity so just M times n times blog complexity so just M times n times blog times and I think because that's the times and I think because that's the size of the queue that's the space and size of the queue that's the space and time because you do every cell once you time because you do every cell once you know - some born new tracking but that's know - some born new tracking but that's constant number of times and yeah like I constant number of times and yeah like I said if you get this other thing I don't said if you get this other thing I don't know I would say this one yeah I mean I know I would say this one yeah I mean I I don't know sometimes it is I mean I I I don't know sometimes it is I mean I I mean I it is just a hard problem I mean mean I it is just a hard problem I mean there's no way around it there's no way around it I don't know how to justify this one but I don't know how to justify this one but yeah I mean it is kind of fun but it's I yeah I mean it is kind of fun but it's I mean I think the and and the coding is mean I think the and and the coding is not that bad once you understand it in not that bad once you understand it in theory but you know that's not it that's theory but you know that's not it that's not easy to understand and I don't know not easy to understand and I don't know if I could have I mean I think some the if I could have I mean I think some the way I came about it is kind of and this way I came about it is kind of and this also has a little bit luck on my side as also has a little bit luck on my side as well is kind of one thing that I've been well is kind of one thing that I've been coming oh this thing for myself and you coming oh this thing for myself and you know some of it you have to figure out a know some of it you have to figure out a way to be south refraction so refracting way to be south refraction so refracting about it have a way to self-reflect it about it have a way to self-reflect it is kind of like one thing I noticed when is kind of like one thing I noticed when I when I study and when I kind of like I when I study and when I kind of like like when I don't get a problem right like when I don't get a problem right what am I getting a wrong one and this what am I getting a wrong one and this happens for sim in a couple of ways happens for sim in a couple of ways similar things like a dynamic similar things like a dynamic programming even this happens a lot more programming even this happens a lot more for me where some problems are not for me where some problems are not symmetric meaning a lot of problems in symmetric meaning a lot of problems in dynamo well maybe not a lot of theories dynamo well maybe not a lot of theories in these kind of coding things a lot of in these kind of coding things a lot of problems are symmetric and dynamic problems are symmetric and dynamic programming meaning you could go forward programming meaning you could go forward or backwards but some problems you can or backwards but some problems you can only go in one direction and I'm and only go in one direction and I'm and very often I forget to go to our that very often I forget to go to our that well I forget to even think about in the well I forget to even think about in the other direction other direction and that's something that I'm trying to and that's something that I'm trying to think like it's still a way to kind of think like it's still a way to kind of do the opposite of what you want to do do the opposite of what you want to do in a way that makes in a way that makes that gives you properties that makes that gives you properties that makes sense sense I don't know if that's I don't think I don't know if that's I don't think that's like a really actionable thing that's like a really actionable thing for anyone other than the future Larry for anyone other than the future Larry who kind of look at this farm again who kind of look at this farm again because I hope I forget it soon but yeah because I hope I forget it soon but yeah I think like sometimes like an analogy I think like sometimes like an analogy would be like you look at a straight would be like you look at a straight form and you're going from the beginning form and you're going from the beginning to the end but maybe sometimes it's to the end but maybe sometimes it's easier to think about it from the end to easier to think about it from the end to the beginning right especially when you the beginning right especially when you do like growing window in some case it do like growing window in some case it was not going when they're sliding was not going when they're sliding windows or a two-finger algorithm or windows or a two-finger algorithm or whatever you want to call it sometimes whatever you want to call it sometimes it's easier to think about it going from it's easier to think about it going from left to right sometimes it's got easier left to right sometimes it's got easier to think about it from right to left so to think about it from right to left so it's not quite I mean this is not quite it's not quite I mean this is not quite analogy but that's what I was trying to analogy but that's what I was trying to think about how to do with kind of like think about how to do with kind of like okay you know doing this stuff for okay you know doing this stuff for search for each one and try to figure search for each one and try to figure out what's on the border like I just out what's on the border like I just couldn't think of it I just couldn't get couldn't think of it I just couldn't get it right like I mean really we were here it right like I mean really we were here for like maybe not dialogue that long for like maybe not dialogue that long but like a good amount of time watching but like a good amount of time watching me trying to figure out how to get me trying to figure out how to get around that thing about like okay if I'm around that thing about like okay if I'm in a lake how do I find out the boundary in a lake how do I find out the boundary right instead I was like okay let's right instead I was like okay let's let's spin myself in the head around my let's spin myself in the head around my head it's been the palm on his head and head it's been the palm on his head and that be the palm yeah I spin the problem that be the palm yeah I spin the problem on his head and be like okay what does on his head and be like okay what does it mean if we play first search or it mean if we play first search or something like that from the outside something like that from the outside right and that's kind of how I got to right and that's kind of how I got to this thing eventually I mean you kind of this thing eventually I mean you kind of watched the tapes it took me a couple of watched the tapes it took me a couple of minutes so it's not like I was like ah minutes so it's not like I was like ah yeah that's now it's obvious and I was yeah that's now it's obvious and I was like well like how do you do it like well like how do you do it therefore search for breadth-first therefore search for breadth-first search from the outside way and that's search from the outside way and that's how I got a take a look at this just how I got a take a look at this just Kirstin image and I was like well I Kirstin image and I was like well I guess you're you know like at the tree I guess you're you know like at the tree I know that I want to go inside but how do know that I want to go inside but how do I want to make like how do I know that I want to make like how do I know that tree is the right level and then I think tree is the right level and then I think from dad I was like okay well if we put from dad I was like okay well if we put something where we go something where we go on the border and like going from the on the border and like going from the lowest up kind of almost like filling it lowest up kind of almost like filling it up one by one up one by one maybe then you know maybe that's how the maybe then you know maybe that's how the way I do it I mean I was playing around way I do it I mean I was playing around with so I was in like great Catherine with so I was in like great Catherine about it I think another way of thinking about it I think another way of thinking about it is yeah like for each cell on about it is yeah like for each cell on the border you're throwing it up to the the border you're throwing it up to the nearest neighbor incremental E or like nearest neighbor incremental E or like kind of I mean in it it's not quite how kind of I mean in it it's not quite how I express this but like but you can I express this but like but you can think about like oh you're Emily or the think about like oh you're Emily or the once at the same time because like once at the same time because like that's a the water and they're like that's a the water and they're like that's a the ocean level sea level yeah that's a the ocean level sea level yeah the sea level is going to one and what the sea level is going to one and what does it look like the sea level goes up does it look like the sea level goes up to two what does it look like and then to two what does it look like and then so forth progressively and eventually so forth progressively and eventually you go find a hose and I just and then you go find a hose and I just and then it's that idea and then expressing it in it's that idea and then expressing it in code in a way that allows you to code it code in a way that allows you to code it in a queen wave versus like you know in a queen wave versus like you know some kind of fold up that goes for the some kind of fold up that goes for the entire finger the entire time and then entire finger the entire time and then keep track of what's on the outside and keep track of what's on the outside and water inside or something like that yeah water inside or something like that yeah anyway I think that's my finger about anyway I think that's my finger about this problem hopefully if you are this problem hopefully if you are interviewing you don't get this one I interviewing you don't get this one I think that's a little bit too high for think that's a little bit too high for me though it's way I think it's kind of me though it's way I think it's kind of fun but you know on an interview may be fun but you know on an interview may be fun is not what you optimize for
2024-03-22 10:41:38
407
https://i.ytimg.com/vi_w…xresdefault.webp
407. Trapping Rain Water II (Leetcode Hard)
ahbYwy_2XSI
So today we will do the problem of minimum number of burst balloons. It is a medium level problem. Once you read it, people will understand. So we have this is the diagram, so this diagram of points is this is the diagram, so this diagram of points is correct, so it is 10:16, you and the correct, so it is 10:16, you and the rate. whose height we do not know, okay, whose height we do not know, okay, our start point and our start point and okay, we will leave some arrows from the This diagram is important. If you had made this diagram then you would have faced a lot of problems as to what to do. Right now this problem is is right is right then this is the answer return. You have to do it now then this is the answer return. You have to do it now if if if what we are doing here to find out the minimum number of is that we are trying to see how much is being intersected. Right, here if you are tu and six which is common, here If you If you If you look at it, this and this is the common part look at it, this and this is the common part or we will take any two if they intersect interval is three. Basically, what is the problem that Basically, what is the problem that we have to see the intersection of two points or two, we have to see the intersection of two points or two, its interval. Common its interval. Common internal is okay. our answer will be as many rights as there are common internals. So our answer will be as many rights as there are common internals. So now if you see, this is now if you see, this is our input, so it is not an input but our input, so it is not an input but here it is sorted, right, so first think here it is sorted, right, so first think you notice that whatever inputs have to be sorted, you notice that whatever inputs have to be sorted, right. we will unite it. Right, from one and we will unite it. Right, from one and six, we have 2 and 8. Right, so here we will do this Right, so here we will do this one and this one from both, in the coordinate, one and this one from both, in the coordinate, if this is D, the common region from here is one. if this is D, the common region from here is one. if this is D, the common region from here is one. give pulse then both will go, okay, so this is it, so what we have to do is that in all the points given, we have to make a new ray to see the interval and whatever number of We have to We have to We have to return right because now we have return right because now we have got two lengths right one and tu tu six and got two lengths right one and tu tu six and 10 * 12 so if we return this length then 10 * 12 so if we return this length then date it is R Answer Okay so what will we do now, now we will Okay so what will we do now, now we will see the remaining points that weather. see the remaining points that weather. see the remaining points that weather. what will be the remaining seconds? We have to check in the sorting list whether there is travel between dem in it, so okay, we will do it from one because we have already kept one okay, we will do it from one because we have already kept one pulse, so we will pulse, so we will check from one now. start ka maximum and ka minimum ok understand previous and previous and meaning ok understand previous and previous and meaning which which previous previous and what will be our start right we also had to check that we also had to check that we have basic what we have to do is minimum we have basic what we have to do is minimum Take the right of both, hello mini, if this Take the right of both, hello mini, if this value comes out back to the second number of the previous element, back to the second number of the previous element, minimum and previous and commerce, minimum and previous and commerce, what will be the meaning of minimum is six and out of one and tu, minimum is six and out of one and tu, maximum is tu. maximum is tu. maximum is tu. [Music] What does it mean that you and six are here? is a common part then right, what if it was 7 and 8? So now we should have two values ​​in the output. So now we should have two values ​​in the output. If we have equalized the code then we will submit this solution That's it, you can optimize something else too, you can do it but this is one of the
2024-03-22 14:29:10
452
https://i.ytimg.com/vi_w…xresdefault.webp
452. Minimum Number of Arrows to Burst Balloon | Python | Leetcode Medium