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
|
---|---|---|---|---|---|
qgK4ZyJX0-U | [Music] hey guys hope you are doing fine welcome hey guys hope you are doing fine welcome back to another video back to another video in this video we will be looking at in this video we will be looking at solution ah another lead coat problem solution ah another lead coat problem which is reversed integer the problem which is reversed integer the problem definition is given a 32-bit signed definition is given a 32-bit signed integer reverse digits of an integer and integer reverse digits of an integer and few examples are given such that the few examples are given such that the reverse of 123 is 321 River so minus 123 reverse of 123 is 321 River so minus 123 is minus 321 whereas if the number is is minus 321 whereas if the number is such that it contains preceding zeros such that it contains preceding zeros like 120 then the reverse is only 21 like 120 then the reverse is only 21 before starting with the solution we before starting with the solution we must be familiar with two important must be familiar with two important operators namely division and modulus operators namely division and modulus when we applied the division operator when we applied the division operator between two numbers a and B we get between two numbers a and B we get questioned whereas when we apply modulus questioned whereas when we apply modulus operator between two numbers a and B we operator between two numbers a and B we get the remainder for example when 10 is get the remainder for example when 10 is divided by 3 we get 3 as the question divided by 3 we get 3 as the question whereas when 10 is modular divided by 3 whereas when 10 is modular divided by 3 we get 1 as a remainder now we can start we get 1 as a remainder now we can start with the solution consider the input X with the solution consider the input X is 17 29 and output la is 0 the output is 17 29 and output la is 0 the output is initially initialized to 0 so the is initially initialized to 0 so the algorithm is as follows well X is algorithm is as follows well X is greater than 0 multiplying them with 10 greater than 0 multiplying them with 10 then add X mod 10 to num and finally then add X mod 10 to num and finally divide X by 10 so this cycles goes on divide X by 10 so this cycles goes on while X is greater than 0 initially while X is greater than 0 initially value of x is 17 29 since X is greater value of x is 17 29 since X is greater than 0 multiply number with ten then add than 0 multiply number with ten then add X mod 10 to num which gives 9 and X mod 10 to num which gives 9 and finally divide X by 10 which gives once finally divide X by 10 which gives once 172 so the new values of num is 10 and 172 so the new values of num is 10 and the new value of x is 172 so now X is the new value of x is 172 so now X is 172 and num is 9 since X is still 172 and num is 9 since X is still greater than 0 we can perform the greater than 0 we can perform the similar operations which similar operations which in the last iteration that is in the last iteration that is multiplying them by 10 add X mod 10 to multiplying them by 10 add X mod 10 to num which gives 92 and finally divide X num which gives 92 and finally divide X by 10 so a new values of num and X are by 10 so a new values of num and X are 92 and 17 since X is still greater than 92 and 17 since X is still greater than zero we can move further and perform the zero we can move further and perform the similar operations by which we get new similar operations by which we get new values of num as 927 and value of x is 1 values of num as 927 and value of x is 1 so 1 is still greater than 0 therefore so 1 is still greater than 0 therefore we can perform similar operations which we can perform similar operations which gives final values of num as 9 2 7 1 and gives final values of num as 9 2 7 1 and the value of x is 0 so here we can see the value of x is 0 so here we can see that 9 to 7 1 is a reverse of 1 7 to 9 that 9 to 7 1 is a reverse of 1 7 to 9 which was the original value of x so now which was the original value of x so now let's begin with the code initially we let's begin with the code initially we need to initialize the output num to 0 and the next thing which we need to consider is whether the value of x is if the value of x is positive then mean if the value of x is positive then mean then we need to perform our algorithm then we need to perform our algorithm which I mentioned earlier that is while which I mentioned earlier that is while X is greater than 0 multiplied num with X is greater than 0 multiplied num with 10 then add X mod 10 to num and finally 10 then add X mod 10 to num and finally divide X by 10 that's it we need to divide X by 10 that's it we need to perform the similar operations if the perform the similar operations if the value is negative but with a slight value is negative but with a slight change that is before performing the change that is before performing the algorithm we need to multiply X with algorithm we need to multiply X with minus 1 so that the negative value minus 1 so that the negative value converts converts positive and finally we need to convert positive and finally we need to convert the positive value to negative so here the positive value to negative so here we converted the negative x value to we converted the negative x value to positive by multiplying it with minus 1 positive by multiplying it with minus 1 and again we made a positive number you and again we made a positive number you too negative that's it now we can return num since the return value is int and so a code is not at finished we need to so a code is not at finished we need to consider the node given in the question consider the node given in the question which states that integers must lie which states that integers must lie within the 32-bit signed integer range within the 32-bit signed integer range that is it must lie within -2 power 31 2 that is it must lie within -2 power 31 2 plus 2 power 31 minus 1 so we can check plus 2 power 31 minus 1 so we can check this case by adding a simple if this case by adding a simple if condition at the beginning of the code condition at the beginning of the code as follows so this condition checks that a number is within the range of 32-bit signed integer we need to also contain check this condition for num that is we can add the same piece of code after we multiplied number ten so that's it a cold is over and we can check it by running yeah it's run successfully so we can submit it it is submitted successfully so if you like the video do hit the like button and subscribe to my YouTube channel for more such upcoming videos | 2024-03-18 11:54:54 | 7 | LeetCode 7 | REVERSE INTEGER | ARRAYS | C++ [ Approach and Code Explanation] |
|
bM0bHFD5MZo | A a beauty mausam jo washing machine thoda this question of list ko 12345 to jo question of list ko 12345 to jo question hai uske andar ko question hai uske andar ko 2 released hum ko and one english 2 released hum ko and one english march inside the other english, march inside the other english, there has been a little light this question and there there has been a little light this question and there is no is no ko cheer ko cheer I have tied you to this, so here I have tied you to this, so here in the case, the list on which was initially something in the case, the list on which was initially something like this 0 like this 0 AFun 123 The Four Five and the playlist given to I have given you two I have given you two I have given you two injections, one copy, I assume the cost injections, one copy, I assume the cost and also call to for, so inside this and also call to for, so inside this we have to we have to delete the English in it from the flames to the court, delete the English in it from the flames to the court, then if we add English and this then if we add English and this So I should write something like this in English So I should write something like this in English and the one who is in the list two should be appointed to the one who is related to it, let's do it tomorrow in the middle, meaning now the one who is one will be appointed to 24 and the one who It It It looks like this looks like this 0684 0684 520 two three four 520 two three four courses were deleted and in their place the courses were deleted and in their place the sacred lingus curved octroi. If we sacred lingus curved octroi. If we see how the people do this then it is very see how the people do this then it is very simple for us or not, this minus one of mine simple for us or not, this minus one of mine was bigger in the next one too was bigger in the next one too but but but who will be whitelisted in his next list, and in the same way, whatever is the trail of the list, you will start joining it, B plus one rate, that too plus one will So this one, So this one, So this one, which is this area, its link has been which is this area, its link has been broken, now my last one, it is something broken, now my last one, it is something like this, then this - 110 whatever like this, then this - 110 whatever is the note, the world list tree, then 123 is the note, the world list tree, then 123 is on the astrology center, MS Word Artist. is on the astrology center, MS Word Artist. Death of and after that the list becomes mental Death of and after that the list becomes mental and from where to where, I did and from where to where, I did not get to travel in the list, even from that point onwards, not get to travel in the list, even from that point onwards, those who do the same work will those who do the same work will see every vote, how will I find 219 first, the time which is I will help in tracing the initial whose list is absolutely there, I have knowledge about it, this note which is on the initial, I will not give the snake note which is national E B twisted notes which is on the tree real tap, I Which will Which will Which will help me in indexing travels and help me in indexing travels and its default value is zero from Saturday. Okay, let's its default value is zero from Saturday. Okay, let's do this by going back to do this by going back to time is not equal to how many time is not equal to how many languages do not come empty. Which one is the one in the list, languages do not come empty. Which one is the one in the list, then do not do the entire travels. then do not do the entire travels. then do not do the entire travels. work, till then there will be no organic need. Now let's see why. If my ID app has ever become equal to 1 - one, that means I will get this note, if I get this 10 minutes then I will say that the note request to take I will say that the note request to take I will say that the note request to take is a simple one is a simple one that if ever there is a technical problem with my ID, that if ever there is a technical problem with my ID, then then what is it that Vinod's sequence is 210 tight. Well, if none of these are there then what will I do, that is, I Sequence to daughters and Sequence to daughters and Sequence to daughters and side effects plus two side effects plus two Okay, now let's see Okay, now let's see if it is out of the missiles, that is, my if it is out of the missiles, that is, my hair oil hair oil is connected to Vinod Raina at the right place, so is connected to Vinod Raina at the right place, so what should I put in the anode next. what should I put in the anode next. what should I put in the anode next. in next which is relax to is ducked meaning question list I should dance to see which is this - who should come next in this, the distic head is fine and the oil of Jurist is Manyata Marg, if your function was get a name then the oil of the list is It is playlist to retail in the list ok takey next means - in Vansh I will join it which is mine as well as requested things and as if I have done so much work then in that day if I return to the states of my list one then My work will be done, just in this corner there is a small function hall in a great deal named inside which we are in public list mode on valley and we pass a national valley and we pass a national whose name is note offering okay whose name is note offering okay mobile mobile no doubt next is not a no doubt next is not a no doubt next is not a then what will we do? Nod request Oo know what next Hands free Arjun Notification is done He said in the morning that we are standing on oil, that day we will return [Music] Torch light and vitamin's spelling of course That If there is then extracted answer and from our new people Mian and submit a tier 2 is accepted I think question will share and this love you finally subscribe The Channel and please like button | 2024-03-20 10:35:34 | 1,669 | Merge In Between Linked Lists | Leetcode 1669 | Leetcode BiWeekly 40 | Java | Hindi. |
|
3Ne-G2yySUc | hello everyone welcome to day twenty eighth of stem bitcoin challenge and eighth of stem bitcoin challenge and today's question is sort array by parity today's question is sort array by parity two in this question we are given an two in this question we are given an array of integers and we need to sort array of integers and we need to sort this array such that at every odd index this array such that at every odd index we have an odd integer at every even we have an odd integer at every even index we have an even integer the result index we have an even integer the result can be any such possible array and we can be any such possible array and we need to write down that need to write down that for example here the input r is given to for example here the input r is given to us as four two five seven us as four two five seven four is an even number at the four is an even number at the even index zero so we are good even index zero so we are good second is an even number at an odd index second is an even number at an odd index we have to swap this we have to swap this 5 is an odd number at an even index 5 is an odd number at an even index we need to update this again we need to update this again so what we are going to do we will swap so what we are going to do we will swap 2 with 5 so one possibility of our 2 with 5 so one possibility of our answer would be 4 5 2 7 answer would be 4 5 2 7 how is it satisfying the condition how is it satisfying the condition this is a zeroth index this is an even this is a zeroth index this is an even number this is the second index this is number this is the second index this is an even number this is the at the first an even number this is the at the first index this is an odd number this is at index this is an odd number this is at the third index this is an odd number so the third index this is an odd number so the condition is satisfied and we are the condition is satisfied and we are good to return this array there are good to return this array there are other possibilities that do exist these other possibilities that do exist these are also acceptable are also acceptable without much to do let's look at the without much to do let's look at the presentation and there i'll be solving presentation and there i'll be solving this by two approaches this by two approaches one using an extra space and one that is one using an extra space and one that is in place in place array by parity to lead code922 array by parity to lead code922 and let's and let's reiterate the question here i have taken reiterate the question here i have taken a slightly different example to what was a slightly different example to what was specified in the question the input r is specified in the question the input r is something like this 1 3 4 something like this 1 3 4 6 5 7 8 10 6 5 7 8 10 and what would be one of the possible and what would be one of the possible result we should have an even number result we should have an even number here so let's replace 4 here so let's replace 4 here here and we have 4 here now and this gets and we have 4 here now and this gets updated to 1 and then we have 3 3 is at updated to 1 and then we have 3 3 is at odd index so we are good here let's odd index so we are good here let's forget this forget this next we have next we have is is 1 at this particular index 1 at this particular index so we ideally should have an even number so we ideally should have an even number so let's swap this 2 so let's swap this 2 so we get six comma one so we get six comma one and and the first four elements are sorted uh we the first four elements are sorted uh we have six at the second index one at the have six at the second index one at the third index next we have is third index next we have is five so five happens to be at the fourth five so five happens to be at the fourth index index uh we need to do something we need to uh we need to do something we need to swap this number swap this number and with what value will swap let's and with what value will swap let's we'll see it later on we'll see it later on next we have is seven seven is at next we have is seven seven is at appropriate place appropriate place so let me just write 7 here so let me just write 7 here and 8 is also added appropriate place and 8 is also added appropriate place which is an even index so let's skip which is an even index so let's skip this as well next we have 10 this as well next we have 10 adds an odd index we need to perform the adds an odd index we need to perform the swap operation between these two swap operation between these two so one possibility of answer would be so one possibility of answer would be we swap these we swap these up up and the output arrays five four three and the output arrays five four three six one ten seven eight five there can six one ten seven eight five there can be many other possibilities as well uh be many other possibilities as well uh but this is one of the possible answer but this is one of the possible answer now comes the question how are you gonna now comes the question how are you gonna solve this question solve this question uh let me just uh let me just uh take a different color pen uh take a different color pen and and on the very first and the knife approach on the very first and the knife approach that comes to everybody's mind is to that comes to everybody's mind is to keep track of even elements keep track of even elements in the array also simultaneously let's in the array also simultaneously let's keep a track of all elements in the keep a track of all elements in the array so one happens to be an odd array so one happens to be an odd element so we'll add odd here 3 happens element so we'll add odd here 3 happens to be an odd element we'll add 3 here to be an odd element we'll add 3 here 4 happens to be an even element 4 happens to be an even element we add 4 here 6 here we add 4 here 6 here 5 here 5 here 7 here 7 here 8 and 10 here 8 and 10 here we have segregated even elements we have segregated even elements so these are even and these are odd now so these are even and these are odd now how do we build the answer we will take how do we build the answer we will take two pointers one here and one points to two pointers one here and one points to the first element of the odd data set the first element of the odd data set and we will alternately place first even and we will alternately place first even then odd so four gets placed here then then odd so four gets placed here then we have one we have one one gets one gets updated then this updated then this this has already been placed next we this has already been placed next we have six have six so six get gets placed there next we so six get gets placed there next we have three three gets placed here next have three three gets placed here next we have eight eight gets placed here we have eight eight gets placed here next we have 5 5 gets placed here next next we have 5 5 gets placed here next we have 10 10 gets placed here next we we have 10 10 gets placed here next we have 7 have 7 so the other possibility of answer is so the other possibility of answer is something like this 4 something like this 4 4 1 6 3 8 5 4 1 6 3 8 5 10 7. and this is another acceptable 10 7. and this is another acceptable answer the time complexity of this answer the time complexity of this approach is order of n while the space approach is order of n while the space complexity is again order of n because complexity is again order of n because you are bucketizing all the elements you are bucketizing all the elements into even numbers versus odd numbers into even numbers versus odd numbers can we improvise on this the answer is can we improvise on this the answer is yes let's try and look that approach the yes let's try and look that approach the question itself gives a hint question itself gives a hint that we need to identify that we need to identify two elements if there is a number even two elements if there is a number even number that exist an odd index we need number that exist an odd index we need to swap it with any other odd number at to swap it with any other odd number at an even index and this is what we'll an even index and this is what we'll exactly follow so let's take two exactly follow so let's take two pointers pointers the first one that we'll search for is the first one that we'll search for is an even number at an odd index and the an even number at an odd index and the second one that you'll search for is an second one that you'll search for is an odd number at an even index odd number at an even index so the initialization of these two so the initialization of these two variables would be variables would be uh uh 0 this one would be would point to 0 and 0 this one would be would point to 0 and this one would point to 1 this one would point to 1 because we'll start the first odd index because we'll start the first odd index is one the first even index is zero is one the first even index is zero so let's just so let's just point this up point this up so we are searching for odd number at so we are searching for odd number at even index we find found out an odd even index we find found out an odd number at even index so we'll stop number at even index so we'll stop the next one is even number at an odd the next one is even number at an odd index this is odd so this is not good index this is odd so this is not good what we're gonna do we'll move this what we're gonna do we'll move this pointer by two places pointer by two places so this points to three now what do we so this points to three now what do we see we see a 6 see we see a 6 that means it's a misfit since it's a that means it's a misfit since it's a misfit we are going to perform the swap misfit we are going to perform the swap operation between operation between 1 and 6. 1 and 6. so we'll replace this so we'll replace this by 6 and we'll update this by one by 6 and we'll update this by one let's continue the process let's continue the process for the next iteration once we have for the next iteration once we have updated uh this index will increment it updated uh this index will increment it by two for searching the next even index by two for searching the next even index next even index will point to next even index will point to here now 2 this is already an even here now 2 this is already an even number so we are good number so we are good we are done with this we are done with this let's move ahead next we have is let's move ahead next we have is five at five at four which is again a misfit four which is again a misfit so so let me just change the color of pen let me just change the color of pen this is another misfit this is another misfit in order to find the other number to be in order to find the other number to be swat we look out for swat we look out for an even number at an odd index so where an even number at an odd index so where is that is that pointer pointing to right now this pointer pointing to right now this pointer points to three pointer points to three from the previous iteration from the previous iteration of the for the odd indexes will this is of the for the odd indexes will this is an odd number one is an odd number so we an odd number one is an odd number so we are good we'll increment this by two are good we'll increment this by two again we witness seven which is an odd again we witness seven which is an odd number what we should do we should number what we should do we should increment it by two we witness them so increment it by two we witness them so we found out another misfit which is we found out another misfit which is 7 at index 7 we have 10 and at index 4 7 at index 7 we have 10 and at index 4 we have 5 these 2 needs to be swapped so we have 5 these 2 needs to be swapped so we'll perform the swap operation we'll perform the swap operation so this gets updated by 10 so this gets updated by 10 this gets updated by five this gets updated by five and let's continue the process we were at for the fourth index for this particular pointer for the even index pointer so we'll increment it by 2 we get an 8 and at 6 we have 8 we are good so this is not a misfit we'll continue and this exceeds the length of the input array and we are done in single iteration in place we were able to update the complete array we are looking for the indexes that are misfit for even numbers and for odd numbers as per this logic i'll exactly do the same thing which i have just told and let's move on to the here i have defined two variables here i have defined two variables odd number at even index and even number odd number at even index and even number at odd index and i have taken another at odd index and i have taken another variable n for the length of the input variable n for the length of the input array till the time array till the time both of them are within the limits of n both of them are within the limits of n i go and check recursively every time i go and check recursively every time i'm incrementing by 2 till the time i'm incrementing by 2 till the time i don't i find i don't i find an odd number at an even index if that an odd number at an even index if that is the case is the case i i uh continue this loop however this loop uh continue this loop however this loop will break as soon as there is a will break as soon as there is a different case there is an different case there is an e odd number at an even index then this e odd number at an even index then this condition will not be true and this condition will not be true and this while loop will break while loop will break so once we are out of the loop we are so once we are out of the loop we are pretty sure that pretty sure that the index the index value that will be held here will have value that will be held here will have an odd number at an even index an odd number at an even index similarly this is again a recursive loop similarly this is again a recursive loop we will keep on incrementing the pointer we will keep on incrementing the pointer even number at odd index even number at odd index till the time we have an odd number till the time we have an odd number at at odd index odd index so once we are out of the loop we are so once we are out of the loop we are pretty sure it will hold an even number pretty sure it will hold an even number at an odd index by virtue of this at an odd index by virtue of this condition condition once we know both these indexes once we know both these indexes we will simply swap those up and this is we will simply swap those up and this is a simple check for us to avoid a simple check for us to avoid unnecessary overflow conditions unnecessary overflow conditions once i'm done with this loop i'll simply once i'm done with this loop i'll simply return the updated nums array return the updated nums array and let's try this up accept it the time complexity of this approach is order of n and the space complexity is constant space this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then | 2024-03-25 11:05:07 | 922 | Sort Array By Parity II | Leetcode 922 | Live coding session 💯💯💯 |
|
s647rX6tn4g | hey what's up guys this is chong so let's take a look at uh 1707 so let's take a look at uh 1707 maximum xor with an element maximum xor with an element from array from array so you're given like an array nums so you're given like an array nums consisting of consisting of none negative integers right and then none negative integers right and then and and you are also given like a a queries a you are also given like a a queries a list of queries list of queries which has like uh who has like two which has like uh who has like two elements the first one is elements the first one is x the second one is the amp and the answer is it's the like the size of this queries each answer is the is the maximum bitwise actual value and and any elements and and any elements of the nums that does not exceed of the nums that does not exceed mi so in other words mi so in other words right so you can basically you can do right so you can basically you can do any of the any of the xor you can use any numbers xor you can use any numbers who is smaller not greater not greater who is smaller not greater not greater than mi and do than mi and do x or with the current with the current x x or with the current with the current x i here and then you get you need to get i here and then you get you need to get the maximum of that the maximum of that and if there's no such number exist and if there's no such number exist then just simply put -1 in that then just simply put -1 in that slot so some so here's the example right so for example we have we have no example one here and we have a lid that's the list of numbers and this we have five numbers and then we have three uh queries so the answer will be a and so for the first one and so for the first one right so since the uh 0 and 1 are only right so since the uh 0 and 1 are only two integers not greater than two integers not greater than than one right and then that's why than one right and then that's why no we just pick the uh the no we just pick the uh the biggest one between the x or three biggest one between the x or three uh zero x or three and one uh zero x or three and one x or three that's why we have two x or three that's why we have two that's why we we have three so same that's why we we have three so same thing for the uh thing for the uh for second query and the third query and here's an example so for example this one here since there's no numbers which is smaller than one right that's why we have minus one and here's the constraints right so and here's the constraints right so the length the length for the nums and the length the length for the nums and the queries they're all 10 the queries they're all 10 to the power of 5. and the numbers to the power of 5. and the numbers of x i and m i they are visiting like of x i and m i they are visiting like the integer right 10 to the power of 9. so that's that right i mean the uh obviously the brutal force way will be what so we just for each of the queries right we we loop through all the numbers and for each of the numbers we do uh we do x or right for for any each of the number who is not greater than than the current than this of the m here we do xor with three and then we just get the maximum of that right i mean obviously that's going to be a of n square solutions right then with this constraints that will tle that's what and so which means we have we need to find a better better way that's and that's what makes this problem a hard problem so so for this kind of maximum beat wise a bit wise a bit wise or right within a a bunch of numbers so a common trick to reduce the time complexity is to use like know we will build a prefix try here sorry a prefix tree yeah so the prefix 3 car also called a try so the pronunciation is a little bit weird so probably i'll just call it a prefix tree so because that's more uh it's more common so this this prefix tree has like only has one node will only has up to two child nodes either we have zero we have zero and we just built uh this prefix tree and we just built uh this prefix tree with the numbers here with the numbers here so that in every time when we have like so that in every time when we have like this numbers this numbers we will basically try to get the beat we will basically try to get the beat values values from the from the highest uh from the from the highest uh from the highest position right from the from the highest position right from the left most left most uh locations and then we build it from uh locations and then we build it from from left to to right from left to to right so and why this prefix tree can help us so and why this prefix tree can help us uh uh solve this problem right so the reason solve this problem right so the reason being is that you know the being is that you know the uh since the numbers right since the uh since the numbers right since the numbers are within the beat numbers are within the beat uh 10 to the power of 5 so which means uh 10 to the power of 5 so which means that you know that you know at most each number can have like up to at most each number can have like up to 36 36 bits and since we have we only have 32 bits and since we have we only have 32 bits and commonly you know whenever we want to calculate the bitwise or we always consider so let's say for example i have i'll so let's say for example i have i'll give you a very give you a very simple example here let's say we have simple example here let's say we have like one zero like one zero uh one one uh one one right so let's see we have this this right so let's see we have this this number here let's see this is the number here let's see this is the x yeah let's see this is the x so what x yeah let's see this is the x so what what's this number that's the uh what's this number that's the uh 8 plus 3 that's 11 right so to be able to get the maximum uh the maximum number uh is we do a xor right we do actually with some with some numbers here with some numbers here so in order to get the the back the max values so what's going to be the uh the biggest value we can get we can ever get for this one so ideally what we can get is what is right so so to be able to get us this 1 right so so to be able to get us this 1 1 1 1 1 1 so what's going to be the ideal 1 so what's going to be the ideal candidates for this one so we're hoping candidates for this one so we're hoping this this there's a number that have a bit value there's a number that have a bit value like like 0 one zero 0 one zero zero all right so if we have a zero all right so if we have a such numbers with this with this bit such numbers with this with this bit values then if we do a bit wise with the values then if we do a bit wise with the current x here we can get one one one current x here we can get one one one one which one which which is our ideal answer which is our ideal answer okay and how can we find okay and how can we find how can we know if there's a number that how can we know if there's a number that has this zero one zero zero has this zero one zero zero that's one that's uh that's when we need that's one that's uh that's when we need to use this prefix tree to use this prefix tree with like this zero or one as a child with like this zero or one as a child child node so so here how here's how this this prefix tree works let's say we have uh four numbers let's say we have a one and then we have uh one one zero zero and then we have uh one one zero zero zero one zero one and maybe uh zero one zero one and maybe uh i don't know maybe zero one one one so let's say we have these four numbers and our our x is what x is x is zero zero one how about this one yeah i'm zero one how about this one yeah i'm just giving like a random just giving like a random example here so let's say we have a zero example here so let's say we have a zero one zero one and one zero one and that's the four numbers we have that's the four numbers we have uh as a candidate and how can we use uh as a candidate and how can we use this this uh tree to find our our final answer uh tree to find our our final answer so the way we're doing is we're so the way we're doing is we're basically we're trying to match the uh basically we're trying to match the uh the bit greedily from the highest the bit greedily from the highest position which is the leftmost location position which is the leftmost location so the reason we can do this so the reason we can do this we can do it in this way is because you we can do it in this way is because you know as long as we have like a bit know as long as we have like a bit we have a target we have a value on the we have a target we have a value on the left most left most position that's where we're gonna set position that's where we're gonna set the the market as one because the earlier the market as one because the earlier the earlier we can mark the earlier we can mark the the higher bit load position as the higher bit load position as one the max the bigger value we can get one the max the bigger value we can get so that's why we check the left most so that's why we check the left most beat position we see if we can have like beat position we see if we can have like a number that can satisfy this bit value a number that can satisfy this bit value to be to be to be one after doing the bitwise or to be one after doing the bitwise or so we have zero here so so what numbers so we have zero here so so what numbers we're looking for we're looking for we're looking for we're looking for one right so for this one the tar one right so for this one the tar the target basically the target uh bit the target basically the target uh bit will be the value will be one will be the value will be one and then we'll see okay do we have a do and then we'll see okay do we have a do we have numbers that has a we have numbers that has a starting uh has has a one value at the starting uh has has a one value at the current current value at the current bit position yes we value at the current bit position yes we we have two we have two okay so we will have this two here okay so we will have this two here that's why we have this bit value here that's why we have this bit value here right so we basically we have right so we basically we have we have one one and then here we have a we have one one and then here we have a one zero and one zero and one right and then from from zero we have a one right and then from one we have a we have one so from here we have one one and and then we have zero and then we also so here's one so that's why uh the way we're do so that's why uh the way we're do using this prefix tree is that we start using this prefix tree is that we start from the root node and then we see okay from the root node and then we see okay if if if the current one has like a child has if the current one has like a child has a a a as a one value as one then a as a one value as one then okay we we find one because one there okay we we find one because one there there's a child here there's a child here and then we move to the second bit value and then we move to the second bit value here here so now what do we have we're looking for so now what do we have we're looking for zero right zero zero right zero bit y x or 1 will become 1. bit y x or 1 will become 1. do we have a 1 here because remember do we have a 1 here because remember we're at this note here we're at this note here and then we're checking do we have like and then we're checking do we have like a 0 yes we have we have zero that's why a 0 yes we have we have zero that's why we'll go here we'll go here we'll go to this round right basically we'll go to this round right basically we're going we're going going this way right and then going this way right and then the next one we're looking for one right the next one we're looking for one right so do we have one of course yes we have so do we have one of course yes we have one because the next one one because the next one is one but for the last one we're is one but for the last one we're looking for zero do we have a zero no we looking for zero do we have a zero no we don't have a zero don't have a zero because the all we have is one so that's why you know the best number we can find is it's going to be a one zero uh one one that's going to be our our best answer and how how how about what's what's going to be the answer you know basically every time when we find a match with the target with the target bit values we can accumulate basically we can add the answer because here we find like the the match which means that you know we have at least we have 10 2 to the power of 3 okay and then for the second one we also find the match which means that right and then here we also find one right and then here we also find one right so right so and then we have a two to the power of and then we have a two to the power of one but in the end here we didn't find one but in the end here we didn't find the match that's why the match that's why we don't have anything to add here so in we don't have anything to add here so in total total the best answer we can get is like this the best answer we can get is like this eight plus eight plus 4 plus 2 which is uh 4 plus 2 which is uh 14 in this in this case because in in the end what we can have is a 1 so and as you guys can see here with so and as you guys can see here with this prefix this prefix tree here you know as long as we can tree here you know as long as we can follow a path right greedily right by uh follow a path right greedily right by uh looking for looking for the a match with the highest highest the a match with the highest highest beat look beat look positions we can just traverse down positions we can just traverse down this prefix tree and then this prefix tree and then we can just use the current path to see we can just use the current path to see if we can find the match for the net if we can find the match for the net for the next bit value if we can and for the next bit value if we can and then we just accumulate then we just accumulate the answers with the current beat beat the answers with the current beat beat position position otherwise with skipped yeah so basically that's how we we're going to use this beat this prefix tree to help us quickly calculate the uh a match uh between all the available numbers okay and then the last thing is that since we also have like these constraints with m right which means that we only we're only considering the numbers that's uh that's not greater than m so which means that we cannot just build the prefix tree with all the numbers we have to follow some sequence and then what's going to be the sequence where we're following here we can you know what we can do is we can sort these numbers from the smallest to the biggest okay and then we also sort this queries by the by m from also from the smallest so after doing that you know we can just so after doing that you know we can just every time when we have like a queries every time when we have like a queries here we can just uh here we can just uh we can just grab all the numbers who is we can just grab all the numbers who is smaller than the current smaller than the current the current am right and then we can the current am right and then we can just build the prefix three on top of just build the prefix three on top of that because next time that because next time we have like a another amp here which is we have like a another amp here which is greater than the current greater than the current which is greater than the previous amp which is greater than the previous amp here all we need to do is just that we here all we need to do is just that we can just grab can just grab the a few numbers right after the uh the a few numbers right after the uh after the last the last position after the last the last position so that we oh we can we um we can only so that we oh we can we um we can only uh add these numbers in the uh add these numbers in the in the prefix in the prefix tree once by in the prefix in the prefix tree once by following following this sequence here right so otherwise you know otherwise if we don't if we don't sort this one so for each of this for each of the queries here we have to loop through all the numbers right we we have to find all the numbers that's smaller than the current am and then we build the prefix tree that's going to be too slow okay so enough talking let's start okay so enough talking let's start coding here coding here and so first thing first right let me and so first thing first right let me create a note for my uh pre for my create a note for my uh pre for my prefix prefix tree right so i'm going to have a node tree right so i'm going to have a node here here and so init and then here all i need is just a and then here all i need is just a children here right so children is like children here right so children is like the the another dictionary right and here we at another dictionary right and here we at most will have two most will have two two child two children but i'm still two child two children but i'm still using like dictionary here using like dictionary here here and we have a root because the node here and we have a root because the node right and then to build the uh right and then to build the uh the prefix tree we have we need an the prefix tree we have we need an insert right and then we have uh we have a query right so we have a two cr and here i'm i'm creating all the uh the signature of the methods first and then we can uh implement those two methods later and then here assuming we have those kind of in certain queries and then all we have is the length of nums right we have this n here and then like i said i sort the numbers right from smallest to the biggest and then i also need to store the queries but after sorting that we will lose the uh the original the original uh other but we also but which we still need to do to output right to do the output that's why i'm going to create a new course object right a list with the original index and the x m for i dot xm chris okay and then i can sort chris okay and then i can sort sort key gonna be the lambda of the uh sort key gonna be the lambda of the uh x x two right so this one x x two right so this one the m we're sorting on top by that the m we're sorting on top by that and then uh i need the uh the answer and then uh i need the uh the answer right so the answer is minus one right so the answer is minus one at the beginning i'm giving it all minus at the beginning i'm giving it all minus one so length of q one so length of q and then for i and then for i x i'm in this sorted queries i also need a j right so to to tell us what was what was the last position well we added we have added the numbers to the to the prefix tree right so while j is smaller than n and nums j it's not greater than m then we just do it's not greater than m then we just do an insert we insert this one into the an insert we insert this one into the into the prefix tree and the into the prefix tree and the right we do this and then here we just right we do this and then here we just do a do a nums uh populate answers i with the nums uh populate answers i with the query of query of x yeah actually we so about the minus one case right so how about minus one and we only do this when the uh if the j is greater than zero so here it means that you know if j is is one i'm sorry if j is zero it means that there's no numbers that's uh that's gonna be smaller than the m that's why then we can simply just uh leave this minus one and we only do the xor when there's something right there when there is any something that's that is smaller than m so that's the the main structure of this so that's the the main structure of this of this of this of this problem and now let's try to of this problem and now let's try to implement this implement this insert and the query so for current so insert and the query so for current so to insert is like similar like the uh to insert is like similar like the uh there are juno there are juno like prefix three implementations so the like prefix three implementations so the only difference is that you know for only difference is that you know for each of numbers we're going to loop each of numbers we're going to loop through from through from from the highest bit to the lowest to from the highest bit to the lowest to the the lowest which is the starting from 31 lowest which is the starting from 31 to zero okay and so we have a bit values so we're going to calculate the bit value of the current one it's going to be the what numbers now we just move shift to the right and then we do our n and one that's how we get the the value of the current bit and if the bit not in the current dot children right and then we do a current dot children dot beat because the new note okay and then i just we just move the the current node to the knight to the next one yeah so so which means that you if yeah so so which means that you if there's like a there's like a multiple like numbers that has the same multiple like numbers that has the same as the values at the same note we just as the values at the same note we just simply ignore it and we keep simply ignore it and we keep moving forward right and for the queries moving forward right and for the queries right right like i said so we also starting from the like i said so we also starting from the root root and then at the beginning we have zero and then at the beginning we have zero equals uh the answer is equal to zero equals uh the answer is equal to zero and we also from loop through from the and we also from loop through from the i in range of 31 minus one and i in range of 31 minus one and minus one so the target minus one so the target right so remember the target the target right so remember the target the target i is actually the opposite i is actually the opposite value of of the current bit right value of of the current bit right because because again right we're trying to get the max again right we're trying to get the max numbers which means that fret numbers which means that fret since for x uh bitwise or if the since for x uh bitwise or if the the current bit is zero we're looking the current bit is zero we're looking for one if it's current for one if it's current value is one we're looking for zero that's why the so the current bit value is this one and to be able to get uh an opposite values basically we can just copy this one and then we can do a x or one that's how we get the target so if the target exists right in the current children so it means that okay we've we have we have a tar we have a match after our tar of our target values that's then we can just accumulate the current answer with the uh with the current beat value right with this one if this current bit is is three then it means that uh we can accumulate eight to the to the answer and then we just move the uh children right we also move move the current the node to the next one the target one else so else if there's no match obviously we there's no there's no new uh values to be accumulated and then the next value will be what will be the current equals to the uh it's going to be the actually the original beat right so it's going to be the target we do a another one we basically we flip the the b value one and then in the end we return the answer okay so i'll repeat this this part one okay so i'll repeat this this part one more time more time so first we're trying we're getting the so first we're trying we're getting the target right which is the uh target right which is the uh the opposite value of the current bit the opposite value of the current bit right and right and if we if there is one then we will go to if we if there is one then we will go to the uh the uh basically of course we'll go we'll go basically of course we'll go we'll go there and then we're accumulating the error the the answers if the target is not there if target's not there and it means what so it means that since we're only having two nodes it's either zero and sorry it's if we don't have a zero it means that the the child has to be one right because we're we're having at most at most two nodes but at least one nodes right so there's no there's no way that you know the current one doesn't have doesn't have have a child because when we when we build the uh the prefix tree here so you see that we're starting from 31 and we we go we build the tree all the way to the to the to the zero bit which means that at least a node will have like a node so it if the current one doesn't have the target node then it has to be the the opposite value okay that's why you know the if the okay that's why you know the if the target is there right and then we of target is there right and then we of course course will go with the target node path if the will go with the target node path if the target is not there we know that target is not there we know that so the child has to be the opposite so the child has to be the opposite value that's why we value that's why we we can safely go to the other values path cool i think that's it or let me run the code okay run yeah so accept it so for the time com time and time complexity right the the insert and the queries for the prefix tree you know because things we have at at most 30 to 32 operations so we can trade this insert and query to both o1 and then actually the only thing left is and then actually the only thing left is just these two swords here just these two swords here that's gonna be the uh the sortings we that's gonna be the uh the sortings we have here because the sorting is have here because the sorting is it's like n log n right it's like n log n right here we have also have an unlock n and here we have also have an unlock n and here it's just an here it's just an that's why the total time complexity for that's why the total time complexity for this one is going to be the n log n yep yeah i think that's it right so for this problem you know it's i think it's one of the things we uh we learned from this problem is that every the so next time when we are trying to get the maximum remember it has to be the maximum the maximum bit wise x or values between one number and a group of other numbers and we're trying to find the maximum this prefix tree is a good way since we can since we have we have since we can since we have we have we have given like the x here we have given like the x here we know our target right so we know our target right so we just get our target value bit by bit we just get our target value bit by bit here and then with this target values here and then with this target values we'll we'll basically will traverse this basically will traverse this this prefix tree from top down this prefix tree from top down and then we'll try to find a match we'll and then we'll try to find a match we'll find a node find a node with this target value if if there if it with this target value if if there if it is then is then we can accumulate the values from for we can accumulate the values from for that bit that bit position and then we'll go with that position and then we'll go with that otherwise otherwise we just continue our our traversing we just continue our our traversing until we reach the the last beat position i think i'll just stop here and thank you so much for watching this video guys stay tuned | 2024-03-20 15:07:13 | 1,707 | LeetCode 1707. Maximum XOR With an Element From Array |
|
q7vrDzmHTiw | hello everyone welcome back here is van damson and today we are diving into a damson and today we are diving into a coding challenge that's often asked in coding challenge that's often asked in interview determining if number is power interview determining if number is power or free so if you're new here make sure or free so if you're new here make sure to hit the Subscribe button and ring to hit the Subscribe button and ring notification Bell so you never miss on notification Bell so you never miss on our coding Adventure okay so let's take our coding Adventure okay so let's take a look at the problem statement we are a look at the problem statement we are given an integer n and the task is to given an integer n and the task is to return true if it's a power of 3 return true if it's a power of 3 otherwise return false so this problem otherwise return false so this problem may look simple but there is more add may look simple but there is more add than one a way to solve it so the first than one a way to solve it so the first method use Loops while the second method use Loops while the second employs some mathematical in size so we employs some mathematical in size so we will start with a first one so we have a will start with a first one so we have a class solution and method is power of class solution and method is power of three and the method takes an integer n three and the method takes an integer n as argument as argument and yeah so now the first thing to check and yeah so now the first thing to check is whether the given number is less than is whether the given number is less than uh one if it is we can immediately uh one if it is we can immediately return false a power of 3 has to be a return false a power of 3 has to be a positive number positive number so let's implement it so let's implement it so if n less than one so if n less than one return return false false and while and model of three and while and model of three zero and zero and divided remainder and return and equal divided remainder and return and equal one so let's run it to verify its one so let's run it to verify its working working so yeah it's working and for n given 27 so yeah it's working and for n given 27 it's true because 27 is 3 to the power it's true because 27 is 3 to the power of 3 and as you can see of 3 and as you can see the function immediately return false if the function immediately return false if it's less than a one and the next step it's less than a one and the next step is to divide the number three uh our is to divide the number three uh our number by three so and repeatedly until number by three so and repeatedly until it's no longer divisible by three so we it's no longer divisible by three so we check modulo 3 and also check modulo 3 and also a division without remainder by F3 so a division without remainder by F3 so and finally we check if we left with one and finally we check if we left with one if we are that means N is a power of if we are that means N is a power of three so let's submit it for unsynthesis three so let's submit it for unsynthesis cases cases so it should work so it should work okay so yeah it's working and we beat uh okay so yeah it's working and we beat uh yeah 71 with respect to runtime and also yeah 71 with respect to runtime and also 95 with respect to 95 with respect to memory so now let's erase it and we can memory so now let's erase it and we can implement the second mathematical implement the second mathematical implementation it's really interesting implementation it's really interesting so return n greater than zero and number model of n equal zero so all right let's move on the second method which doesn't use Loops or even recursion so did you know that the largest power of 3 that fits into a 32 a bit integer is a free to the power 19 is one one six two two six one four six seven so we can use this information to solve the problem in a very efficient way so it's just return n greater than zero and yeah this number model n and voila you can see that this method also worked like a term so let's run it and yeah so it's working for our test case and let's see if it's working for unsinterest cases as well so yes it's working and we beat 99 with respect to memory and yeah it's took 94 milliseconds so uh quite good and so there you have it two methods to solve the esport of free problem so I hope you fun fun and for those interested in other and for those interested in other programming languages I will include the programming languages I will include the link in the description below for link in the description below for implementation in C plus go Russ and implementation in C plus go Russ and much more and if you enjoyed this video much more and if you enjoyed this video make sure to hit the like button and if make sure to hit the like button and if you have any question or suggestion for you have any question or suggestion for the future video leave the comment below the future video leave the comment below and until next time keep practicing and until next time keep practicing happy coding | 2024-03-24 10:31:28 | 326 | Crack LeetCode 326. Power of Three Coding Interview Question! 🤯 | Two Mind-Blowing Methods Explained |
|
I3ZKNIPDlCs | 114 WhatsApp Guys Welcome to my channel, so today we will solve one of the least important heart problems, today we will solve one of the least important heart problems, interweaving of strings, interweaving of strings, so first of all we will discuss the approach in the problem, so first of all we will discuss the approach in the problem, withdrawal logic canteen. All right, so withdrawal logic canteen. All right, so as I always say, the as I always say, the most important thing in dynamic programming is our most important thing in dynamic programming is our approach. approach. approach. logical field then it does not take much time to do the court. Ok then the problem is that it is saying that keep us from 30, Aishwarya students are three, so I have asked that I can become ST by using Ishwar S2. Can I do it, do I have to use it for the whole semester? Okay, so how is the problem of chromium falling down? Let's discuss it. Okay, so this is the example. Okay, so see, if I have to do something strange like this, then I have only one I have only one I have only one requirement, which of my requirement, which of my Ashraf-ul-Haq is doing this, F1 is doing this, it is Ashraf-ul-Haq is doing this, F1 is doing this, it is storing and analyzing, so I have taken the area from S1, this point Went back then I have a Went back then I have a Went back then I have a requirement then do S2 If you have a pointer then requirement then do S2 If you have a pointer then coaxing is not possible then back I used school only Now coaxing is not possible then back I used school only Now I came here I came here Edward Carpenter came here and I have a Edward Carpenter came here and I have a requirement Okay so team my S2 then where is it requirement Okay so team my S2 then where is it Okay, so I gave it to him, I took it, that is, I Okay, so I gave it to him, I took it, that is, I took his S2 Siskaari, now took his S2 Siskaari, now see what else is there that I can see what else is there that I can take it from being a requirement and also from MS Word take it from being a requirement and also from MS Word and not from S2, okay, so and not from S2, okay, so here I have here I have here I have dynasty or S2 treatment is okay so if you see here the choice is coming to you then you understand Chowk this is telling me problem to think extremely Gemini regular I am okay 24 This is done and Yoga is that I have to do work full Yoga is that I have to do work full Yoga is that I have to do work full stringer chat using all the letters stringer chat using all the letters ok so I don't think it takes much effort for me to understand online ok so I don't think it takes much effort for me to understand online top comments Shravan means Tribhag felt then she came back to Bigg Boss, means Tribhag felt then she came back to Bigg Boss, neither will you take your choice and this neither will you take your choice and this neither will you take your choice and this solve it, so soon after all what is doing this, if possible, first of all I will put on the rest, I am Rinku, I am Mohit, I am fine with the first record, then after that I will talk, okay, let's solve all Lungi Springs A B & C Lungi Springs A B & C Lungi Springs A B & C worry ok string to solve one will go worry ok string to solve one will go mine will also go C ok zero will go mine will also go C ok zero will go 000 ok all these are their starting 000 ok all these are their starting point also A N is ok from the alphabet that point also A N is ok from the alphabet that I have to return Babool return drink I have to return Babool return drink p bhool salt strengh p bhool salt strengh p bhool salt strengh trick C and what's in Tylent J&K Okay see now now look let's come to the choice First of all it's very easy to think crow also okay so 34 what is it I have that 24 that stroke okay all make a merit So the result is shrink to pause, forget the result is full pimple to pause, I will tell who made it, okay, if it comes to this, it is okay, that's why I will take this training, to remind me speed is dependent on science in tab is equal to dot size intense. Penance is equal to blot size intensify equal to zero size okay this is I took all the strings of okay this is left in the ants and what a guy is equal to this lesson learn personal so what does it mean that I this Priyanka I I I can use that to make my interleaving lion, okay, so can use that to make my interleaving lion, okay, so from here also, I will not get any result, from here also, I will not get any result, record, dress and initial, this is my result record, dress and initial, this is my result for this, okay, so maybe for this, okay, so maybe I can call it from the record, please. I can call it from the record, please. I can call it from the record, please. my exam comes then my net record will be broken, that's why I am writing like this, okay so Solve K B C D I Plus One because I have used this trick, Gel Reminder and K Plus One, okay so this is it, I have And Amit, I And Amit, I And Amit, I only vote among myself on the day of jail extent and chief and that DJ is equal to see, this DJ is equal to see, this means that I am also means that I am also getting results from spring, otherwise I could never getting results from spring, otherwise I could never get angry in this form. get angry in this form. get angry in this form. told in the example, okay, 10th lets, then here also he will race with me and solve one now, machine earning from Avel, 20mg plus one, market plus one, okay, then back here and that is why this case of mine can be My result for My result for My result for appreciation and that this one should be character appreciation and that this one should be character but my two is coming as but my two is coming as seen earlier in this case not that I also seen earlier in this case not that I also got the space okay so let me listen if you got the space okay so let me listen if you source the gift rate then take the dream also. source the gift rate then take the dream also. Return to me further, Soul was sleeping ok Return to me further, Soul was sleeping ok but but from here and to do two was coming but but from here and to do two was coming so I took another from back ok and so I took another from back ok and in the end what will I return then the in the end what will I return then the race will end ok then race will end ok then if I don't get answer from both the places if I don't get answer from both the places Meaning, it doesn't even come from this condition. Meaning, it doesn't even come from this condition. More than this condition, I have kept it close after More than this condition, I have kept it close after seeing the electronic test. seeing the electronic test. Okay, so return file. Okay, now let's talk about Okay, so return file. Okay, now let's talk about West Indies. Okay, I know what happened to this condition. This is the condition. It will be quite simple. quite simple. quite simple. say that I have to use all the springs, this one also, Singheshwar, I have to use the next one and add it, okay, so if I use all the strips, then this one of the pendant, if you see it, then This is that my This is that my This is that my intake quantum will also intake quantum will also come here, the point of S2 will now come here come here, the point of S2 will now come here and also the point A of ST, which is the index point, will and also the point A of ST, which is the index point, will come here, meaning so that Noida the way are come here, meaning so that Noida the way are looking so so what. looking so so what. looking so so what. equal to ncd and that i request to a bj is equal to in thi than what return true that ki ss k ricardo nc ok my ki ss k ricardo nc ok my ketu has come to the end but ketu has come to the end but yes this is the thread ok so it can be said yes this is the thread ok so it can be said yes this is the thread ok so it can be said that my key should be added and this support should go wherever it is, that means I can make this Singh strange only by using S2, but ST is not such a case for me, okay, so the sequence for this is E E E Wait its sequence I can Wait its sequence I can Wait its sequence I can return for specific only NC why return for specific only NC why but meaning that enter has but meaning that enter has not reached Ujjain ok then that money problem not reached Ujjain ok then that money problem day is quite simple and electronic after doing it you day is quite simple and electronic after doing it you will know how well I have written something in will know how well I have written something in English ok so this is what I have done 10 English ok so this is what I have done 10 English ok so this is what I have done 10 write, all these are going well, is there any difference, okay, so this is my record seat, its power will be expanded, see, I will submit it in the year, which will be done, isn't your upcoming one recorded, isn't it So okay, now So okay, now So okay, now I have to memo it to remove it from Delhi, okay, sorry, I have to memo it to remove it from Delhi, okay, sorry, what should I see, what are what should I see, what are my parameters changing, so let's my parameters changing, so let's keep it simple, one thing is changing keep it simple, one thing is changing and there is one more thing. and there is one more thing. and there is one more thing. baby, there is a change that the plus one class thing did not come and by doing this thing my answer is changing that we are always incrementing to compare, is it okay then Lakshmi did director vector in sorry. Vector vector ki in TDP ok now let's fold BJP bp dot assign a scientific doctor sir expensive what oo come we are fuel plus point I have to return the size initial here also Tulsi control book-1 In N B plus In N B plus In N B plus one - I am okay, so this is my table, one - I am okay, so this is my table, I have done minus one in this first school, I have done minus one in this first school, okay and return and I have to toe the answers, okay and return and I have to toe the answers, okay so come in the DP in the answer, this is equal to dress okay. this is equal to dress okay. this is equal to dress okay. where I am breaking the results of all my problems and if I see this note related to FD PI, equal to minus one means there is a problem, it has already been solved, so in that case I will return DPI. If dance on a person is a loser, let us sacrifice and discuss running status of matter cold, think 75 percent poster, then Dhan, if your problem is solved, then look, Samra is doing this, what did you do in the problem, first of all I Man going to me the choice is Man going to me the choice is Man going to me the choice is ok what is the problem of my bike ok what is the problem of my bike depends on then I came to know depends on then I came to know that it is delaying the index at the point of powder and S2 of one ok that it is delaying the index at the point of powder and S2 of one ok van I hate van I hate you just right you just right you just right ABC heart is forced hand juice milk and developed thick is my choice I have written here and this table condition is done okay all three of them have to do this blouse all three conch and only Karegi Singh is utilized which Just give NC very soon, Just give NC very soon, Just give NC very soon, after Aaron Finch, I saw that my answer is after Aaron Finch, I saw that my answer is correct, then what I did while correct, then what I did while washing it in Memo Ishqiya, washing it in Memo Ishqiya, I saw that my two parameters I saw that my two parameters are varying, and from that I did a to-do. are varying, and from that I did a to-do. are varying, and from that I did a to-do. made a list and Shershah has given his results for the problems and I am not worried and if my problem is solved then I am giving the competition again. So, this problem was so simple unlike the birthday one, there was nothing If not then If not then If not then you are sorry for this, you can also see its solution you are sorry for this, you can also see its solution here, the memo is also for him and BJP is fine, it here, the memo is also for him and BJP is fine, it means he has a hydrated blackwater mood, he is so means he has a hydrated blackwater mood, he is so difficult to think, it is difficult to think, it is very easy for toppers to think at the bottom up, so very easy for toppers to think at the bottom up, so like this. like this. like this. my channel thank you for watching my beloved. | 2024-03-20 13:43:16 | 97 | LeetCode 97. Interleaving String | Dynamic Programming | Coding Walk-through | Interview Prep 🔥 |
|
58LRot_AOPg | hey everyone today we are going to throw the electrical questions shortest path the electrical questions shortest path in binary metrics so you are given n by in binary metrics so you are given n by n binary Matrix grid return the length n binary Matrix grid return the length of shortest career path in The Matrix if of shortest career path in The Matrix if there is no clear path return -1 a clear there is no clear path return -1 a clear path near binary Matrix is a pass from path near binary Matrix is a pass from the top left cell 0 0 so here the top left cell 0 0 so here to the bottom right cell and minus 1 and to the bottom right cell and minus 1 and then minus 1 so here then minus 1 so here so so um such that all the all the visited um such that all the all the visited cells of past are zero cells of past are zero and all other adjacent series of paths and all other adjacent series of paths are eight directionally connected are eight directionally connected so they are different and they share the so they are different and they share the edge or corner edge or corner the length of a clear pass is a number the length of a clear pass is a number of visited cells of this path so let's of visited cells of this path so let's see the example so you are given zero see the example so you are given zero zero zero one one zero one one zero and zero zero one one zero one one zero and the output is four because uh we can the output is four because uh we can move like a restart from zero zero and move like a restart from zero zero and then move right and then next so in this then move right and then next so in this question we can move like a Direction so question we can move like a Direction so we move like a bottom right and then we we move like a bottom right and then we move at the bottom side and then so we move at the bottom side and then so we passed like a four zero so that's why I passed like a four zero so that's why I have to put these four in this case have to put these four in this case and uh so example three is a kind of and uh so example three is a kind of edge case if edge case if um zero zero is one in the case we can't um zero zero is one in the case we can't move so in this case output is -1 move so in this case output is -1 so for the most similar question I so for the most similar question I solved before so solved before so we moved like we can move like a full we moved like we can move like a full Direction but I in this question we move Direction but I in this question we move um eight Direction um eight Direction so that's the difference so that's the difference yeah so let me explain how to solve this yeah so let me explain how to solve this question before I start my explanation question before I start my explanation so let me introduce my channel so I so let me introduce my channel so I create a lot of videos to prepare for create a lot of videos to prepare for technical interviews I explain all technical interviews I explain all details of all questions in the video details of all questions in the video and you can get the code from GitHub for and you can get the code from GitHub for free so please subscribe my channel hit free so please subscribe my channel hit the like button or leave a comment thank the like button or leave a comment thank you for your support you for your support okay so let me explain with this example okay so let me explain with this example so actually I have three things just so actually I have three things just only three things I have to explain so only three things I have to explain so one thing is that if a starting point is one thing is that if a starting point is one so in that case we should return one so in that case we should return minus one minus one so that is the one thing so that is the one thing and next so we Traverse this Matrix with and next so we Traverse this Matrix with a breast first search so we use a q a breast first search so we use a q so the data we keep in the so the data we keep in the queue is at like a row column and the queue is at like a row column and the distance distance so this distance should be a return so this distance should be a return value so that is a second thing value so that is a second thing and the third thing is that um and the third thing is that um so so every time we visit a new place so up to every time we visit a new place so up to date new date new Place uh with one like this Place uh with one like this like this like this so that prevent us from regularly so that prevent us from regularly visiting the same phrase visiting the same phrase so we can calculate such so this path so we can calculate such so this path properly properly and so that is acting the breast for and so that is acting the breast for such but before press for such that such but before press for such that means starting point means starting point so so um once you start um once you start um algorithm um algorithm update starting point update starting point with one with one so only this place is Omega before press so only this place is Omega before press or search so that is a different case so or search so that is a different case so after that new place is a updated in the after that new place is a updated in the breast for such breast for such so I'll show you so I'll show you um how to write a code later um how to write a code later yeah so that is a basic idea to solve yeah so that is a basic idea to solve this question so without being said this question so without being said let's get into the code let's get into the code okay so let's write the code okay so let's write the code um first of all check if the starting or um first of all check if the starting or sorry I forgot to say so ending cell sorry I forgot to say so ending cell also blocked that means uh one so we also blocked that means uh one so we can't reach goal definitely right so in can't reach goal definitely right so in the case we should return -1 so if with the case we should return -1 so if with zero zero so that is a starting point zero zero so that is a starting point equal one or equal one or so gold should be minus one and a minus so gold should be minus one and a minus one one equal one in the case we should return equal one in the case we should return minus one minus one if not the case so if not the case so keep length of lead keep length of lead as a n and so we can move eight as a n and so we can move eight directions so directions directions so directions equal equal so so 1 0 1 0 and the minus one zero and the minus one zero and uh and uh zero one zero one and zero minus one and zero minus one and one one and then one minus one yeah like this yeah like this and then after that so use Q for press and then after that so use Q for press for such so Q equal so e is DQ for such so Q equal so e is DQ and uh and uh as I explained earlier so the data we as I explained earlier so the data we keep in Q is like a keep in Q is like a um row um row from from and the distance is one so yeah I'll say this one and then um after that Mark starting cell as a visited so click zero zero equal one so that we can uh prevents revisiting and then so now from now on WE implement the breasts as such so while Q so Q has data first of all um take the lift data from Q so row column and these lift data from Q so row column and these tons tons so equal to Q dot up left and uh if law equal n minus 1 and then column equal n minus one so in the case uh we read the uh so ending cell so return distance so reached reached the ending set if not the case um like I X X pro or possible Neighbors so for let's say DX and DUI in so let's say new low and the new so let's say new low and the new column equal so current low plus purus column equal so current low plus purus DX and the current column plus d y DX and the current column plus d y after that after that um okay so check if the um okay so check if the May bar is is in May bar is is in the grid and they're not the grid and they're not um um blocked so if zero greater than or equal new low and uh less than n and zero greater than or equal to new column and less than n and delete new row and the new column equal zero so in the case add a new row new column and a distance plus one to Q so put up end and uh new role and a new column and distance so this is a current length and the next portion should be plus one right so that's why plus one and then don't forget to update currency and not correct a new cell um to a wizard one so that we can prevent dbsd so grid and a new role and a new so so if we reach the like a ending cell uh we if we reach the like a ending cell uh we can definitely return distance here so can definitely return distance here so if this while loop finish that means we if this while loop finish that means we we couldn't reach the goal so in this we couldn't reach the goal so in this case just return minus one yeah that's it so let me submit it I got the error here so ah so we need a triple here so like this yeah so let me submit it looks good and I believe sent um algorithm so b294 so time complexity of this solution should be o n Square where N is a size of a grid so in the worst case best for such algorithm needs to visit each cell once and since there are any Square cells in the grid so time complexity is a proportional to n Square so space complexity of this code is also one square in the worst case so the main contribute to the space usage is the queue used for resource such traversal so at any point the queue can hold at most n Square elements in the worst case scenario where all cells needs to be visited so that's why space complexity is on Square yeah so that's all I have for you today if you like it please subscribe Channel hit the like button or leave a comment | 2024-03-25 17:12:48 | 1,091 | Shortest Path in Binary Matrix - LeetCode #1091 Python, JavaScript, Java and C++ |
|
BtyCm8zmTpI | all right let's talk about the result ip address so a valid fbi just consists of address so a valid fbi just consists of exactly four integers separated by a exactly four integers separated by a single dot so each integer is between 0 single dot so each integer is between 0 and 255 and cannot have leading zero so and 255 and cannot have leading zero so which means which means this is not valid this is not valid and this is not valid and also this is and this is not valid and also this is not valid right so you are given the not valid right so you are given the string s string s containing only digits and return all containing only digits and return all possible value ip address that can be possible value ip address that can be formed by inserting dot into the s right formed by inserting dot into the s right so this is the given stream so this is the given stream so you can possibly return this one or so you can possibly return this one or this one right so this one right so uh you just have to know the uh you just have to know the the length of the string is actually the length of the string is actually um um it's actually restrict between it's actually restrict between four four and twelve right so you can have either and twelve right so you can have either zero point zero point zero point zero zero point zero point zero point zero right or you can have 255 255 255 255 right or you can have 255 255 255 255 which is 12 right so you can actually which is 12 right so you can actually have a base case for this to just making have a base case for this to just making sure the dollar string is about right so sure the dollar string is about right so it's if that is less than four or it's if that is less than four or as the lens is actually greater than 12 as the lens is actually greater than 12 i can actually know this is not a the i can actually know this is not a the stream right so stream right so i will have a list of string i will have a list of string uh become a google variable variable to uh become a google variable variable to store my value at the address so i'm store my value at the address so i'm going to release i'm going to return this right right over here so uh what i will do is i i will actually uh split the string to four segment so for each segment i will just make sure this the number is actually between 0 and 255 if that is if that is good i will move on the next index so at the end i will just just making sure my uh four different segments and adding the dots so uh you might understand why i meant but this probably is easy way to okay so i have a inner risk statement right and i will have a helper function and it's going to be popular void and i'm going to pass in the string and passing the index of the string and from passing the segment and also passing the segment index so you would know like which uh which position you are at and i'm going to call this function s so starting from 0 and passing the in array and you also start from zero and at the end you just return this so let's talk about how i need to take care of the base case for this helper function so if i index if the string index is actually equal to s length i probably i probably should know like i have to make sure my sigma index is also equal to 4 right if that is true then i can actually know i can add a string to my list right so and segment index is actually two to four i would just say list new string so i will convert the sigma number in the ring number to the string and add into the list so i'm gonna say segment zero plus dot plus segment one plus dot plus segment two plus dot plus sigma three right and later on you'll just return so this will be the return value if you find the segment is valid right and just want to make sure if there is a problem when the either sigma index is actually equal to four and you didn't finish the traversing the string then you have to return right or you either actually hit the end of the string but the sigma index is not equal to four so which means this is now the value string right so you have the lc else if case right so if index is actually equal to x or all the segment index is actually 24 you also have to return so this will be pretty much the base case so i'm going to traverse so for the length for each for each integer in the sigma is either between one and three right so this is one right this is three so you have you have like a one and three possible uh traversal right so length less than equal to three of course and i also want to making sure like my current position for the index in the string for the full full string plus the length is actually less than equal to the extra length so i will not get out of bound right so and then plus index is actually let's simply and i'll just keep plus my name so uh in this situation i will actually just uh pause pause in my string to the integer so i will be able to know and i actually get about this energy or not right so parse in and what i will do is i will have to substring the the with my length right with my length right so so index so the current position is index so the current position is actually zero right zero plus the length actually zero right zero plus the length so it could be one so it could be one so zero one right but you don't actually so zero one right but you don't actually include include the the uh the last one so substring is actually uh the last one so substring is actually exclude exclude the the the last character right so in this the last character right so in this process so just want to make sure you process so just want to make sure you know know what is substring method and also if the what is substring method and also if the valid valid the value if the value is actually what the value if the value is actually what is actually greater than 255 is actually greater than 255 so you don't want it and also so you don't want it and also uh the leading zero right the leading is uh the leading zero right the leading is the leading zero so if the length is the leading zero so if the length is actually greater than one actually greater than one and also and also the star chart at the star chart at index index so you always have you always use index so you always have you always use index this is because the first character is this is because the first character is it is an index position not index plus it is an index position not index plus then not index plus you know then not index plus you know it's not it's not it's not it's not all the situation it's always in this all the situation it's always in this star.chart at index star.chart at index if that is equal to zero the first if that is equal to zero the first character then you will have to break character then you will have to break out out this is not valid okay this is not valid okay so just want to make sure this is not so just want to make sure this is not valid valid and it's always happened on the first and it's always happened on the first integer and you always have the integer integer and you always have the integer i mean the index the current index for i mean the index the current index for each segment for sure each segment for sure and and if everything if everything is is pretty good right then you are is is pretty good right then you are just passing just passing the the uh the value into your segment uh the value into your segment and and just call your uh just just call your uh just traversing for the rest of the character traversing for the rest of the character so i would say have s so i would say have s and the index cross and the index cross right i'm using the length so just in right i'm using the length so just in this plus length and that would be the this plus length and that would be the exact exact position exact exact position where you add in the string where you add in the string and also i need to pass a segment and and also i need to pass a segment and segment with segment with sigma index will plus one no matter what sigma index will plus one no matter what right because i already store this right because i already store this current current index already so if you backtrack right index already so if you backtrack right you have to you have to restore restore the the segment to negative one so you you're segment to negative one so you you're actually reusing again actually reusing again and and so so uh this is actually pretty much the uh this is actually pretty much the solution so solution so let me just run the code and see what let me just run the code and see what happens happens i might get some error for sure okay i i might get some error for sure okay i don't and here we go so for time is base complexity so for for every obvious for the uh full time i actually don't know but for the space is actually what uh it's actually the height of the tree so if you actually think about the back tracking this is actually the tree so i would say like all of probably the the land of the ass so it's going to be all of logan for sure and for this time i have no idea so if you have any solution please let me know and | 2024-03-20 13:19:56 | 93 | LeetCode 93 | Restore IP Addresses | Backtrack | Java |
|
o4B0Mb2aaxE | okay cool 312 burst balloons givin em balloons indexed from 0 to n minus 1 well that's not a complete sentence that's why I read Tyler will anyway huge balloon is painted with number are they represent by away gnomes you are asked to first order the balloons after you what if I guess what after you burst balloon I if you purse balloon I you will get numb left numb sup left times numb sub I times numbs up right coins here left and white other adjacent in taxi safai after the burst the left and right then becomes a Jason find the maximal number of coins you can collect by bursting the balloons wisely okay and some stuff about boundary conditions and you have pen is you go to 500 okay uh-oh it was kind of fun okay please um no spoilers then but you could watch me struggle but please no spoilers a little bit okay hmm so my first inclination is just try to think is this greedy and usually it's not I mean I explained this a couple of times but I feel like greedy is always like a trap and if that's the case and maybe it's dynamic programming but what is the dynamic mode when we write hmm because this is only adjacent right so it's not like you're not splitting things in half necessarily but and how do you keep track of those things now become adjacent hmm okay I'm still so right now I'm still thinking about data and programming I'm just trying to think if it is dynamic programming how do i you know what is the DP on also please don't give me hints for this one for a little bit I mean one thing that I am a little weak on despite one out of yours I just I am a lubricant anemic programming's so I think I'm cheese No so Valley ignore the comment it's not me try to be mean I'm just trying to be trying to figure out this one a little bit on these things yeah I would say dimensional analysis and it's go to 500 so I could find do stuff that's n square maybe n Square log and if I want to do it that but what does it mean to burst a balloon how can you do so as a DP poem I would think about how to describe let's say I burst one balloon how do I at least I guess n khabees zero so that kind of force swings in the loop a little bit oh yeah how do I describe the subproblems in that case right and if I have n square away how to describe that tiny like how do you solve it right what are the if I burst this if I first have random if I burst this if I first have random number in the middle can I solve left number in the middle can I solve left and right I don't know it might be that and right I don't know it might be that it is greedy to be honest it's just that it is greedy to be honest it's just that I'm just trying to think about in the DP I'm just trying to think about in the DP way am i talking on and try to not look way am i talking on and try to not look at the comments or spoilers but actually at the comments or spoilers but actually I mean well that's tough zero right it I mean well that's tough zero right it always makes sense to pop to zero first always makes sense to pop to zero first wait because you get no coin for me but wait because you get no coin for me but it prevents future maybe it is time it prevents future maybe it is time thank you yeah then you kind of figure out relaxing it's like a weird and I say relax I meant like graph theory a relaxing like you know it's almost like a weird ice tray type problem maybe is it clear hmm well because well you is it clear hmm well because well you definitely wanna get rid of all the definitely wanna get rid of all the zeros so we could that we filled out the zeros so we could that we filled out the zeros because obviously the coins are zeros because obviously the coins are zero but but also so dad like future zero but but also so dad like future because you know like given zero and an because you know like given zero and an adjacent number which is any number you adjacent number which is any number you want to pop to zero for us so that when want to pop to zero for us so that when you popped a real number later like you you popped a real number later like you know you get coins from it I think know you get coins from it I think that's fair mm-hmm this doesn't look that's fair mm-hmm this doesn't look like greedy though I feel like this is a like greedy though I feel like this is a big number now that's 15 but this is 40 big number now that's 15 but this is 40 so that would be more your choice of its so that would be more your choice of its greeting mmm-hmm I mean I think there is like a weird maybe enter the fourth dynamic or something like that DP but that clearly too slow so I Oh hmm what could I maybe missed is that I mean I looked at their hmm does that mean anything well it hmm does that mean anything well it means you it's hard you can go over four means you it's hard you can go over four I guess maybe that means one thing maybe I guess maybe that means one thing maybe there's also some kind of state that you there's also some kind of state that you can keep track me I mean it may be greedy is the right me I mean it may be greedy is the right word wrong word word wrong word sorry but it's like almost like a sorry but it's like almost like a comparison I mean like okay first thing comparison I mean like okay first thing one like there's a function that's like one like there's a function that's like second order or something like that like second order or something like that like like the cost function of the greedy like the cost function of the greedy isn't necessary just bursting it but isn't necessary just bursting it but it's like there's some or like some it's like there's some or like some weird function on first thing dis before weird function on first thing dis before word cursing the neighbor or something word cursing the neighbor or something like that and there's some function on like that and there's some function on that maybe and then once you do that you that maybe and then once you do that you can do a sort of a greedy maybe let's can do a sort of a greedy maybe let's first think this means you got fifteen first think this means you got fifteen but it wasn't means you're five your but it wasn't means you're five your cost function what does it mean suppose cost function what does it mean suppose this way first thing the one means you this way first thing the one means you have in the future in somewhere three have in the future in somewhere three times five more I do like that's kind of I I'm not gonna I like this problem per se but not as an interview probably not but well maybe when I see the solution but uh so I would like to you know you know smallest means well uh hmm why would you not pop five instead well but like in this case right now pop two three then why how do we choose the five I'm listening we'll try to work out this example just to kind of see if I could work on an intuition nothing like this you know you popped it three you get the team answers well you know that's just a problem what we ate but then you have me down to minus 15 times 8 is 120 and then you can oh you can pop to 8 so you pop the edge you get 40 and you get 305 now but what does it mean to parka cologne because I think well you had some you had some coin but so if you pop five the cost function is so then you put the three and eight together whether eight cut the 5/8 then it went from so again cut the 5/8 then it went from so again eight times five minus three just prop eight times five minus three just prop that and then you have minus 5 plus 3 that and then you have minus 5 plus 3 times 5 20 three months what what's that times 5 20 three months what what's that this is negative 16 9 to the stake of this is negative 16 9 to the stake of that theory that cost function is 113 that theory that cost function is 113 maybe it's not good enough only to do maybe it's not good enough only to do greedy in this case are you parked 3 so greedy in this case are you parked 3 so 5 goes from 3 to 100 that's it I guess it's like a weird sorting issue I guess it's like a weird sorting issue ami thing but thanks ami thing but thanks back to staying up posting wet hope I back to staying up posting wet hope I see y'all next week guy today trying to see y'all next week guy today trying to a mini marathon so that's why I've been a mini marathon so that's why I've been longer than usual usually it's already longer than usual usually it's already 120 here - so a.m. so it's not like you 120 here - so a.m. so it's not like you know good yeah and I seen y'all thanks know good yeah and I seen y'all thanks for their support for their support okay so bye pop - eight if five goes okay so bye pop - eight if five goes from 8 to 1 so that's you go to negative from 8 to 1 so that's you go to negative 5 so this is 5 5 so this is 5 okay I mean I guess this kind of fits okay I mean I guess this kind of fits for this but but like that does not it's for this but but like that does not it's not convincing enough for me boy Eric not convincing enough for me boy Eric okay actually bite down coach I don't okay actually bite down coach I don't have to do it manually okay that's popping and changing - it's for testing just for intuition so it's for testing just for intuition so okay gonna be righteous yeah I don't know how long just bought my ticket because this is one of those oops and let's figure out the Delta of this which is some like weird cost function I'm trying to hear when I pop five it's I'm trying to hear when I pop five it's calculated while your left has a delta calculated while your left has a delta from your number two okay which I couldn't times make I even need to go too deep this is just confusing you mister smelling like let's just look Wow people overwhelmingly like this one Wow people overwhelmingly like this one so maybe I'm missing something obvious negative seven don't think that negative seven don't think that convinces me of anything convinces me of anything no ifs no buts this is the longest bit no ifs no buts this is the longest bit but in this case this is the highest so but in this case this is the highest so doesn't make this is like delete doesn't make this is like delete coercion of one boy well and then your coercion of one boy well and then your last round last round you always know like wait waiting game you always know like wait waiting game with something like one more turn and with something like one more turn and then next thing you know your last turn then next thing you know your last turn takes like two hours this is what it takes like two hours this is what it feels like feels like [Music] one of this like a heuristic to kind of one of this like a heuristic to kind of do it is some sort of so I'm not talking do it is some sort of so I'm not talking about I'm talking for many hours about I'm talking for many hours straight straight I guess okay I don't know if there's an easy way to once you merge something it's over that once you merge something it's over that and your problems or your like your cell and your problems or your like your cell phones you need to know where it began hmmm I think there's a dynamic programming solution but I don't think it sends you can enter the fifth or it sends you can enter the fifth or something when I do have a code a number one when I do have a code a number one solution but seems like maybe not maybe solution but seems like maybe not maybe it's a query with a odd course function pop a balloon I'm still thinking about pop a balloon I'm still thinking about in terms of subproblems maybe that's the in terms of subproblems maybe that's the wrong way to think about it maybe this wrong way to think about it maybe this is kind of a figure out the cost is kind of a figure out the cost function well like a true course of function well like a true course of popping a balloon which is not just a popping a balloon which is not just a number of coins but but it means a lot number of coins but but it means a lot of implications that I'm not doing a of implications that I'm not doing a good job of thinking about which is what good job of thinking about which is what I was kind of trying to see by you know I was kind of trying to see by you know the shape of these things all right the shape of these things all right let's go a little bit please case okay let's go a little bit please case okay okay just one balloon you pop okay okay just one balloon you pop okay that's there's two balloons I guess this actually doesn't matter what order is up like what the answer still let me just like what the answer still let me just say yeah that's yeah that's no that's say yeah that's yeah that's no that's not true not true two balloons you have to wonder lower two balloons you have to wonder lower one first yeah you cheated of it thank you - it's my 120 plus 24 plus a [Music] maybe the greedy this way the greedy is popping the smallest balloon until got three balloons and then maybe after two three balloons you just proof force the race because as long as you two really biggest number maybe everything in between doesn't really know like but you choose the lowest well you have three numbers you pop the middle number some weird thing like that maybe maybe it is just greedy because this earliest you pop the smallest number then your numbers get bigger together I think I was just over generalizing to and he goes three case and over thank you free case let me try dad and then then we tried and able to say okay and with dad you could actually do which record I sleep but yeah I'm not going to I'm just going to do it we love it I'm just going to fold up to calculate them and just Chris I think it's like easy to call and I think for now I'm just in my testing I mean yeah nicely on the edge case I I mean yeah nicely on the edge case I think it's around the edge maybe do you think it's around the edge maybe do you pop a long one that I wanna edge yeah pop a long one that I wanna edge yeah maybe you do yeah maybe well so if that's the case I mean I'll explain why you're about this far maybe maybe I could moduli such a function okay maybe right this is a little late [Music] make sure hot water is cold right here I really need to down I need this - yeah I really need to down I need this - yeah I need this for calculating the coins I need this for calculating the coins final actually just now that's tough final actually just now that's tough love it I don't know what I'm thinking love it I don't know what I'm thinking it's just Glade in him then maybe this it's just Glade in him then maybe this is my task alarm then okay so we what we is my task alarm then okay so we what we said was we would take the smallest said was we would take the smallest number I started implementing stuff that number I started implementing stuff that is what now I was a so that's not great mmm that's less than 100 so that there should always be something okay there should always be something okay and then now we wash that number cause I guess this is if it's queer don't we [Music] No okay now that we got it down to boy we okay now that we got it down to boy we get them get them well actually we want to get rid of them well actually we want to get rid of them we still want to get uh we still want to we still want to get uh we still want to get rid of all the zeros even before get rid of all the zeros even before word we okay no it's a quaint way to word we okay no it's a quaint way to filter yeah okay now we should get numbers now let okay it compiles wish it did something okay it compiles wish it did something that uh unit I was you into leaving that uh unit I was you into leaving because let me just any stupid so I because let me just any stupid so I guess in one elevation of the loop by guess in one elevation of the loop by the way you add a bunch more answers okay doing this way it gets interesting maybe but we already wasted a zero so this wouldn't happen if okay so there should be no zeros and the remaining answers then okay so we just maybe do a case yeah so you want a meadow and in a smallest number and and bigger sample I don't know this is too greedy maybe I don't know this is too greedy maybe I'm going some places and that's one the I'm going some places and that's one the numbers are zero now we only we moved on numbers are zero now we only we moved on a server so they shouldn't be there a server so they shouldn't be there was it a smaller number first okay well you need to hope the numbers will give you the same some the same whatever and then smaller of the two numbers not the bigger of the two numbers that's the point of popping the small one but there are other cases because I've been moving a zero so if you have two numbers well a scimitar here which is we yeah okay if you have two numbers and you practice and mr. Adams take a number twice yeah and mr. Adams take a number twice yeah and just one they just pop it three and just one they just pop it three honest not convinced at all about the honest not convinced at all about the solution is very happy but yeah well I solution is very happy but yeah well I guess it has to be less than 100 but guess it has to be less than 100 but yeah also it's not the right answer I yeah also it's not the right answer I don't know what I'm gonna do I'm just don't know what I'm gonna do I'm just gonna go find your stuff oh man so gonna go find your stuff oh man so greediest doesn't seem like it's right greediest doesn't seem like it's right then alright so this is kind of what we then alright so this is kind of what we talked about with no never bad idea then talked about with no never bad idea then what do I do what do I do well don't break it down to easier well don't break it down to easier components to understood and then see components to understood and then see where it goes wrong okay would you pop where it goes wrong okay would you pop the - let me print even text pads I'm the - let me print even text pads I'm gonna like keep track so I mean here my gonna like keep track so I mean here my strategy is to pop the - maybe that's strategy is to pop the - maybe that's not what no that's not right well how should I well that's even like it keep going yeah well that's even like it keep going yeah and then after 15 sir it's this way at and then after 15 sir it's this way at least okay so three case maybe it's like just and Zaheer is not to pop it Wow hmm well and Zaheer is not to pop it Wow hmm well one dirtiness should be an endpoint one dirtiness should be an endpoint i-best I don't actually but it shouldn't i-best I don't actually but it shouldn't matter matter so what maybe I think I was some other so what maybe I think I was some other strategy which is to take the biggest strategy which is to take the biggest number I mean I think what I'm thinking number I mean I think what I'm thinking of is take the biggest number or maybe of is take the biggest number or maybe went blue for us because every what I notice here is that you kind of actually want to pick its number in the middle right maybe he says climbing to keep his huge and then all climbing to keep his huge and then all the other numbers are just in between the other numbers are just in between and kind of other subproblems okay given given two numbers how do I merge older intermediate stuff with time as the border may be tightest the dynamic programming just greedy work I said I wrote a lot of code but I do think I am getting a little bit of insight of Mabel to whitewash no query maybe maybe not maybe making some progress anyway we definitely test to get rid of the zeros I think it does nothing for us except will give us negative score I'm not naked ever but you've got to be negative I think this point is what we have to do I think there this part is also should be mostly right because you know the only number of cases but at least maybe smaller about this greedy person a we just never want to get maybe I'd even the biggest number yet what is the biggest middle number or the biggest middle number or the best number for the middle can you do it that way well it's a path dependent I guess not because you always punch stuff around it but it like it's still a case where you want to pop like a couple of 99 in the middle now because then you cuz that would be one of your other conditions and then you have to huh thanks for the tip let me think man huh thanks for the tip let me think man uh uh think about this a lot already think about this a lot already oh yeah I mean I've oh yeah I mean I've yeah I was I think I was like yeah yeah I was I think I was like yeah getting to thinking about it thanks getting to thinking about it thanks again for the tips I'm squirrel pox I again for the tips I'm squirrel pox I mean that's why I was kind of thinking mean that's why I was kind of thinking about like what does it mean for you a about like what does it mean for you a hundred I'm like well like like you were hundred I'm like well like like you were saying what if that's already attached saying what if that's already attached to last bubble like I said it's never to last bubble like I said it's never greedy but untested ice bubble what does greedy but untested ice bubble what does that mean well how do I restructure the that mean well how do I restructure the prom to like what I want to intermediate prom to like what I want to intermediate perhaps in between like you know the perhaps in between like you know the left and the right okay I think I see left and the right okay I think I see what you mean actually and I think what you mean actually and I think that's how you structured a time that's how you structured a time programming and it I still end cute girl programming and it I still end cute girl maybe yeah okay maybe yeah okay I have blue cop in place it's go just in I have blue cop in place it's go just in case just for my friends but yeah I case just for my friends but yeah I think I'm gonna blame it on the sleep because that because yeah I think the key insight and I was kind of if I'd like I don't know you might miss the point where I said what if it's good but and I try to flooring it but because I was trying to figure out how to man I chef Cantus fast in it about rigor how to kind of separate the subproblems and but I was thinking too much about solving the problem first or like first to pop where you're popping the balloon mass then is a clear separation because by definition you're popping up on a mass then all your left will have to you know yeah okay if that's n cube I mean I'm waving a little bit but I think I have the idea you might had some ear I'll explain it after if I get it right but now that you're sort of snide and cuz I shall find out faster that's the that's just negative one is a place on that's just negative one is a place on up now that's why they will practice never about I'm still 2 n minus 1 [Music] now we have two palpable doing so it now we have two palpable doing so it isn't okay oh my toilets right I mean this is too white or you have two hours to write wearing that okay so let's say you picked iPhone into pop and I left anyway [Music] [Music] it's something like cocktail of nine it's something like cocktail of nine minus one times but that's the main cost minus one times but that's the main cost not to matter why you I guess I could just store another thing I guess I could just store another thing I just didn't store another thing yeah I just didn't store another thing yeah okay maybe dollars to it missing key okay maybe dollars to it missing key down because to stop the best optimal things because to stop the best optimal things might not be so if we take this as your might not be so if we take this as your last number - uh - put into pop then you last number - uh - put into pop then you means you pop all your left balloon means you pop all your left balloon except of one aluminum trying to figure except of one aluminum trying to figure out what does that mean maybe laughs white is not the right you know a start on this a little bit you know a start on this a little bit earlier mr. place yeah of course mr. go-to well this is the best name of coins you get is the left to right Plus what you get for getting this one which how do you get to test you maybe need to take a look right depending on your second I don't like your pass on the left and can and cute anything in here that would can and cute anything in here that would take way too long so you can reduce it take way too long so you can reduce it to a hundred maybe I could abuse the to a hundred maybe I could abuse the fact that it's just a hundred your intent is like 10,000 times fifty hundred times 5/1 or 510 five hundred today it's not like that's like if I'm a today it's not like that's like if I'm a game I gotta find this well maybe this game I gotta find this well maybe this is one case where I actually learned is one case where I actually learned something and I know the formation that goes at this but then it requires you to add a dimension which I don't think we could afford and also just a dimension here man is to a Oh mmm think that so that's why I was kind like I'm close no well if deeply is that like I'm close no well if deeply is that the DP is the reason then you know the DP is the reason then you know that's how I would think about it great that's how I would think about it great well at least memoization maybe there's well at least memoization maybe there's a queen would think about it like this a queen would think about it like this is also standard it yeah I'm just trying is also standard it yeah I'm just trying to figure out how to calculate the score to figure out how to calculate the score right I mean I think I have century this right I mean I think I have century this is the laughs applause this is the right is the laughs applause this is the right support and then I'm just trying to support and then I'm just trying to figure out the cause of or the score of figure out the cause of or the score of you well of this one how do you get to you well of this one how do you get to left in there right like how do you left in there right like how do you choose - I like there's smallest index choose - I like there's smallest index to get to score am I doing this weird to get to score am I doing this weird and it's time for me to do some learning hmm I'm a guy oh I guess have to first hmm I'm a guy oh I guess have to first love one you Fran chilly so that means love one you Fran chilly so that means Oh sometime I guess leftist implicitly Oh sometime I guess leftist implicitly to last one you ghosting so I guess the to last one you ghosting so I guess the score is I think I made this ago well so score is I think I made this ago well so normally everything in between and you normally everything in between and you do two thing last on the on the border we don't have to maybe read about this a little bit let me let me point around this and in the car thing right now which is my hunt explains how mixed up maybe I'd formated my deep here and over I rap too you have to two pounds on the I rap too you have to two pounds on the other side that's fine but thanks thanks other side that's fine but thanks thanks what the hell yeah let's - later today I'm just good I call my intuition is an open off on this one well I just yeah that was very close but maybe not I don't think this function was kind of anti trouble with I think if I don't have to collect basic I have no still no hmm well is it because well I see disappoint well I guess I don't eSport no there's only one number how its pain what what am i doing uh sorry fights I'm sure it's just later good night there we go my my thing is just we're all together thanks for the destroyer oh nice little Dino soaked wet ground made a comment okay cool okay well is that right it is I need a awesome one more case maybe sorry I'm a little slow that's all it's a I'm on my seventh hour of decoding John and twitch so that's my excuse for being a little slow in time but it's the longest I've done but yeah I'm an integrator you need to do stuff for like five straight hours so five six straight hours so I don't think that's no reason to excuse well hopefully maybe there's slightly easier time based case I probably have an off by one somewhere I just don't like this is woefully right maybe I mean except for maybe one of the cases I bought that could wait - Mike the one yeah they feed you and stuff - just let me just think I couldn't just let me just think I couldn't register them well one number is too far okay maybe I double karna this actually because I just already factors that in so maybe maybe no that's not true you know this maybe no that's not true you know this is flowing there's two numbers so I is flowing there's two numbers so I don't know okay this is not much just a don't know okay this is not much just a lot so maybe that's a business right lot so maybe that's a business right I must have double counted something I mean I mean where did this all right now I cite the left size one because [Music] [Music] yeah I agree yeah I agree that's why I've been trying to do a lot that's why I've been trying to do a lot of them but uh today it's just been of them but uh today it's just been exhausting I'll just say mix right let's get some I'll just say mix right let's get some of these man of these man I guess everyone needs well I get that I guess everyone needs well I get that off so yes that's good it means that off so yes that's good it means that somebody just when you walk it's off by somebody just when you walk it's off by 90 there's my two number ones all right 90 there's my two number ones all right why is my green check that assumption oh man oh man I forgot that I changed sorry it's very late I've got that like you're hacking face then take one like you're hacking face then take one price and you know they'd have to change price and you know they'd have to change another crisis okay it's still one thing another crisis okay it's still one thing but it's it's more right which is good but it's it's more right which is good enough for me enough for me well not good enough for me yet but good well not good enough for me yet but good enough for now yeah i mean what you enough for now yeah i mean what you don't well you don't know is I'm just don't well you don't know is I'm just actually delirious what I had too much actually delirious what I had too much caffeine so I'm really into you caffeine so I'm really into you you need to use the restroom at a time blah it's only like six possibilities I blah it's only like six possibilities I just have a type of plan here I don't know I want to start this way I don't know I want to start this way right that know that I I think I try to wash it and that left me to do things in a way that I'm not usually deeply I'm the only screen up just called a I'm the only screen up just called a little bit no I think you should still little bit no I think you should still be the same thing but at least it's be the same thing but at least it's easier to read okay okay I am struggling with this bond right now [Music] what does it mean well we're not able to avoid them is your number is going to jump jump I think maybe you have to do maybe I I think maybe you have to do maybe I don't pop the last balloon well no why don't pop the last balloon well no why because we tried to do it to see when because we tried to do it to see when didn't change the answer sir sure did didn't change the answer sir sure did change yeah we didn't know so I mean I change yeah we didn't know so I mean I don't know justice white but it did not don't know justice white but it did not change the answer so we pop you guys change the answer so we pop you guys should manually mantissa and figure should manually mantissa and figure out what but uh you pop this one so [Music] [Music] yeah you type this and if no dish mm-hmm yeah you type this and if no dish mm-hmm I'm quite I think that's right I'm quite I think that's right oh my god but that means you parties you oh my god but that means you parties you if we close on 32 almost not to like take care of zeros at almost not to like take care of zeros at some point I think I mentioned that some point I think I mentioned that earlier and I think it's still useful earlier and I think it's still useful bit yeah maybe dish it's not like that except forgot to hand out education yeah okay let me do something okay let's yeah okay let me do something okay let's get back up on the servos for this and then maybe we just created porn trees maybe that maybe that simplifies our so much cases it did something I think I didn't do this for yeah so this okay we're on the right track again okay we're on the right track again maybe maybe no no no no aah maybe maybe no no no no aah and that coin I think this one has to so and that coin I think this one has to so you pop this you get the court cost just you pop this you get the court cost just because I'm used to optimization but because I'm used to optimization but this is actually just going to something this is actually just going to something that I like the subproblems okay well we don't need dry stone it is now that I in this simplified apartment every move in this simplified apartment every move it took place where I can do what I it took place where I can do what I don't know oh Jesus how does that give don't know oh Jesus how does that give me me I don't know what I mean I don't know what I mean it works but if you ask me if I believe it works but if you ask me if I believe in it I don't think I do in it I don't think I do that's my list of answers I thought that's my list of answers I thought question why not question why not whatever fun fun people okay okay well whatever fun fun people okay okay well if I don't terminate early uh yes like if I don't terminate early uh yes like oh yeah I still don't know if I won somewhere that's fine oh no am i doing something funky because I can definitely be less [Music] I think this is just wow that's why I [Music] know you want that so maybe it's right but do I use end anyway what's hoping I mean I got one little closer but also maybe no closer to death what is this negative thing I mean definitely shouldn't have any many girls how do I even get negatives in here amazing processing random Wembley I mean it's probably just that that is passing random memory so like like it wasn't our bounce I didn't get check somewhere but more likely okay this actually seems more likely but it's that's more likely than an overflow because all these should be integers or like and they're just less than 100 even and I said that I don't get it because this should be at most one or at least one and at most n minus 1 then UN so of course oh wait England's - to make my restaurant ok let's try that you know cuz minus one is the last pound so and mine is just one with two one at the border ok ok yes [Music] that's mighty practice with dynamic all right definitely need this because I all right definitely need this because I forgot to tell too soon so you can't forgot to tell too soon so you can't just take gnomes nothing I have enough just take gnomes nothing I have enough to look at us upon days I was so close I felt like I got that one other enzyme right okay see whatever should not be your thing so let's see yep two numbers love more than to what I yep two numbers love more than to what I do in that case oh because I just never do in that case oh because I just never meant order things I did too okay I meant order things I did too okay I guess other stuff I did too [Music] long time ago and I've been have been struggling my turn off by once maybe dynamic poor grandpa just not the way to cap off a seven and a half hour stream once again thanks for the hint yeah - once again thanks for the hint yeah - callbacks I don't know I want to say I callbacks I don't know I want to say I would have gone there eventually but would have gone there eventually but knowing today oh maybe that's not true knowing today oh maybe that's not true Ivan oh yeah okay yeah just y'all know Ivan oh yeah okay yeah just y'all know you're too tired to play em even more you're too tired to play em even more test cases okay cool well I'm really test cases okay cool well I'm really slow - but you've an Ncube tickle only slow - but you've an Ncube tickle only 16 millisecond which was actually 16 millisecond which was actually surprising maybe I don't know why maybe surprising maybe I don't know why maybe the test cases are no Lex I think yeah the test cases are no Lex I think yeah first of all yeah I mean post-mortem a first of all yeah I mean post-mortem a retro on how I saw the farm I definitely retro on how I saw the farm I definitely they try to I'm having a general you I they try to I'm having a general you I don't don't I could have obviously skipped agreed I could have obviously skipped agreed yeah but I couldn't come up very quick yeah but I couldn't come up very quick each case for greedy so I was tryna and each case for greedy so I was tryna and he's implemented to kind of get he's implemented to kind of get intuition about it I think for whatever intuition about it I think for whatever reason I just didn't racialized a reason I just didn't racialized a dynamic program fast enough I also I dynamic program fast enough I also I don't know I think I struck a little bit don't know I think I struck a little bit with I took and Cuba below too slow for with I took and Cuba below too slow for n is equal to 500 maybe I got it to my n is equal to 500 maybe I got it to my math a little better two cubed is 125 math a little better two cubed is 125 million maybe that's fast enough yeah million maybe that's fast enough yeah maybe my internal clock has to be a maybe my internal clock has to be a little tuned for it yeah exactly and I little tuned for it yeah exactly and I was doing it forward I think at some was doing it forward I think at some point I did cut when after I did the point I did cut when after I did the greedy thing I'm like greedy thing I'm like maybe the greedy thing taught me to look maybe the greedy thing taught me to look up things to think about it in terms of up things to think about it in terms of what happens if I kept this balloon what happens if I kept this balloon until the last balloon and that kept me until the last balloon and that kept me and then that in a weird may be and then that in a weird may be unnecessary but a long roundabout way unnecessary but a long roundabout way allow me to kind of think about dynamic allow me to kind of think about dynamic programming again where that was the programming again where that was the last balloon to pop and that helped me last balloon to pop and that helped me have a separation of bound left and have a separation of bound left and right but I think so one thing that I right but I think so one thing that I did want to point now a little bit is in did want to point now a little bit is in my obviously I was ahead help them and my obviously I was ahead help them and once callbacks for which I'm thankful once callbacks for which I'm thankful which you know unfortunately you know which you know unfortunately you know I'm on the tracks it's not gonna be at I'm on the tracks it's not gonna be at my interview side ever needed to be able my interview side ever needed to be able to do this by myself like you know a to do this by myself like you know a little you know maybe was it go air pod little you know maybe was it go air pod cheating is Rises a friend no but uh so cheating is Rises a friend no but uh so I didn't well I think I didn't formally I didn't well I think I didn't formally I mean I think something that I I mean I think something that I definitely did a little bit bad on is definitely did a little bit bad on is well one is I didn't float out to things well one is I didn't float out to things and we set up the problems and okay I and we set up the problems and okay I chef created these wars a little bit chef created these wars a little bit earlier just to kind of so that I feel earlier just to kind of so that I feel each cases because I was doing weird each cases because I was doing weird things that we sell but also yeah I mean things that we sell but also yeah I mean I forgot to get a better sense of I mean I forgot to get a better sense of I mean and yeah if you watch me kid I don't and yeah if you watch me kid I don't know how carefully because I kind of did know how carefully because I kind of did this phone and there for a bit but if this phone and there for a bit but if you catch me on the stream I I set up you catch me on the stream I I set up most of this immediately and some guys most of this immediately and some guys fight you know just one experience but fight you know just one experience but that also kind of worked against me a that also kind of worked against me a little bit on this problem because I little bit on this problem because I thought I was very close to the end when thought I was very close to the end when I didn't have a clear formation in my I didn't have a clear formation in my head which led to me having weird like a head which led to me having weird like a weird ish off by once under under to weird ish off by once under under to subproblems and also the cost because I subproblems and also the cost because I was using left and right because I was was using left and right because I was just like in my head I was like fudging just like in my head I was like fudging I was like yeah I maybe I'll get it if I I was like yeah I maybe I'll get it if I just kind of get it just kind of get it and sometimes it works but in this case and sometimes it works but in this case I kind of paid a price for it but if I I kind of paid a price for it but if I had kind of really step back and really had kind of really step back and really formally but what this function means formally but what this function means what does it mean to calculate left and what does it mean to calculate left and right right and excuse me and I think once I did and excuse me and I think once I did that which was to which which is the the that which was to which which is the the best cost that you can given that you best cost that you can given that you populate one of them or you popped one populate one of them or you popped one of the balloons between left and right of the balloons between left and right that's the and even now I'm sure going a that's the and even now I'm sure going a little bit to be frank but that's just little bit to be frank but that's just the best order the maximum number of the best order the maximum number of coins that you can collect popping left coins that you can collect popping left and right laughs yeah yeah III think I and right laughs yeah yeah III think I struggle a little bit with kind of you struggle a little bit with kind of you know and I guess to that point and I know and I guess to that point and I kind of played around it with a little kind of played around it with a little bit well you said well what am i singing bit well you said well what am i singing I'm singing oh it's still so I think I'm singing oh it's still so I think sorry let me get it together in my head sorry let me get it together in my head so I could kind of formulate this sub so I could kind of formulate this sub problem a little better I mean this up problem a little better I mean this up for me or you know which is the part of for me or you know which is the part of just recursion yes yeah the Mexico or the max number of coins between yeah the Mexico is that of from within that range where where the Mexico is popping a balloon right well glass to be honest I'm not convincing glass to be honest I'm not convincing myself either a little bit maybe I'd to myself either a little bit maybe I'd to think about it but like you pop a think about it but like you pop a balloon under well and in this case if balloon under well and in this case if we pop the leftmost button first then again you know you pop I'm sorry I do lass so if you pop the leftmost button last then that means that everything from I'm saying is really wrong that's for example is equal to left meaning you pop the leftmost but doing glass it means that you can only have two borders which is y plus one and that was one which you know is really default case it's just edges and the same in the right and in the middle of any of those buttons last that means yeah I'm struggling a little bit yeah I think the struggle for me like and you know this is like the setup of this poem and they're not many different type different types of setups with dynamic programming so like I I have all this set up correctly I think it's just a deformation which determines the cost function changed a little bit you saw me struggling a little bit on thinking that from left to right this you also need to know the maximum balloon death within that range but that's not true because all the balloons already pops or your add so you're assuming that the last balloon that popped over there you don't need to return the balloon that was last part because you are popped for the cost function which is here because everything in between is already popped and out that was the part that I was struggling with a little bit but uh I think as a result I think one thing that I am trying to figure out how to do better about is yeah I mean I guess I solved this problem a little bit and I guess I know how to solve this particular problem if I see it again but what I need to do better is figure out well what am i or how am i learning from this and formally this problem in a way that if I see you know yeah a similar problem I could solve it way much better yeah maybe I chopped it up to a bad night Oh late night but it's still I wish I could figure out a sound a little bit better cuz Joey popped all the balloons from left to right and all your left and that's cut why this one doesn't have any you know cause of one of them the kicker is because you were popped or decrements inside you're left with left of that range and right of whatever that range is and that's what this thing is I mean we have one balloon enough along with your ranges one then Yugi you just pop that and you get to immediate borders I think I kind of understand this form but I think one thing I'm also just try to figure out in terms of learning is yeah how do kind of clearly formulators and I think thinking back I kind of was one step away from thinking it correctly initially where I was like okay because I think what I was thinking about sausage-like iterating pivots or their sub pivots on the left and on your way but but I wasn't thinking well enough and which is why I talked about like the cost Bing and not enough but I think my sub problems were a little off in that I still worried about the numbers to pop but in that case or the last button to pop in that case my my sub problems were wrong anyway but I was just kind of doing it all happened I think that's what I would say that's what the pattern-matching buys you it is that or like from being familiar with GT coupe arms is that you get so good at kind of writing these templates but you still have to you know understand the problem to really solve it and of course again thanks and blacks on you know walking me through it a | 2024-03-24 10:15:14 | 312 | 312. Burst Balloons (Leetcode Hard) (Updated Video in Description/Comments) |
|
eXcfiIHMJec | hello everyone so in this video let us talk about a problem from lead code the talk about a problem from lead code the problem name is number of boomerangs so problem name is number of boomerangs so you are given n points in the plane that you are given n points in the plane that are all distinct where the point is are all distinct where the point is denoted by x of x and y of y a boomerang denoted by x of x and y of y a boomerang is a tuple of points i j and k that you is a tuple of points i j and k that you have to find out such that a distance have to find out such that a distance between i and j equals the distance between i and j equals the distance between i and k you have to find out between i and k you have to find out different type of tuples that can be different type of tuples that can be formed the order of the tuples also formed the order of the tuples also matter so let's say that you have three matter so let's say that you have three point zero comma zero one comma zero two point zero comma zero one comma zero two comma zero comma zero so let us draw it out let's say you have so let us draw it out let's say you have this as the number plane and this is this as the number plane and this is zero comma zero okay the next one is one zero comma zero okay the next one is one comma zero so one comma zero and the comma zero so one comma zero and the next one is two comma this is two comma next one is two comma this is two comma zero zero number of boomerangs so boomerangs is number of boomerangs so boomerangs is that you can form any that you can form any like you can find out any i j and k in like you can find out any i j and k in this plane such that this line is equal this plane such that this line is equal to this line to this line so what you can directly see is that if so what you can directly see is that if i just find out this as one of the i just find out this as one of the possible answers so this because it is zero so this length is one this length is one so this is one of the possible tuples also but you can see that this is also one of the tuples so going from left right or right to left so because the order matters so what they are trying to say is that one comma zero zero comma one and two comma zero as well as one comma zero two comma zero and zero comma zero so if you just find out a decimal i and j and i and k so i and i and j so this distance is one and this distance is one and this is one this now i can find out like all of the possible boba ranks or electropulse in this because what you can actually see is that the total length is up till 500. you can do like you can do of n square approach but not of n cube because that will be like time limit x here but you can do easily now what you can actually do is that for a boomerang like for a boomerang to form the best case scenario is like you just have to ensure that for a given point for a given point what is this length and what is this line so let's say we just take out three points let's say i k and k so for a fixed i if i just do a for loop for every ith element inside the area that we have for every i okay we just have to find out what are the total number of lengths that are equal okay and from all of those equal lengths you can form out the possible number of what you can say boomerangs so what you can actually do is let's say for every given eye for so i just find out from every point i i will find out this distance between every other point okay so let's say this point so for respect to this point there is one point here one point here so i just find out all the distance between every this point let's say this length is one this length is one this length is two this then this two then this three three and let's see one point that is three now with respect to this point how many boomerangs i can form with this as a center let's say if i take this is the boomerang this is the like a center point then i can form number of boomerangs with equal lengths only so this is one of the boomerang second form or this and this okay so what if let's say i have n lengths that are equal then for every ix length i can choose the other n minus one length okay so total number of boomerangs i can form is n into n minus one for a given point okay so what what eventually i have to do is that for every point you have to make a separate map of how many total lens that are equal with respect to this point and then finally when you have all the map you just iterate over all this map and find out how many total lines that are equal so let's say there are two lengths of length one that are equal so for this one i can form this is the boomerang and from this one i can form this at a boomerang because order matter now let's see if i have three lengths so if i have three lengths that are connected to this singular point how many total moving second form i can form this boomerang i can form this boomerang with the rest of this boomerang this boomerang which is probably this boomerang and this moving so for every ith point i have other n minus one point so for every n point i have other n minus one points which i can pair with total number of points i can form is this and then we just have to add all of those points for every ith point that we did over in this for loop and that's who runs so let us show and move down to the code part now so what we have done is that we have taken the total point of this whole array is n total number of boomerang second form is total and iterating over every ith point i will make a separate map and for that particular map what i'll do is that i will find out the distance between the is point and all the other points that we're treating over and stored inside this map okay what is whatever the distance now because the distance between two points is if you just want to find out distributing two points i know that you directly know the formula if this is x one y one this is x two y two distance between them is under root of let's say x1 minus x2 whole square plus y1 minus y2 whole square now because it's under root then and we are storing it in map how my total tuning occurrences are there then this will cause a problem because it is untrue but what we can actually do is because if we directly remove this under root also then also these will be unique values only because the distance will be unique so what instead of writing on this value when i just calculate out x 1 minus x 2 whole square plus minus y 1 minus 5 2 whole square because eventually we do not read the need actual distances we just need how many total distances are same okay so that so we we are eventually in this distance are only calculating out this like difference into like difference whole square okay for x and y not the undo part and then add those distances inside the map now we have the total number of distances that are same now for we again hit it over the map and then for any distance that is like if i have any acres greater than one okay then what i'll do is i will increment the total i into i minus one so if i have total occurring so let's say n so n into n minus one so total occurrences i dot second for every given point that is inside this map so i dot second into i to second minus one so it is n into n minus and into n minus 1 okay that is how we can get the total occurrences for a given point how many total number of pairs i can form that will be boomerangs and then situation so going to our diamond city what we have done is that we have done two for loops and for f like for this outer follower we also make a map also okay so it so we are already creating a new map so this this whole operation like inserting so it is n square login okay so n square and there's a login operation to insert inside the map also and that's so and then this is again in for you but the overall maximum which it is n square login and you can also like optimize the same mobility by making an ordered map also here but it i don't think so it does matter too much but yeah that's overall diversity for this problem as well thank you for watching till the end i will see you in the next | 2024-03-18 10:29:52 | 447 | 447. Number of Boomerangs | LEETCODE MEDIUM |
|
j9akOmURIEs | okay so back again the next problem we're gonna go with um yet another elite code medium so welcome i'll just give you one moment and we'll i'll just give you one moment and we'll check something yeah basically the last problem that we solved took us like half an hour didn't really need to take that much time but i got a little bit uncertain at some points so we'll try i'll try again uh the next question should i do as many problems as i can before 10 o'clock my time or just russians at 10 o'clock my time i should just say try to as many problems as i can if i want to go late i might go later if i want to go late i might go later who knows you know who knows you know or earlier whatever what have you let me or earlier whatever what have you let me uh let's get the next problem let's take a look at the next problem so it's uh maybe a minute or yeah okay so the next problem verified pre-order so the next problem verified pre-order sequence in a binary search tree sequence in a binary search tree let's see give an array of numbers verify whether it is the correct pre-order traversal sequence of a binary search tree you may assume each number in the sequence is unique consider the following binary search tree one two three five six five two six one three false five two one three six oh only using using only a constant oh only using using only a constant space complexity space complexity probably not i don't want to do it recursively which would not be i actually could you could i think you i actually could you could i think you could could um i think you can um so basically let's see pre-order so basically let's see pre-order [Music] [Music] pre-order traversal you pre-order traversal you actually don't know i don't know about actually don't know i don't know about this we'll just say leave that for now this we'll just say leave that for now so free or traverse i mean you could you would check you check the first in order to be a binder in order to be a in order to be a binder in order to be a pre-order traversal of a binary search they have certain properties i guess they have certain properties i guess i actually don't know i would do this i actually don't know i would do this even you know if we forget about this even you know if we forget about this this part this part um you have a left subtree or right subtree but you don't necessarily know where the so you want to verify the left subject but you don't even know where the right subtree is yet you only know where the right subtree is when the left subtree i guess ends so you would say all these numbers need to be smaller down the left sub left and then finally you have the end i and then finally you have the end i guess since i finally have a number guess since i finally have a number that's that's larger that's going to complete larger that's going to complete this first level here and the next this first level here and the next number that's larger number that's larger has got to be larger than this value i'd want to keep like a stack or something so five two one and then three it's so five two one and then three it's gotta be larger than the gotta be larger than the previous so this group of three you find previous so this group of three you find and then the next value and then the next value it's got to be larger than this one so six is greater than five three is greater than 2 i mean i guess you could do that kind of trying to figure out how we can do this trying to figure out how we can do this with constant space complexity with constant space complexity let's just try to solve it in general let's just try to solve it in general right in the first place right in the first place if we could solve it at all and then if we could solve it at all and then figure out how to do the constant space figure out how to do the constant space complexity so complexity so i would probably use a stack it's real i would probably use a stack it's real simple simple um keep pushing values from left to um keep pushing values from left to right onto the stack that are smaller right onto the stack that are smaller and then eventually uh excuse me you gotta compare that to the excuse me you gotta compare that to the previous value on the stack previous value on the stack um and pop the stack and then you see another value if it's now this next value could be smaller or larger right so if it's a basically the pre-order traversal you have a head node and then you have the tree split into two other pieces the left subtree in the right and in order for it to be a binary and in order for it to be a binary search tree search tree the left subtree has to be binary search the left subtree has to be binary search tree tree and the right subtree has to be binary and the right subtree has to be binary search tree and the left subtree needs search tree and the left subtree needs to be everything in the left sub tree to be everything in the left sub tree needs to be less than the head needs to be less than the head and everything the right subtree has to and everything the right subtree has to be greater than the head greater than or be greater than the head greater than or equal to equal to or just greater than say um what's tricky about this is basically as soon as you find from left to right that isn't smaller from left to right that isn't smaller base base pretty much pretty much pretty much what you want to do you want to find the split between the you want to find the split between the two subtrees two subtrees the left subtree in the right subtree the left subtree in the right subtree the head of the left subtree in the head the head of the left subtree in the head of the right subtree clearly you can just look from left to right until you find the first value that's larger than the head right that's got to be the right the excuse me because then you have this left subtree and then this right subtree and you can you can just do it recursively right the first value should be the head of the tree and then really the first value on the right side you know first value to the right that you find that's larger than this value it's got to be so here five would say the left subtree so here five would say the left subtree is two is two and the right subtree is six however and the right subtree is six however there's one and three being to the right there's one and three being to the right of five of five is not a possibility another way to verify this is uh the property is that for each value everything to the right there is a certain number of values that are smaller and then a certain number of values that are larger and all the values are larger yes the values that are smaller to the yes the values that are smaller to the values that are smaller values that are smaller block of values that are smaller and block of values that are smaller and then a distinct block of values that are then a distinct block of values that are larger larger and all the values are smaller or and all the values are smaller or smaller and all the values that are smaller and all the values that are larger or larger larger or larger and if you have any kind of discrepancy and if you have any kind of discrepancy in those two blocks then in those two blocks then [Music] [Music] for any any value then no no that's not for any any value then no no that's not true true it's like for one one and three everything to the right is just larger for two you have one thing though that's smaller to the now can you check that property directly now can you check that property directly without using any extra space without using any extra space because ideally what i would do is i because ideally what i would do is i would just i would just do a recursive would just i would just do a recursive solution let me see if i can if i can solution let me see if i can if i can solve that solve that or just resolve it recursively first so i'll explain what that would look okay we could even do pointers i mean yeah we'll just we're just doing i mean yeah we'll just we're just doing a hp a hp uh okay all right um f of okay okay all right um sure so what we want to do is interval equals pre-order 4 and x equals 4 and x equals this one x is less than pre-order dot this one x is less than pre-order dot size size increment x if increment x if pre-order of x pre-order of x is then uh okay if pre-order of x uh okay if pre-order of x is greater than the value is greater than the value then we break then we break and you return a x and you return a x and x b um first value that's greater than first value that's greater than and so you're actually going to recurse and so you're actually going to recurse on a plus one um up to x minus one and then x to b it's inclusive and uh i don't know about this one uh i don't know about this one i don't know this doesn't seem so let's see right here um oh yeah i keep forgetting i'm throwing f oh yeah i keep forgetting i'm throwing f here too this is basically recursive left side oh whoops let's throw just a bunch of random i don't think you have duplicates in a i don't think you have duplicates in a binary search tree binary search tree by the way it's also taking me a lot by the way it's also taking me a lot longer than i was expecting it to longer than i was expecting it to uh yeah 18 minutes it's been a pretty uh yeah 18 minutes it's been a pretty pretty good amount of time pretty good amount of time it's okay i guess you know all right how are we doing here false true everything else false false true everything else false false true false false one of these are false true false false one of these are true true all right yeah i didn't think the logic all right yeah i didn't think the logic i don't really even understand the logic i don't really even understand the logic that i have here that i have here so this one is true okay so at one point yeah so how do we how is this supposed to work is the if a yeah if a is equal to b obviously if a yeah if a is equal to b obviously that's that's that's just true by default uh if that's just true by default uh if b is less than a then it doesn't make b is less than a then it doesn't make sense and if a is greater than equal to sense and if a is greater than equal to it was off the edge now that actually may not be a problem um yeah that might be wrong um yeah that might be wrong um that never really should happen though i that never really should happen though i think think so we set so we set val the pre-order of a we set xc with a plus one to the next index and now we say okay um as long as x is less than the pre-order size we want to find if pre-order of x is greater than value that's going to break so we found the next um i guess spot to split our array of x yeah found this next value of x to split yeah found this next value of x to split the array the array it's pre-order of a a uh x equals a plus one all right when i find the first time all right when i find the first time where this is where x where this is where x occurs where this is greater right occurs where this is greater right now it could be that that never occurs um because the right subtree could just be because the right subtree could just be empty so actually you probably would return true here so wait so now here's the question if we then we're going to have truths when then we're going to have truths when things are false and false and things things are false and false and things are true hmm hmm why does this give us false on the why does this give us false on the bottom one like if we did we just did this case right that should be true but our right that should be true but our algorithm won't come up algorithm won't come up true yeah true yeah and why i actually want to say something like this uh that's interesting okay uh that's interesting okay this third one causes problems why is that so the algorithm is five find the first value that's larger so recurse here and recurse here and then it would say six first of all it's larger is eight and so you would record oh that's why you would recurse oh it's actually the other one that's oh it's actually the other one that's causing problems um um i guess my question is do you have a return ever returned false why do you return when do you return um right so here is you would say what do you recurse on if if the next is larger is larger there is no left subtree basically there is no left subtree basically [Music] [Music] if there is a left subtree if there is a if there is a left subtree if there is a right subtree right subtree you would recur so you just have to you would recur so you just have to check if there is or isn't a left or check if there is or isn't a left or right subtree right subtree that's kind of all i guess um yeah i don't i don't think this is correct this algorithm i don't think it doesn't make sense to me [Music] which is to say this is this is um the left tree subtree exists when and square that equal to zero right square that equal to zero right uh i don't know create another one uh i don't know create another one so yeah x so yeah x is the is the new right subtree's head and if that's right next to the previous which is val or a which is val or a um maybe let's put another way maybe let's put another way if x if x minus a plus one minus a plus one is greater than equal to one i think is greater than equal to one i think yeah that's what it's supposed to be x minus a this is you actually [Music] um um yeah this is very confusing there's a and then a plus one those are two numbers two indices it one minus zero plus one the number of numbers between three and seven seven minus three plus one is five three four five six seven that's if it's inclusive exclusive you subtract two that's why okay that's why i'm so confused yeah uh there's gonna be three really you'd say this is great that equal to three that's really the way i think about it there we go that's what we want to do okay yeah that's that's what we want alternatively we can yeah yeah that's me better do it this way that's why it's confusing or just the difference between these two numbers is greater than equal to one or greater than equal to two really yeah it's so i don't know i'm trying to think of a way that's like easy to understand what this means um let's do it this way should be at least three numbers between the between these two that's if um that's if um x is less than or equal to the index is less than or equal to pre-order.size yeah it's going to be less than this yeah it's going to be less than this this index this index um and then we finally say little red let's say it's true rhett and equals if right subtree and then return red there's no left subtree and there's no there's no left subtree and there's no right subtree right subtree that's just true yeah i think that's fine it'll return yeah i think that's fine it'll return true anyway okay all right what does this do now okay all right what does this do now still wrong always true still wrong always true um okay let's do it this way hmm hmm [Music] i was gonna say it's just always true i was gonna say it's just always true why is this this doesn't this doesn't why is this this doesn't this doesn't really make sense does it really make sense does it um no this doesn't the algorithm itself is like i don't even know what the i just want to just know that if the i just want to just know that if the left subtree left subtree is correct and the right subtree is is correct and the right subtree is correct then the whole tree's got to be correct then the whole tree's got to be correct there is there is a caveat here there is there is a caveat here um uh that got stuck well the tricky thing is the left every value in the left sub tree needs to be less than the key and everybody in the right subtree needs so you just need to take that previous value less than the key so you say if or i don't know just call it k-a-x or i don't know just call it k-a-x i can't call it k first greater than the key so this is greater than the value that's fine you're done but if it's not creating the value and it's greater than the key they would turn false i think that's the super confusing um i don't know what these sanity checks are supposed to do i don't know i really have no idea call us in max i guess initially i don't call us in max i guess initially i don't know now we're gonna call these the new keys values values don't know it doesn't seem right um so greater or less than the key i don't defense is the left or right i don't know i don't know yeah it's totally it's bunk it's not doesn't make any sense whole algorithm doesn't make any sense i want to use some kind of recursion but i really don't know all right so we got beat up by this question we weren't super speedy with our problem solving with this one we have to really how do you verify how do you verify that the uh array you're looking at satisfies the pre-order traversal of a binary search tree that's a good question i don't actually know that off offhand i have to think about that for a while like what's the case where it doesn't like what's the case where it doesn't work well work well pre-order traversal the first element is pre-order traversal the first element is the head of the tree some number of elements is the left subtree and then some number of elements to the right subtree could be zero all the values to the left need to be all the values to the left need to be smaller than the head smaller than the head all the values to the right on the right all the values to the right on the right have to be larger have to be larger so you can group it that way you could so you can group it that way you could say all right it'll take say all right it'll take all the smaller values put down the left all the smaller values put down the left side all the larger values put that on side all the larger values put that on the right side the right side and certainly if we recurse on the left and certainly if we recurse on the left side and recurse on the right side and side and recurse on the right side and it's true it's true on both sides now that's actually not on both sides now that's actually not enough enough that's where i'm getting into some that's where i'm getting into some trouble it's actually not true trouble it's actually not true to just recurse to the left or curse on to just recurse to the left or curse on the right because the right because not only does everything on the left not only does everything on the left side need to be smaller side need to be smaller than that head node and everything on than that head node and everything on the right side be larger than the head the right side be larger than the head node we're simply recursing on the left side and the right side does not guarantee if we just split on the first node on the right side that's larger that's not enough to guarantee right side is larger that's actually i right side is larger that's actually i think the problem it's not enough to think the problem it's not enough to guarantee that everything the right need guarantee that everything the right need to guarantee that everything to guarantee that everything past that point is also larger than the past that point is also larger than the head node interesting in other words just being a pre-order is not sufficient the left side could be is not sufficient the left side could be a pre-order verse on the right so i a pre-order verse on the right so i could be pre-order traversal however could be pre-order traversal however all the values on the right side may not all the values on the right side may not necessarily be larger than the head node necessarily be larger than the head node that you provided that you provided so you need an extra condition beyond so you need an extra condition beyond just being a pre-order traversal and just being a pre-order traversal and that's that's you just have to verify that everything you just have to verify that everything to the right is what you can do to the right is what you can do um yeah you just you could say um yeah you just you could say uh you could do it this way uh you could do it this way um just larger it's true and we'll say we don't need this key anymore it's not we don't need this key anymore it's not really necessary really necessary so yeah dude this we could do this way so yeah dude this we could do this way um i think we'll just just return false in these cases and we'll say and really this isn't this is actually less than or equal to b let's say i don't know v let's say i don't know v we'll call it v of g equals we'll call it v of g equals x so let's circle the v plus plus v x so let's circle the v plus plus v larger and equals larger and equals v greater than val v greater than val and really we have i don't really need this anymore excuse me but still giving me false huh which one is the one giving me problems this one the third one huh oh why is that let's focus on that one so we have two and three okay so we say val is pre-order of a is five x say plus one is two less than or equal increment x the order of x increment x the order of x greater than val break so x is here greater than val break so x is here which is which is zero one two three four zero one two three four right larger is true right larger is true x is four less than or equal to x is four less than or equal to b uh oh or we'll say jay and we'll say um and we'll say um that's probably why i miss misprogrammed that there was no there we go okay right correct it should be correct now um see if they have any test cases where let's go for it probably wrong in a bunch of test cases probably wrong in a bunch of test cases why empty test case should be um huh i feel like this should be true by default i'm so confused all these cases just return true oh oh pass all the test cases okay oh pass all the test cases okay interesting interesting it's too slow though i thought that it's too slow though i thought that might be the case um brother i'm getting my butt whooped by this problem no kidding it's a saturday right yeah okay yeah okay you can use a key so there's a better way to do this right um um this is an expensive way to solve this this is an expensive way to solve this problem the reason why this is so problem the reason why this is so expensive is that this takes um expensive is that this takes um quadratic time if you just take the list and you put it what's gonna happen is at every point you're gonna guarantee you're gonna have to run a loop to guarantee that everything to the right is larger than the head the head which if you sort the list from left to right that's very expensive it's true but it's very expensive ideally what you want to do is just when you recurse you have a key and you just check against that key that uh all the values are yeah the left subtree doesn't need to be yeah the left subtree doesn't need to be larger larger actually left substrate needs to be actually left substrate needs to be smaller but the left subtree is smaller but the left subtree is guaranteed to be smaller anyway guaranteed to be smaller anyway so i don't really care so we could do it so i don't really care so we could do it this way there's a clever way to do this or somewhat clever so actually it's in min is what you want and you say so if okay all these values need to be larger and left subtree is and left subtree is key the right subtree is actually going to give you the new and updated key all right try again i am struggling with this problem man i'm struggling yeah this is sorted in descending order this shouldn't be such a problem now we're almost descending 8 000 elements can i copy this um why don't you try one of the contest questions happening right now just for fun how's it going very single day how are we just going well yeah that's not a bad idea i could do yeah that's not a bad idea i could do that yeah sure that yeah sure let me let me see if i can finish this let me let me see if i can finish this one first though one first though yeah good call um yeah good call um [Music] [Music] okay 340 milliseconds well what's okay 340 milliseconds well what's in tle on this one how come i got the timeout here why well this is certainly faster but it's well this is certainly faster but it's not fast enough apparently not fast enough apparently it's kind of weird though because it's kind of weird though because this breaks pretty quickly pretty soon this breaks pretty quickly pretty soon checks left subtrees checks the right checks left subtrees checks the right subtree subtree i mean really in theory this shouldn't i mean really in theory this shouldn't be too expensive because um [Music] hmm hmm i it's too slow though why is it too slow i mean maybe there's things i can do to speed it up i'm wondering uh if it's still correct i wonder why it's taking so much time excuse me still tealing it does why interesting that that's sufficient as it is but um at least to solve the problem but how how do you do this faster it's not fast enough it's not fast enough [Music] [Music] i'll be blunt i really don't know i'll be blunt i really don't know how i can make this faster i mean there might be a way to not use the um not use as much space but in terms of time complexity this is pretty fast it's pretty fast so actually maybe it's not that fast i take actually maybe it's not that fast i take it back maybe it's not that fast it back maybe it's not that fast [Music] if that's a very large portion oh no right it was sort of decreasing i'm sorry yeah sort of in decreasing i'm sorry yeah sort of in decreasing order no no this is quadratic time i'm order no no this is quadratic time i'm sorry sorry i made a mistake right because if there's not much to remove on the for the right sub-tree for the right sub-tree and we've traversed from left to right and we've traversed from left to right until we find sort of the difference until we find sort of the difference between the left subtree and the right between the left subtree and the right subtree subtree each time right then we have quadratic each time right then we have quadratic time time for each okay i'm sorry i understand now for each okay i'm sorry i understand now yeah that actually makes sense yeah that actually makes sense i don't know why i didn't see that i don't know why i didn't see that before i really like before i really like uh i did practice more i really thought uh i did practice more i really thought i should have thought about this some i should have thought about this some more more um okay i think i understand now the algorithm as written is not great [Music] um it's correct but um it's correct but time limit exceeds the time limit that's quadratic time algorithm in some but how do i do this in a way that's not but how do i do this in a way that's not quadratic time if you want to do this recursively you know divide and conquer you cannot guarantee that the divisions are going to be or even remotely equal that's really the or even remotely equal that's really the problem problem yeah it takes a linear roughly a minute yeah it takes a linear roughly a minute linear low of end time linear amount of linear low of end time linear amount of time time each time you execute to split each time you execute to split to divide and the divisions are not to divide and the divisions are not necessarily uh necessarily uh equal in size so that's it really equal in size so that's it really um that's the problem that's why it's um that's the problem that's why it's quadratic time in theory how about this the first leg of the of the pre-order the first leg of the of the pre-order traversal first you know sort of from left to right that section should be sorted in descending order so you can actually if you know that that's true you should be able to use a binary um i want to say in logarithmic time you can find that's not decreasing i guess not if that works i don't know if that so i want to say if you can find this in logarithmic time instead of linear time then you're fine then you're in good shape it's going to be the first number so there's a left half in the left half and a right and if the number is smaller and if the number is smaller well actually you're doing something really the remaining um values into two pieces the remaining um values into two pieces but specifically you're trying to find to the left side all the numbers are are less than a certain value and to the right side all the numbers are greater than a certain value so you really want to find really from right to left of oh that's really interesting yeah you can use a not even think of that that's very not even think of that that's very clever um what's interesting though is that basically there needs to be a value in they need to be both larger than the they need to be both larger than the vowel than the head and also vowel than the head and also larger than the key you'll certainly run into a point where if and then you can do this is kind of interesting so first element in the range is greater ah yeah that's it which i think you probably want happily i don't have premium so i don't happily i don't have premium so i don't know what that question is but it looks know what that question is but it looks like a good solution except it's slow like a good solution except it's slow happy decoding keep happy decoding keep up thanks yeah thanks i appreciate that oh yeah you can't see the question yet i'm sorry it's premium it's premium um thank you yeah it's a slow solution i'll see if i can get the right solution though see if i can get there i don't think we shenanigans we would say so i don't actually know i don't actually know how this is going to work they're looking for the first value the first value that's larger than it also has to be larger than the key right because that value right because that value must define the right sub ahead of the must define the right sub ahead of the right subtree right subtree because if it's not at the head of the because if it's not at the head of the right subtree that means it's got to be the left subtree which it cannot be all right so right so right exists p is not equal to end left subject exists we could just do x the end if we um i don't know about this let's just think i don't know about this let's just think about this for a minute about this for a minute um i don't know man dude i'm like um i don't know man dude i'm like getting really hung up on this question getting really hung up on this question right subtree exists when and the left subtree exists one or or x minus a minus plus one is greater than x minus a minus plus one is greater than equal to three there's this rhett right subtree oh um right subtree oh um yeah yeah yeah so the right subtree exists you say this has got to be and p p has got to be greater than the key and then f l x b yeah left subtree exists yeah left subtree exists because the right subtree doesn't because the right subtree doesn't necessarily exist in which case necessarily exist in which case p may not be defined and you just xbf left side xbf left side a plus one x minus one a plus one x minus one something like this i don't know man something like this i don't know man i don't even know if this will compile i i don't even know if this will compile i don't know what's gonna happen here always false great i don't know man i gotta really think about this um all right first things first uh let's focus on one at a time let's do all right let's do that okay all right let's do that okay what happens here okay so our key is let's f5 to the head now we want to say let's f5 to the head now we want to say okay somewhere here from left to right there is a number that's greater than five so find this upper bound again now a is zero this shouldn't be plus one that's just a so we would find a pointer would point so we would find a pointer would point here right okay six where's what we got okay six where's what we got so this is fine let's begin and end for so this is fine let's begin and end for whatever reason that seems okay whatever reason that seems okay um i was actually thinking that these um i was actually thinking that these you wouldn't want to add and subtract you wouldn't want to add and subtract these iterators this way but these iterators this way but these are random iterators so it's fine these are random iterators so it's fine it actually works out it actually works out if you're dealing with other kinds of if you're dealing with other kinds of iterators it'd be harder iterators it'd be harder you'd have to use a different different you'd have to use a different different syntax so that's something to remember syntax so that's something to remember for myself um but anyway so this index so okay so now we get this right subtracts this left subtree exists x when we're looking at zero one two three four uh minus zero so x is four right that index and we say if this is less than or equal to b and the right subtree exists it's left subtree x minus four plus one square negative three um x minus zero that's one right there's one two three four that's the number i should get which is what i get yeah um that's actually five we got should we get one two three four five rather so the left subtree is the right sub so the left subtree is the right sub trees we say okay let's trees we say okay let's take a look at the right subtree and take a look at the right subtree and right p is greater than the key that's right p is greater than the key that's good good um i have our new value which is going um i have our new value which is going to be six to be six and we say okay val of x and we say okay val of x b and f x is four b and f x is four v is four l is six v is four l is six okay um i don't think this is necessary i don't think this is necessary i think this is gonna always be true i think this is gonna always be true well i don't know let's see a equals b so one is true yes this word is true so one is true yes this word is true which is what i expect it's false though in the next iteration six so yeah so that actually goes off true and then let's look at the left subtree iterated on the left subtree you have this uh no that's wrong that should be the key left subtree it's really confusing heck heck also i don't think that's um all right which part was wrong the third one from the bottom is the okay which one is that okay okay five two six one three four true false so our algorithm would uh find the first value it's larger than five which is um and we could we could print to see what and we could we could print to see what this finds what this gives us so first get three so first get three which is strange i really get six what two why is two what why is a one [Music] ah my freaking brains on delay here what's going on what is going on uh what what okay it's a zero oh i see the problem that's why no kidding what happened [Music] there was no value found that was larger now here's here's the tricky thing this upper bound assumes that you're dealing with sort of a set of numbers that has a sort of a set of numbers that has a certain property certain property excuse me so right no that doesn't work properly so the thing the thing that i guess i'm trying to is is i'm gonna lay down for a minute i'm i'm gonna lay down for a minute i'm getting really tired getting really tired um i think i found the problem um the i guess the problem with the the algorithm that i'm um i guess false negatives so false i guess false negatives so false positives i guess positives i guess is the issue so if it were uh the pre-order traversal of binary uh the pre-order traversal of binary search tree search tree then this algorithm is always going to then this algorithm is always going to return true on those cases return true on those cases however if it's not true that this is a however if it's not true that this is a um in other words it's false that this is a binary the pre-order traversal binary search tree the algorithm that i have will not always return false sometimes return false positives that is the problem that we're looking at right now the issue which is pretty interesting which is pretty interesting excuse me no what i was hoping excuse me no what i was hoping yeah so that's that's the problem yeah so that's that's the problem um basically we need to figure out a way um what i want to do [Music] excuse me i would like to do yeah so okay so i'm i'm really not i'm really not approaching this problem correctly right like i need i need a solid solution before i start coding kind of just wildly coding things and there doesn't make sense you need to actually have like a solution before you start programming it right like this it's not not correct or not not reasonable to just start programming so the issue seems to be that we want to excuse me um the partition element such that all the the partition element such that all the elements elements to the right are larger than to the right are larger than the value you're looking for and all the the value you're looking for and all the elements to the left in this particular range split the range into two pieces partition the range in two pieces now obviously this works nicely if we assume that the range is already however there is a problem um if there could be two things it could be that all the values i guess this value you're searching for i guess this value you're searching for so there's no so there's no there is no right subtree there is no right subtree that could be true that would that would that could be true that would that would actually give you actually give you you know sort of the element would sort you know sort of the element would sort of just fly off the side of the of just fly off the side of the but yeah basically you would show up you but yeah basically you would show up you wouldn't you wouldn't find the element wouldn't you wouldn't find the element that you're looking for that you're looking for right if there's no right subtree to be right if there's no right subtree to be found found that could be one case that could be one case but another case could be that but another case could be that you can't actually partition you know you can't actually partition you know your numbers are not partitioned in such your numbers are not partitioned in such a way a way where there's two distinct you know one where there's two distinct you know one one one you know one side on the left side is you know one side on the left side is less than your value and less than your value and the other side on the right side is the other side on the right side is larger than your value that could just larger than your value that could just be false be false in which case you may also run all the in which case you may also run all the way off the edge or way off the edge or you might might grab one of these you might might grab one of these numbers now if you do end up off the edge basically you want to verify if you go off the edge though and you if you go off the edge though and you don't find that there's no right subtree don't find that there's no right subtree so let's say you could do a you could do so let's say you could do a you could do a linear search an exhaustive search and a linear search an exhaustive search and just check just check left to right to see left to right to see if there are any values that you should if there are any values that you should be finding be finding if indeed there is no right subtree then you would just recurse on the left side substrate right you just wouldn't now the problem with that though now the problem with that though is you can't tell whether or not there's no sub tree if there is a uh if there is a uh or if the or if the partition won't work or if the or if the partition won't work properly properly now if the partition doesn't work now if the partition doesn't work properly uh you return false properly uh you return false right that's it you just you can't right that's it you just you can't partition partition um you sort of terminate early um you sort of terminate early you'd be able to you'd be able to check you'd be able to you'd be able to check that in uh in linear time because everything on the everything's in the yeah you must have that that partition must but the problem then is that if you but the problem then is that if you let's say you just sort let's say you just sort in decreasing order from left to right in decreasing order from left to right um the first time you would show um the first time you would show that okay you don't have a right subtree logarithmic time but then you'd say okay um let's let's verify that we're not in a faulty so let's suppose that p goes right out right off the edge without the left subtree well yeah we're going to process now this this lad this this sub range as a that's just the whole range of the left subtree now what ought to happen is our key gets updated basically if any value in that left basically if any value in that left subtree subtree is larger than that key is larger than that key um i think that might be the problem we i think that might be the problem we just need to specify um and then you're looking at left subtree or right subtree i mean that may have been the problem um so actually i think i know what i'm doing there's a range these numbers need to be there's a range these numbers need to be in that's what i'm doing wrong in that's what i'm doing wrong duh oh i feel so silly now i've seen i've seen you know okay these binary search tree verification questions really what you want to do is you just need to pass in a range of values and update those range values accordingly um yeah that's all that's all you have um yeah that's all that's all you have to do okay and you just have to compare that all the numbers match match the the range and specify and update the range accordingly if it's a left subject right subtree just and i mean a minimum and a maximum range and i mean a minimum and a maximum range you know in values you know in values minimum maximum values yeah i don't know minimum maximum values yeah i don't know man i man i like i think i just need more experience like i think i just need more experience with these questions with these questions because i've seen binary search because i've seen binary search verification type questions in the past verification type questions in the past and i know that you need to do some kind and i know that you need to do some kind of like min max of like min max um verification but i don't do it um verification but i don't do it like i don't always think to do that like i don't always think to do that which i think if i thought to do that in which i think if i thought to do that in this case i'd been i would have been this case i'd been i would have been done already but yeah it seems that you you do a logarithmic search i guess you assume that it's correct i guess you assume that it's correct until it's not um until it's not um and excuse me during the verification of the excuse me during the verification of the sub trees it'll it'll come out sub trees it'll it'll come out that the range wasn't actually um that the range wasn't actually um partitioned that's pretty much what what should happen and that's about it but you do need a left subtree check and a right subject i can eat both recursive check now the tricky thing recursive check now the tricky thing here though here though is how do you do this with a constant is how do you do this with a constant memory oh i have no idea memory oh i have no idea not a clue i guess you'd have to use some kind of a i guess you'd have to use some kind of a while loop i don't know while loop i don't know some i don't know some i don't know oh excuse me i have no idea i don't even have the i have no idea i don't even have the regular solution yet regular solution yet let me try that let me try the regular let me try that let me try the regular solution first solution first see if we can do that the recursive one very similar to what we were doing awesome man i'm i'm falling asleep here awesome man i'm i'm falling asleep here i need to go to bed i need to go to bed all right um okay excuse me let's do this um lower ah say yeah lower greater than the lower bound um um so the [Music] and so the right subtree the lower bound is going to be updated to this value is the upper bound doesn't change so everything has to be greater than or everything has to be greater than or equal to equal to it's gonna be greater than or equal to it's gonna be greater than or equal to whatever the previous lower bound was whatever the previous lower bound was and uh whatever this value this new and uh whatever this value this new value is value is it's gonna be greater than equal to both it's gonna be greater than equal to both the upper bound doesn't change the upper bound doesn't change and the lower amount of the left subtree and the lower amount of the left subtree lower bound doesn't change but the upper lower bound doesn't change but the upper bound changes everything's got to be lower and smaller than smaller than everything yeah everything to the left side is still got to be larger than whatever the range is lower bound but the upper bound now everything has to be smaller than the head and it also has to be smaller than whatever the previous upper bound was so let's get updated um now this pointer being greater than the key i don't know if we need to do that i don't know if we need to do that anymore i don't know if that even anymore i don't know if that even matters let's just check to see what happens wrong answer true false nice we can just do uh oh nice i see it works now oh nice i see it works now okay that's all i had to do okay that's all i had to do here's another question um does that even matter oh it doesn't seem to matter got the feeling like it wouldn't i got that feeling like see a non-existent um yeah basically it's vacuous vacuously true for non-existent intervals and then for the other interval intervals you just need to make sure that your your values are in the upper and lower bound ranges uh if the interval is just one and then i don't think you even need to check this quite frankly this is sort of a base case after that um after that um all right that's good all right that's good are there any test cases we fell on nope are there any test cases we fell on nope oh okay wow brother okay yeah i really need to get better at okay yeah i really need to get better at uh oh i don't need this anymore either uh oh i don't need this anymore either anyway yeah i really need to uh need to practice some more you know um um just looking to see which parts i can huh pretty interesting okay now the question is how do you do okay now the question is how do you do this this how do you do this with less memory how do you do this with less memory so this should have been like a really so this should have been like a really easy question i don't know man i'm like easy question i don't know man i'm like not that great at this but in simple terms um yeah whenever you're dealing with verifying binary search trees you want to basically have a lower bound and upper and uh yeah if and uh yeah if if it is indeed a binary search tree if it is indeed a binary search tree then then you can use this binary ser you can use this binary ser yeah if it is indeed a binary search yeah if it is indeed a binary search tree tree in this case you can actually use this in this case you can actually use this routine to do a logarithmic search routine to do a logarithmic search um obviously if it it's not a binary um obviously if it it's not a binary search tree and the logarithmic search search tree and the logarithmic search gives you something funky gives you something funky then at some point you're going to then at some point you're going to violate your bounds violate your bounds on the lower and upper bounds just have on the lower and upper bounds just have to update them correctly between each to update them correctly between each excuse me for each of the each of the excuse me for each of the each of the other other excuse me iterations now right now the excuse me iterations now right now the question is question is um can you do it using only constant um can you do it using only constant space complexity space complexity i could i was barely able to do it using i could i was barely able to do it using extra space extra space the constant space complexity basically you would need to do these without a the problem that i have with doing it without recursion is it um yeah i don't really know how to do this without without recursion you could view this like a a depth first search in a breadth first search um like i can i can definitely do this i can definitely do this iteratively in sort of a breath first search type of in sort of a breath first search type of way but that's not constant space way but that's not constant space complexity all right complexity all right definitely not using constant space complexity i think using constant space complexity i think is is i would need to this is property from left to right for each number there's a certain pocket for each number there's a certain pocket of values to the right where to the right all those values are larger but up to that point all the values are smaller so as you move to the right all these values are smaller and then boom and i guess there's this check that you and i guess there's this check that you want to do want to do basically i want to do a kind of like basically i want to do a kind of like dynamic programming sort of thing dynamic programming sort of thing like a very clever way to do this that like a very clever way to do this that doesn't involve recursion doesn't involve recursion or searching i don't want to say or searching i don't want to say you say okay um you say okay um i guess if you start with five then i guess if you start with five then all of your numbers the right of five all of your numbers the right of five have to be less than five have to be less than five up to a point where they're no longer up to a point where they're no longer less than five so i guess you have a a less than five so i guess you have a a lower bound and an upper bound where your upper bound is infinite and your lower bound your upper bound is five and your lower bound is infinite two is is less than five that's greater two is is less than five that's greater than our lower bound now harper bound goes from 5 to 2 and the next value has to be less than 2 and it's not the question is is it greater than it's going to be greater than 2 but is it if it's greater than two if it's greater than two that could be okay no see that's not that algorithm doesn't make sense that's not necessarily a correct algorithm five two one three six and then one is five two one three six and then one is less than two and then less than two and then three is greater than one it's gotta be greater than two also maybe you're supposed to maybe maybe it maybe you're supposed to maybe maybe it is still sort of end login is still sort of end login time and you say okay once you find you know once you find you know six is greater than you know it's six is greater than you know it's greater than the last value greater than the last value it's greater than your your you know it's out of a certain bound you want to find out which then you can figure out what value is then you can figure out what value is supposed to come after six supposed to come after six i don't know because if this is greater than five everything to the right of that is all supposed to be five huh let me lay down for a minute think huh let me lay down for a minute think about it i'm wondering if there's a way to do this that involves maybe a binary search or or just something some some constant or just something some some constant time time so i think i'm thinking the first value you look at is the head the first value you look at is the head the next value is either on the left the next value is either on the left subtree or the right subtree if it's in the left subtree that means it's smaller than that the previous value if it's in the right subtree that means it's greater let's suppose we're in the left subtree for a moment that means we have to be less than the head and then now this value is the new head of the left subtree and so our sort of our state is kind of the same as it just was where we have a new head and now this next value we look at we compare it to that head now if you're larger now if you're larger then you can't be larger than then you can't be larger than that means there is no left subtree and that means there is no left subtree and you're in the right subtree you're in the right subtree and again it's another ahead of another and again it's another ahead of another subtree subtree um but i guess like if you if you just um but i guess like if you if you just kept going smaller smaller smaller kept going smaller smaller smaller on the left subtree all the way down on the left subtree all the way down sort of nothing sort of nothing changes i guess in the state of things changes i guess in the state of things something like that if you but once you switch to the right subtree that's when things get interesting so as soon as you switch to the right subtree your you're larger than now the question is which sub which subject are you a part of then like which head are you now that the subtree of and i think you could use a logarithmic search there right because um from left to right left to right after that point you could do a logarithmic search to figure out which head your which head you're larger than um which which part of the tree is that node belong to how many um how many um of these sub trees that you looked at of these sub trees that you looked at this left subtrees how many of them are this left subtrees how many of them are empty right empty right um so let's say um so let's say you're right something because you perform your logarithmic search and you find that your i don't know somewhere in the middle so like 500 400 300 200 100 and then you know your value is like 350. so there's 500 400 300 200 100 um and you're you're 350. so you're you're right on off of 400 you're that right subtree there okay repeat your uh your algorithm i mean no what's the significance of that though um i don't really know exactly i think i think you use that to update what the i guess the minimum and maximum what the i guess the minimum and maximum value should be value should be uh because if you uh because if you if you now find a right subtree there if you now find a right subtree there that's uh actually i don't know i want to say if you if you find a value that's smaller to the right it could be a left now you can see the left subtree right subtree of the node you're looking at if you find a smaller smaller oh yeah yeah yeah the reason why that's oh yeah yeah yeah the reason why that's significant significant is that any number left or right is that any number left or right has to be at least as large has to be at least as large as that number they just found which was as that number they just found which was when we say was uh 350 and 300 and 400 right so your your 350 is it's gotta be hanging off of 300 so you can't have any number less than 300 now i think that's why so if you find the left if you're on a left sub tree and you go below 300 that's um that's your new minimum that's your new lower bound oh and that means you're a binary search tree anymore but let's a binary search tree anymore but let's say you keep going you do a similar say you keep going you do a similar thing you get another thing you get another right subtree um um that makes that works for the first that makes that works for the first the first right subtree the first right subtree but let's say you have another right but let's say you have another right subtree right subtree right and if you are and if you are if you are above is larger than it's the sort of two nodes there right there we said there's 300 and 400 and so so that actually tells us that all the nodes that we're going to look at now on this right subtree must be between 300 and 400. it actually gives us our our bounds because if we find anything above 400 that means that it's a new node on that on that previous branch previous tree and that that's actually where i think we need the stack because that's because that gets confusing right because you have multiple you know you have multiple layers and these branches i just gotta figure out you know i just gotta figure out you know where the heck is this new node supposed where the heck is this new node supposed to go a node that's smaller than 300 a node that's smaller than 300 uh all right that's sort of already done uh all right that's sort of already done i guess um i guess um but you can have a node that's larger than 350 then 400 or yeah because that would just get placed on a different right when you move when you move to a left when you move when you move to a left sub-tree all those values have to be less than the head and when you move to a right subtree all and when you move to a right subtree all the values have to be larger the values have to be larger than the head however than the head however when you move to a right subtree when you move to a right subtree you don't necessarily know which head you don't necessarily know which head that node belongs to um now in theory the easiest thing to do um now in theory the easiest thing to do is just find the first number is just find the first number that's larger that's larger than your head value and then you say than your head value and then you say everything then that splits the array everything then that splits the array into two pieces right into two pieces right the left subtree and the right subtree the left subtree and the right subtree that's all well and good that's all well and good however that's that's the basis for the however that's that's the basis for the recursive recursive algorithm we're trying to figure out a algorithm we're trying to figure out a way way me should not only do it iteratively but also do it without using a stack which is super challenging it's hmm excuse me now i'm wondering if maybe there's a way to use the vector itself like like a stack in that you could somehow save the position you need to jump to to jump back to i don't think you can i don't think it's that easy i don't think so i think it's as i said certainly navigating as i said certainly navigating you know down the left side of the tree through the different head nodes i think it's smaller and smaller and then boom you see a node that's larger and then you want to figure out okay which and then you put it there and you say and then you put it there and you say okay okay let's see the next value is another if i let's see the next value is another if i it's larger it's larger i guess again left subtree nodes that you want to left subtree nodes that you want to iterate over um interesting [Music] excuse me here keeping track of i don't know man it's hard seems like there's a lot of information well as soon i mean as soon as you see well as soon i mean as soon as you see no see a value that's larger you don't necessarily know [Music] um if any if it's larger than any of the nodes then that implies that all the all the nodes that are smaller than that if that makes sense um you're not going if that makes sense um you're not going to see any more of those because i mean not just that one i mean it's gonna be the i guess the head node that it's attached to and you're not gonna see anything that head node that head node because you can't right i mean certainly anything larger is either on the on that right subtree or is on some other head node that's larger off of some other head nodes larger possibly but something that's smaller than that current node's head node um basically if you see that it should have already been processed because everything to the right of the head of a right sub-tree needs to be larger is that right i don't know i'm kind of just babbling on here because i'm just thinking it through like what are some of the properties that we can use of these of these trees everything to the right of a head node there's the root and the head of the right sub tree well yeah you've got this left subtree it yeah you've got this left subtree it could be sort of any any shape what once you see a node that's larger than a particular then all the nodes for that head node then all the nodes for that head node you've already seen you've already seen that's good yeah it's going to be true that's good yeah it's going to be true the reason for that is that for a particular head note everything to the left of its subtree is less than and everything to the right of its subtree is larger but but also everything in that right subtree follows everything in the left subtree so there's a certain partition point where you will no longer see that left subtree and if this node is encapsulated by another you know let's say this is like a sub you know that's a subtree of some other tree whether it's on the left side of the right side that property still holds that's actually that's the question i'm wondering because everything on the on the left subtree so it's always going to be preceding the stuff in the right subtree this is a certain like cascading effect i guess i'm not really sure how to express it an inductive property where um i just think the left subtree the right uh like i want to say that you see a note you know you're moving you see a note you know you're moving from left to right from left to right you see a whole bunch of left sub trees you see a whole bunch of left sub trees see a right sub tree you say okay this see a right sub tree you say okay this is the finally i found the head is the finally i found the head for that right subtree you know the for that right subtree you know the appropriate position to put it in um you can guarantee after that point that the head of that node you won't see anything to the right of your current position that true because for that head node true because for that head node there's a left subtree and a right there's a left subtree and a right subtree and everything in the left subtree and everything in the left subtrees or subtrees or you've already seen it right correct you've already seen it right correct and further that means that and further that means that every node from there on out to the every node from there on out to the right right has got to be larger than that has got to be larger than that particular head that you found particular head that you found so you have an absolute minimum like it just got updated true now do you have an absolute maximum is that possible um not really i don't think you ever really have an absolute maximum the deal with the maximum is that uh the deal with the maximum is that uh the maximum will just tell you you don't really have a maximum actually well i don't know actually i don't know well i don't know actually i don't know now now i'm not sure i don't know what to think of the max we definitely have an absolute minimum there taking up that i got it got updated but now here's the thing like you could have multiple layers of you know from that right subtree you have a bunch of other left sub trees and then another right subtree you know the left sub trees and on and on you kind of have this like i don't know you have this like nesting that goes on and the problem is that let's say out of the blue you do get this very large node that goes all the way to the top level and that's supposed to be your your new sure you get a new minimum um sure you get a new minimum um but like how do you know but like how do you know which left subtree you're supposed to which left subtree you're supposed to jump to jump to because in earlier when there was only because in earlier when there was only one one sort of branch to pay attention to sort of branch to pay attention to uh it was pretty simple but uh it was pretty simple but now you need to somehow keep track of now you need to somehow keep track of the the quote-unquote holes the the quote-unquote holes to figure out which head node to jump to figure out which head node to jump back to back to see that's that's the thing i'm not sure see that's that's the thing i'm not sure about um well you're you're not gonna about um well you're you're not gonna jump to the jump to the previous ones ever again previous ones ever again uh the smaller ones uh the smaller ones so that's kind of good i guess so that's kind of good i guess however when you do your searching you need to somehow i don't know jump jump to the correct ones i'm not because we're trying to do this with all because we're trying to do this with all this without any extra this without any extra space um so we're not really keeping space um so we're not really keeping track of the sort of holes track of the sort of holes uh quote what you can do you can actually what you can do you can actually uh i have an idea uh i have an idea you could okay this is kind of kind of uh tricky but if you're if you're okay with destroying the array right at the end of it what you can do basically you have your logarithmic basically you have your logarithmic search that you're going to do search that you're going to do now that you know you're not going to now that you know you're not going to revisit a certain node revisit a certain node you can write in that node the you can write in that node the index um index um that you're going to jump to to perform that you're going to jump to to perform another binary search another binary search if that makes sense um if that makes sense um so if your binary search fails that sort so if your binary search fails that sort of gives you your stack of gives you your stack you kind of jump to the next index to you kind of jump to the next index to search maybe you could do something like that in that way you would actually be able in that way you would actually be able to chain your binary searches to chain your binary searches to figure out which node to jump to to figure out which node to jump to and ultimately i want to say something like there i want to say something like there really can't be that many of these really can't be that many of these indices to jump through something like indices to jump through something like that that i want to say something like that some i want to say something like that some kind of algorithm that you can come up kind of algorithm that you can come up with with sneaky kind of algorithm where you uh you don't use more memory you don't need a stack but the stack is sort of implicit in in the array you kind of write it in as you as you walk through it something like that i don't know i mean i don't know i don't know if you can i don't know i don't know if you can even do that if that even makes sense i don't know man i don't know i'll have to come back to this i think think about it some more i don't know if i'm gonna live stream that part i'm really tired uh probably just gonna end the stream go to sleep but this has been a really interesting question i got stuck on it you know i don't know i don't know what the uh how to do this without extra time complex extra space complexity let's really ponder it some more let me uh oh what let me go ahead and get going let me go ahead and get going let me get going so thank you all for watching hanging out saying hello i do appreciate it um wow oh it's two and a half hours i spent on this no kidding dying all right i'm getting out of here so take care have a good uh have a good rest of your day | 2024-03-22 12:10:28 | 255 | Verify Preorder Sequence in Binary Search Tree (Medium), C++, Leetcode |
|
_ZBkBn57JJI | question 242 of leak code valid anagram so given two strings s and t return true so given two strings s and t return true if t is a nanogram of s and falls if t is a nanogram of s and falls otherwise an anagram is a word or phrase otherwise an anagram is a word or phrase formed by rearranging the letters of a formed by rearranging the letters of a different word or phrase typically using different word or phrase typically using all the original letters exactly once so all the original letters exactly once so in the first example we have anagram and in the first example we have anagram and nagaram which returns true because if nagaram which returns true because if you see all the values of an s are you see all the values of an s are within t and there is no remaining within t and there is no remaining values rating carbon the second example values rating carbon the second example is false because we have two letters in is false because we have two letters in each which don't add up right the only each which don't add up right the only thing that's similar between the two thing that's similar between the two examples here is the a so we could use examples here is the a so we could use some kind of sorting algorithm and sort some kind of sorting algorithm and sort them and then see if they're the same them and then see if they're the same that would work just fine but what we're that would work just fine but what we're going to use instead is a hash table going to use instead is a hash table also called a frequency map and we're also called a frequency map and we're going to store the frequency so we're going to store the frequency so we're going to loop through s and we're going going to loop through s and we're going to update our frequency map so this is to update our frequency map so this is what the frequency map is going to look what the frequency map is going to look like so we're going to have a which is like so we're going to have a which is going to be pointing to 3 right because going to be pointing to 3 right because we've got 1 2 3 n which is pointing to 1 we've got 1 2 3 n which is pointing to 1 g which is pointing to 1 g which is pointing to 1 r which is pointing to 1 and m which is r which is pointing to 1 and m which is pointing to 1. so we've created our pointing to 1. so we've created our frequency map now what we can do is we frequency map now what we can do is we can loop through t and we can see if the can loop through t and we can see if the letter at this position is found within letter at this position is found within the frequency map and if it is then we the frequency map and if it is then we can subtract it from the frequency map can subtract it from the frequency map and then we move along we can subtract and then we move along we can subtract it we can move along it we can move along subtract it subtract it we can move along we can move along subtract it and then once this is complete if we pass all the tests that we have in our full loop checking the frequency map then we can return troop right but say we have an a here we get to the a this is going to go to -1 so we need some conditional logic which is going to say if so if map or letter is less than one just return false or if it's undefined return false so the way this algorithm is set out time complexity would be o n where we create the hash table so we have to loop through each value within string in order to create the hash table so that's going to be of n times so it's going to loop through the entire string plus m where m is looping through the entire t string and then space complexity is of n because we're storing all the values of string s within our hash table which we've created so firstly before we add any code we can take care of an edge case right so if s dot length doesn't equal t dot length then it's not going to be a valid diagram because they're not the same length then we need to initialize a map so our hash table which is going to be an object string s string s and we need to populate that map and we need to populate that map so let's just declare letter so let's just declare letter as si as si so we're grabbing each letter here so we're grabbing each letter here if if the map the map at letter doesn't exist at letter doesn't exist we're going to create it and set it we're going to create it and set it equal to one equal to one else else map of the letter map of the letter gets incremented gets incremented so if there's already a value within map so if there's already a value within map that letter then we just increment it by that letter then we just increment it by one and this will give us the frequency one and this will give us the frequency map we're looking for okay so the second map we're looking for okay so the second part of this algorithm we just need to part of this algorithm we just need to loop through loop through the second string the second string create a variable called letter we'll create a variable called letter we'll equal it to t at position i so the equal it to t at position i so the second string at position i to make this second string at position i to make this code a bit more readable then we need to code a bit more readable then we need to carry out a few if clauses so if carry out a few if clauses so if map at letter map at letter is undefined is undefined we can return false right because it's we can return false right because it's not found within the map not found within the map so they aren't valid anagrams so they aren't valid anagrams if if map letter is less than one map letter is less than one we can return false because there's more we can return false because there's more of the same letter in one string than of the same letter in one string than there is in the other so return false there is in the other so return false and then map and then map letter decrement letter decrement so if we pass the first two if so if we pass the first two if statements then we need to decrement statements then we need to decrement from map at that letter's position and from map at that letter's position and if we pass all that throughout the if we pass all that throughout the entire for loop we can return true entire for loop we can return true because that will essentially be a valid because that will essentially be a valid anagram anagram let's run this to see if it's worked let's run this to see if it's worked okay let's submit it okay let's submit it okay and there you have it | 2024-03-22 11:43:34 | 242 | Valid Anagram - LeetCode 242 - JavaScript |
|
9e1aLKHVwEg | Hello hello friends so this is the problem from the list difficult contest 3638 list difficult contest 3638 omelette using quantity three or more omelette using quantity three or more times in one and ₹ 100 from the station I want you to check on one side light sweet The person who The person who The person who is the list of the people and not the example of who behaves the two is research in a manner type and name is the name of the portion so let's have a pun cheese litterateur dad tank and Sudhir Vaikunth comes in his white skirt Subscribe to 1110 More Read That System Map The Time Win The Opposition Fighter Card Okay So This Pregnancy That Always Notice The Video then subscribe That Always Notice The Video then subscribe to How To Editor In To The System Valid For Android System But Milk 100 Is Not Considered to be seen it is due to solve this problem solution President Number of People More Than One Should at Least in Swarna Time and OK 100 Grams Defining Dictionary for the Times and Doing Simply Midning Dip Eliminate setting the Eliminate setting the Eliminate setting the full value point one ok so the solution from left full value point one ok so the solution from left is that time thirteen cases minute tawe and 3000 minutes and subscribe subscribe this Channel and subscribe the Channel press The Seervi media agency list and adjacency maximum lagna approach should not contain information Should Should Should Not Going Strong Entries and Outgoing Not Going Strong Entries and Outgoing APN Subscribe to the Video then subscribe to the Video then subscribe to Torch Light Bill Complex Finally E Torch Light Bill Complex Finally E Torch Light Bill Complex Finally E travel through period hole's set of the agency list all of the map ok chirva flight real mathematical operations to check also bounce of the time should share and performing wash population du Plessis like it ifik sundar karenge is loose the person for the 3031 subscribe The Channel and subscribe subscribe The Channel and subscribe subscribe The Channel and subscribe the Light a lamp o the Light a lamp o Pregnancy It is not done with the change of wave Pregnancy It is not done with the change of wave effects Entry 800 to 1000 Cities to Take Off effects Entry 800 to 1000 Cities to Take Off Pollution in English for Kids for the Pollution in English for Kids for the Efin More List Play List Subscribe Efin More List Play List Subscribe Time is the Tree of Life in Everyone Time is the Tree of Life in Everyone Time is the Tree of Life in Everyone Subscribe To Who Is The Inside The Range Of Merit List Side Table Of Saintly Figures List Start Doob 600 First Time Because There Are Candidates Author Last Time 100 subscribe The subscribe to the Page if you liked The subscribe to the Page if you liked The Video then Last Time Machine Time Travel Last Time Machine Time Travel Give Me The Volume With Range Just Like It Is Give Me The Volume With Range Just Like It Is In The Range Of Dresses In Can See The In The Range Of Dresses In Can See The Question Is The Range Of Channel Subscribe Question Is The Range Of Channel Subscribe Button To The Journey To The World Button To The Journey To The World Will Be Subscribe My Channel Like Will Be Subscribe My Channel Like Will Be Subscribe My Channel Like call the return sudhir va basic operation to convert sudhir va basic operation to convert president to the list final reduced to president to the list final reduced to select from its ncc the like share select from its ncc the like share and subscribe subscribe 602 | 2024-03-19 15:30:27 | 1,604 | 1604. Alert Using Same Key Card Three or More Times in a One Hour Period | Biweekly Contest 36 |
|
6rIamdWnn7A | welcome to mazelico challenge this problem is called find the shortest problem is called find the shortest super string super string given an array of strings words return given an array of strings words return the smallest string that contains the smallest string that contains each string in words as a substring if each string in words as a substring if there are multiple valid strings there are multiple valid strings in of the smallest length return any of in of the smallest length return any of them them okay so you may assume that no string in okay so you may assume that no string in words is a substring of another string words is a substring of another string in words in words so say that we're given these words here so say that we're given these words here this superstring contains every single this superstring contains every single word word in our words list basically what we're in our words list basically what we're trying to figure out is trying to figure out is how many of these words can we overlap how many of these words can we overlap and save as much space as possible so and save as much space as possible so the order is going to matter the order is going to matter and yeah so this problem's and yeah so this problem's pretty simple to understand pretty simple to understand but the solution is very difficult in but the solution is very difficult in fact i think it's the hardest question fact i think it's the hardest question this this year this this year so i'll do my best to try to explain the so i'll do my best to try to explain the solution solution but i still don't quite understand it but i still don't quite understand it well so just keep that in mind well so just keep that in mind alright so the first thing we need to alright so the first thing we need to figure out or understand is that figure out or understand is that this can be solved as a graph problem this can be solved as a graph problem um one thing we could kind of see is um one thing we could kind of see is every time we want to add another string every time we want to add another string we want to check to see is we want to check to see is how much overlap is there between the how much overlap is there between the source word and the target word that source word and the target word that we're trying to add so say that where we're trying to add so say that where this is our source word this is our source word and we are trying to add uh this word and we are trying to add uh this word here here how much like space can we save how much like space can we save well if we were just uh looking at the well if we were just uh looking at the entire word see if there's an overlap entire word see if there's an overlap say that we looked at our target word or say that we looked at our target word or source word and said okay from this end source word and said okay from this end from the very whole string from the very whole string this is the same as this word here and this is the same as this word here and obviously it's not obviously it's not so we can't say four but if we look at so we can't say four but if we look at this this cta cta we can save three character cta cta we can save three character strings here because strings here because all we need to do is just add this end all we need to do is just add this end and that's going to contain and that's going to contain that first string of six characters in that first string of six characters in here right so this would be the here right so this would be the minimizing minimizing path so what we'll do is create some path so what we'll do is create some sort of data structure that's going to sort of data structure that's going to record record the cost from a source index to a target the cost from a source index to a target index index because that's all that really matters because that's all that really matters and once we have that and once we have that then we can make this into a graph then we can make this into a graph problem to solve it out so let's start problem to solve it out so let's start by creating by creating a lookup we're going to call it cost a lookup we're going to call it cost and i'll start by initializing n to be and i'll start by initializing n to be the length of words the length of words so this cost here is going to be so this cost here is going to be representing to us representing to us from the index number is going to from the index number is going to represent represent the word that we're at and each one of the word that we're at and each one of these is going to have a list of the these is going to have a list of the character that we're character that we're the index word that we're trying to add the index word that we're trying to add here and we want to calculate how much here and we want to calculate how much space space can we save so we'll just start with can we save so we'll just start with zero because we don't know what they are zero because we don't know what they are yet and we'll times this by nine so each yet and we'll times this by nine so each one of these are going to be one of these are going to be a word that we can add and we'll say a word that we can add and we'll say four blank and range of four blank and range of n okay so now we have n okay so now we have our data structure we want to calculate our data structure we want to calculate this out so four i this out so four i in range of n we want to calculate for in range of n we want to calculate for every other one for j every other one for j and range of n as well we're going to and range of n as well we're going to calculate to see calculate to see depending on what the minimum length is depending on what the minimum length is we call we call our example that we just mentioned with our example that we just mentioned with these two these two we're going to take the minimum length we're going to take the minimum length between the two between the two and check to see from the starting point and check to see from the starting point of this can is the same as the ending of this can is the same as the ending strings strings of whatever is in here and if it's not of whatever is in here and if it's not we'll just continue on to see we'll just continue on to see okay what is these these three equal to okay what is these these three equal to these three these three and so on and so forth and see if we can and so on and so forth and see if we can add it up so add it up so what we'll do is have another nested for what we'll do is have another nested for loop we'll say 4k in range loop we'll say 4k in range of the minimum between length of words of the minimum between length of words i and length i and length of words j and we're going to move of words j and we're going to move backwards because we want backwards because we want we want to see what the largest one is we want to see what the largest one is okay so if words of i okay so if words of i uh let's see minus k onward uh let's see minus k onward is equal to words of j is equal to words of j uh up to k uh up to k j here okay if this is true j here okay if this is true then we want to update our cost then we want to update our cost to be equal to k so cost of i to be equal to k so cost of i k our j is going to be equal to k k our j is going to be equal to k and that will immediately break and that will immediately break otherwise if otherwise if like we can't find one that's true then like we can't find one that's true then it's just gonna stay at zero it's just gonna stay at zero so let's first look at this and see if so let's first look at this and see if it makes sense it makes sense um here with this example there's no um here with this example there's no overlap overlap at all so you can see like the only at all so you can see like the only times that we can save times that we can save spaces if we add the same letter to spaces if we add the same letter to itself because obviously itself because obviously if we add alex to alex we can save four if we add alex to alex we can save four characters because we don't need to add characters because we don't need to add anything at all anything at all and later on when we build up this and later on when we build up this string we could just subtract string we could just subtract the however many letters that we're able the however many letters that we're able to save from the beginning to save from the beginning and just add whatever's left to that and just add whatever's left to that string string okay so now we have that cost now this okay so now we have that cost now this is where it gets difficult um is where it gets difficult um how can we calculate how can we calculate what our minimum string could be um now what our minimum string could be um now if we were to do this brute force if we were to do this brute force we could create like a permutations list we could create like a permutations list of of all the different paths that we can take all the different paths that we can take to add all the words like you can have to add all the words like you can have uh i don't know like all sorts of all uh i don't know like all sorts of all sorts of different paths that we can sorts of different paths that we can take to add every single word and then take to add every single word and then we can just like we can just like um build up the string and calculate the um build up the string and calculate the minimum cost and whatever is the minimum minimum cost and whatever is the minimum cost we can return that string right but cost we can return that string right but that that is going to be an exponential time and is going to be an exponential time and it's going to reach the time limit so it's going to reach the time limit so that's not going to work but surely if that's not going to work but surely if there's a recursive solution there's a recursive solution then there's probably a dynamic then there's probably a dynamic programming solution right programming solution right so here's what we're going to do there's so here's what we're going to do there's two insights here the first thing is two insights here the first thing is using a bit mask using a bit mask and recall that there's only 12 words so and recall that there's only 12 words so what we can do is what we can do is use a bit mask to represent the state at use a bit mask to represent the state at which which we're in right now so see how we had we're in right now so see how we had like sort of a mess like this like sort of a mess like this uh each one of these ones represents uh each one of these ones represents that fact that we've that fact that we've added this word to the string okay added this word to the string okay but that's not enough because the order but that's not enough because the order matters right and specifically for this matters right and specifically for this question here question here it's really more about what character it's really more about what character or what word have we just added so have or what word have we just added so have we added just added this one have we we added just added this one have we just added this one just added this one uh and so on and so forth so what we're uh and so on and so forth so what we're going to have to do then is create some going to have to do then is create some sort of dynamic sort of dynamic programming array dp array programming array dp array and what this will contain is and what this will contain is um like the key will be the um like the key will be the bitmask representation of our state and bitmask representation of our state and we're going to have a we're going to have a list here of every single index list here of every single index um inside of our words so it'll be 12 um inside of our words so it'll be 12 maximum maximum and this will be contained two things and this will be contained two things it's going to contain it's going to contain first the length of the string that first the length of the string that we've calculated so far we've calculated so far okay as well as the string so far that okay as well as the string so far that we've we've that we created and that way at the very that we created and that way at the very end we could just take end we could just take our bit mask that represents everything our bit mask that represents everything added added like this and we'll just take whatever like this and we'll just take whatever the minimum length is the minimum length is for this bit mask here and return the for this bit mask here and return the string that represents the minimum string that represents the minimum length length because we'll be calculating it all the because we'll be calculating it all the way through so way through so um that's definitely hard to understand um that's definitely hard to understand but but i'll do my best here but but i'll do my best here and we'll try to figure out everything and we'll try to figure out everything okay so first thing we want to do is okay so first thing we want to do is create our dp array right create our dp array right so the dp array is just going to be a so the dp array is just going to be a nested list nested list and it's going to contain a list here and it's going to contain a list here and we have to have and we have to have what a tuple right and the first thing what a tuple right and the first thing length will start with an infinite value length will start with an infinite value so that we could so that we could decrease it immediately every time and decrease it immediately every time and we'll have what an empty string at first we'll have what an empty string at first so tuple empty string and we'll multiply so tuple empty string and we'll multiply this by however many indexes we have this by however many indexes we have now we want to have this oops now we want to have this oops see here so we have this see here so we have this and then we want to do this inside of a and then we want to do this inside of a for loop so four blank and range of for loop so four blank and range of what uh well we want to have every what uh well we want to have every single state possible right so single state possible right so it's from zer from zero all the way on it's from zer from zero all the way on to to all ones so we'll just have to use a uh all ones so we'll just have to use a uh bitwise here and say one bitwise here and say one with n being all the representations with n being all the representations right there right there okay so now we have our dp array okay so now the first thing we want to fill our base condition uh so for let's see i in range of n we're going to calculate um everything with like one state here because this we know if if we're just adding this first word initially then the minimum cost is just just going to be the word that we're adding the length of the word and it's going to be the word itself because we've gone from 0 to adding a word right so we know what that is so we'll just take dp and we'll say i like this and this will equal let's see it will be words and words i and words i okay so let me make sure this also looks okay so let me make sure this also looks good here okay so you can see like when we're adding here four alex five loves and there should be eight lead code right here and it's kind of hard to um know what all these index numbers are right now because these are all like states but that's so be it like let's assume that's correct for now okay so now now we need to figure out update our dp array in order for every update our dp array in order for every single state as well as single state as well as every single different index number that every single different index number that we're adding at from the state we're adding at from the state before okay so uh we'll call this four before okay so uh we'll call this four it's called bitmask in a range of it's called bitmask in a range of i to n i to n okay so what we got here okay so the first thing we want to figure out is from which source to which target are we okay so to do that i'm going to first okay so to do that i'm going to first calculate calculate the different possibilities from which the different possibilities from which index to which index we're coming from index to which index we're coming from right now right now so to do this let's see i'm gonna call so to do this let's see i'm gonna call this bits this bits and we're gonna say for and we're gonna say for j in range of uh j in range of uh let's see and let's see and if we find that in this state this index if we find that in this state this index number exists number exists then we'll add it to this bits so if then we'll add it to this bits so if bitmask will use the and one j if that's true then we'll add it to this bits and now we can calculate what the word that we're adding or the index number anyway and as well as our source i will say forefront and we'll use this air tools permutation to get every single different permutation from the source target and this actually matters because depending on what word we're adding and which word we're coming from uh it could be different the answer could be different so permutations in okay so now let's first calculate the okay so now let's first calculate the candidate like candidate like what's the word um what's the word um that we will end with right now because that we will end with right now because if it's not if it's not smaller than uh some previous value smaller than uh some previous value we've calculated then we've calculated then then we should just leave it so a then we should just leave it so a candidate is going to be candidate is going to be let's see we're going to look at their let's see we're going to look at their dp and we'll say dp and we'll say um now this one gets really tricky but um now this one gets really tricky but oh that's right um we're going to use a oh that's right um we're going to use a or symbol here because we want to or symbol here because we want to calculate like calculate like when the state didn't have this added when the state didn't have this added character right so character right so what we'll do is say or and we'll take what we'll do is say or and we'll take one to add like this one to add like this and we're going to take the ad here oh no that's not the ad it's the source as well as take the second character which is going to be a string and we're going to add the second element so this will be whatever path string that we calculate so far without having added this word and we'll take see we're going to add this and we are going to take from our cost and we are going to take from our cost function function however many words we can save however many words we can save onward right so cost and we'll take onward right so cost and we'll take uh from target to source onwards so whatever we can save onwards we'll add that to our candidates and now we're going to try to update our dp the bit mask the index number we're the bit mask the index number we're trying trying to add we'll take the minimum between and our tuple of candidates and our tuple of candidates length of the candidates as well as the length of the candidates as well as the candidate itself okay finally uh at the very end we should have the very last number here dp will contain like um with with the different index numbers with with the different index numbers added last added last and we want to take the minimum between and we want to take the minimum between these right so we'll take the minimum these right so we'll take the minimum of this and we'll just take the second of this and we'll just take the second element element inside of that so okay so let's see if this works i'm sure yep target there's no targets yep target there's no targets should we add should we add okay so i don't know if this worked but okay so i don't know if this worked but whatever yolo let's see if this works uh okay so i messed something up here of course i'm adding the cost of course i'm adding the cost maybe maybe [Music] yeah i might have to switch that around should be the source to add let's see all right yeah yeah so i think that's what the problem was let's go yep there we go accepted oh yep there we go accepted oh so are you confused i mean me too like so are you confused i mean me too like what the hell this is not what the hell this is not a reasonable interview question um and a reasonable interview question um and even after looking at the solution i'm even after looking at the solution i'm still confused i'm still still confused i'm still very confused about this but hopefully very confused about this but hopefully this kind of helps you kind of get there this kind of helps you kind of get there i may have made some mistakes in what i i may have made some mistakes in what i was explaining was explaining um but yeah time complexity wise it's um but yeah time complexity wise it's going to be exponential for sure because going to be exponential for sure because of this permutations it's going to be of this permutations it's going to be 2 to the nth power as well as n squared 2 to the nth power as well as n squared because of all these nested for loops because of all these nested for loops so it's still better than doing the so it's still better than doing the brute force method brute force method but you know if i was just trying to but you know if i was just trying to solve this solve this on the spot maybe the brute force method on the spot maybe the brute force method like like would be acceptable i don't know um would be acceptable i don't know um but yeah all right so i definitely but yeah all right so i definitely recommend looking more into this uh recommend looking more into this uh specifically this traveling salesman specifically this traveling salesman problem could help problem could help but these bit mask situations are really but these bit mask situations are really confusing and confusing and something that i don't fully understand something that i don't fully understand myself so sorry i can't be more help i myself so sorry i can't be more help i hope this helps there are definitely hope this helps there are definitely more more places that you can look for uh places that you can look for uh resources so resources so thanks for watching my channel remember thanks for watching my channel remember do not trust me i know nothing | 2024-03-25 12:00:46 | 943 | Leetcode - Find the Shortest Superstring |
|
tvE1yniU760 | foreign so today we are going to see this so today we are going to see this question that is patience with the question that is patience with the condition in the lead code so here what condition in the lead code so here what you have to do write a SQL query to you have to do write a SQL query to report the patient ID patient name all report the patient ID patient name all the conditions of the patient who have the conditions of the patient who have type 1 diabetes type 1 diabetes and here the condition is type 1 and here the condition is type 1 diabetes is always start with the diabetes is always start with the this prefix Dia B1 right this prefix Dia B1 right so we have to return the result table in so we have to return the result table in any order any order the query result format is in the the query result format is in the following example following example so here we go so here we go patient write a patient name and patient write a patient name and condition we have given and the output condition we have given and the output you can see that this so here what is you can see that this so here what is the condition the condition the the type 1 diabetes it always start with the type 1 diabetes it always start with the d i a b one prefix d i a b one prefix so here we can see so here we can see here it is starting with d i a b one so here it is starting with d i a b one so result in the result it is included result in the result it is included and also you can see that here is also and also you can see that here is also starting so it is starting so it is also included also included but here d i a b here there is no one so but here d i a b here there is no one so that's why it will be not included that's why it will be not included so here d i a B1 start with here here so here d i a B1 start with here here you can see d i a B1 start with here you can see d i a B1 start with here so it must start with b i a B1 so it must start with b i a B1 right so here I have already written the right so here I have already written the query query so so we have to select all the we have to select all the columns so that's why I written here columns so that's why I written here select star from the vegetable patient select star from the vegetable patient table and here is the condition table and here is the condition so it must start with these otherwise it so it must start with these otherwise it should contain this should contain this and make sure that here you first of all and make sure that here you first of all you should give the space so let us you should give the space so let us see why I have written this see why I have written this so first condition is it will be so first condition is it will be starting with the this right starting with the this right and next is it can be in the after this and next is it can be in the after this this acne this acne after this whatever decision is there after this whatever decision is there you will find that there is space and you will find that there is space and Dia B1 so that's why I return this it Dia B1 so that's why I return this it should contain this space and this should contain this space and this that means it will be start here that means it will be start here so if I go to the table yes here you can see in the conditions yes here you can see in the conditions it will be either will be here at the it will be either will be here at the starting otherwise starting otherwise it will be at the second place right you it will be at the second place right you can see that can see that with the space and this with the space and this so that's why so I have written this so you might be thinking why we have taken here as space if we take here without space then what will happen will be like will be like ACN e ACN e and d i a b and d i a b one zero zero one zero zero one zero zero one zero zero but in this condition you see that there but in this condition you see that there is no starting is no starting here it will be start from by uh here here it will be start from by uh here will be space and it is starting from will be space and it is starting from here there will be no space here so we here there will be no space here so we can't take this can't take this right so here you in the question you uh right so here you in the question you uh find that it always start with the find that it always start with the d i a B1 d i a B1 so if we replace this so if we replace this if we delete this space that will be not if we delete this space that will be not taken in the answer why because it is taken in the answer why because it is not starting with d i a b one not starting with d i a b one so so for that condition I have taken so so for that condition I have taken here a space here a space so so if it is in the if it is in the condition condition after this it should be have first space after this it should be have first space so that's why I have taken here a space so that's why I have taken here a space and this condition is for if it is and this condition is for if it is starting from here and this condition is starting from here and this condition is for after this acne it should be start for after this acne it should be start so that that is why I have written this so that that is why I have written this or in this two condition first it should or in this two condition first it should be start with either with this otherwise be start with either with this otherwise after space It should be there after space It should be there so now let me delete the explanation and so now let me delete the explanation and let us run this code here we will get error why because here I have written query now it should run the here you can see success submit here we go so this is the way we can write a query for patients with the | 2024-03-21 11:32:04 | 1,527 | 1527. Patients With a Condition leetcode solution | Leetcode SQL Solutions | realNameHidden |
|
91_RHE_U3t4 | hi today i'm talking about leak code problem problem one two two six the dining philosophers one two two six the dining philosophers and i had to actually read this problem and i had to actually read this problem a few times a few times to be sure that i understood it it's a to be sure that i understood it it's a very very very very unlit code like problem but once i did unlit code like problem but once i did understand it understand it i really liked this problem i thought it i really liked this problem i thought it was very interesting was very interesting so let me explain it to you using this so let me explain it to you using this diagram diagram basically we've got five philosophers basically we've got five philosophers sitting at a table sitting at a table i've labeled them here zero through four i've labeled them here zero through four and at this table there are five forks and at this table there are five forks zero through four also labeled in green zero through four also labeled in green so the philosophers need to hold two so the philosophers need to hold two forks forks in their hands to eat their spaghetti if they try to eat the spaghetti without two forks then they won't be able to and yet they can pick up the forks and they can put the forks down and they can eat spaghetti so the problem is that all of these philosophers are going to try to simultaneously eat their spaghetti and what we want to do is organize it so that they can eat as much spaghetti as they want meaning have as many as many periods where they pick up their forks and eat spaghetti and put their period and put their forks back down as many of those periods as we want um without ever getting into the problem of one philosopher or of the philosophers trying to fight for the same fork so you can imagine just um you know you have if you if you were to just tell your philosophers hey grab your uh grab your right fork and your left fork and then just eat and then put your forks down when you're done the problem is that zero and one would both be trying to grab the same fork and one is trying to grab the same fork that two is you know you the philosophers need um two forks in order to eat uh and there are only five forks like there's the same number of forks as so this problem is asking you to write so this problem is asking you to write or to create or to create an object that will manage five an object that will manage five threads each thread threads each thread is acting on behalf of one of the is acting on behalf of one of the philosophers philosophers so there's a thread for philosopher zero so there's a thread for philosopher zero and and it's going to try to pick up the forks it's going to try to pick up the forks and eat spaghetti and eat spaghetti there's a thread for philosopher one there's a thread for philosopher one that wants to do the same thing and so that wants to do the same thing and so on on and what you need to do is manage these and what you need to do is manage these philosophers philosophers so that they can all pick up their forks so that they can all pick up their forks and successfully eat their spaghetti and successfully eat their spaghetti and the the problem is going to give you and the the problem is going to give you a number in which means the number of a number in which means the number of i think of it as plates of spaghetti i think of it as plates of spaghetti that the philosophers are going to eat that the philosophers are going to eat so if you're a philosopher you can pick so if you're a philosopher you can pick up your two forks you can eat one plate up your two forks you can eat one plate of spaghetti of spaghetti you could hold on to the forks and just you could hold on to the forks and just keep eating your plates of spaghetti keep eating your plates of spaghetti but then the other philosophers wouldn't but then the other philosophers wouldn't get theirs so you've got to somehow get theirs so you've got to somehow manage across multiple threads manage across multiple threads the the coordination so that all your the the coordination so that all your philosophers can philosophers can eat at the same time so my first solution to this uh wound up being pretty slow but i i went with the the approach of slow and steady wins the race one thing that that is maybe not quite so good about this problem is that there is um there's basically one one good way to solve it so if you look at the the um accepted solutions pretty much everyone is in the same distribution almost everyone solves it in about the same time except for me i've invented a slower way to solve the problem than most everybody else did but then after thinking about it a little bit more i figured out the faster way so let me talk to you about the slower way first and basically what we're going to use to what is called a lock in python so a what is called a lock in python so a lock lock is just this object which um is just this object which um has let's see a lock it has has let's see a lock it has state like is it locked it's called state like is it locked it's called something else but something else but like there's just a state locked which says which is basically just a boolean true or false it's conveying whether the lock has been locked or not there's also acquire and what acquire does it's a function that when you call it it's going to try to lock the lock and if the lock is unlocked then it will just lock the lock and return back to the caller if the lock is locked then what acquire is going to do by default is it's going to block and block means the execution of the thread is not going to continue until acquire stops blocking and returns back so somebody you know a caller calls acquire if the lock is unlocked it just immediately returns it immediately locks the lock and then returns and the caller can go on its way if caller calls acquire and the lock is already locked then it's just going to wait like this function call will take as long as it takes for the lock to become unlocked and then return back to the caller and so then the caller can return on its way or it can continue on its way and then the final function here is just called release release and release just flips the state from locked to unlocked so basically locks pretty simple but they're how you can coordinate shared resources across multiple threads and that's exactly what we need to do for this problem so so we want to make sure that our philosophers can all share their forks across the different threads and the way we're going to do that well the the easiest the the slow but easy solution is we can realize that well if just one philosopher was eating at a time then we would uh never run into any contention um that is there would never be any problems nobody's fighting for the same forks so if we just say hey floss for zero you can start you pick up both of your forks eat your plate of spaghetti set your forks down and then it goes on to the next philosopher philosopher one philosopher two philosopher three so you can kind of right away see like not only is this going and it's just going to loop so if we if we need to eat 20 plates of spaghetti we're just going to loop 20 times however many times we're just going to keep looping you can kind of see one how this is obviously going to work because it's impossible for us to contend if only one guy is eating at a time and then two you can see how it's going to be slower than everybody else's solution and the reason is of course we have five forks and five philosophers and it takes two forks to eat a meal well the maximum kind of throughput that we can do is two philosophers simultaneously eating we can never do more than that because there aren't enough forks to do anymore but doing less than that just means we're going to be slower so my my solution has just one philosopher eating at a time but that means we're basically going at half the speed that we might be going half the speed because instead of two people eating at once there's just one guy eating at once so let me show you what that code looks like i think it's it's pretty straightforward my solution object is going to have as its initialization function so what i'm going to do when i start is i'm going to create a lock object and we get the locks from the threading module i'm going to create a lock object and basically i want there to be one lock per philosopher and the locks are just going to represent like hey it's your turn to eat so your the philosophers are going to try to acquire their lock um yeah let me let me talk about that in a second so okay we create a lock one for each of the philosophers and then what i'm going to do is lock all of the philosophers but the philosopher and the zero position so in my initialization i just go one to five to acquire or rather to lock all of the locks except for lock zero okay and so then this function is what the um the elite code problem wants me to write wants to eat and this function is going to be called by the five threads that represent the five philosophers so this this function gets called five times simultaneously and what i'm doing here in line 23 is i'm figuring out who the next philosopher is this is the philosopher who are going to say okay i'm done eating you can go and that philosopher the philosopher input is just like the number of the philosopher you are so 0 1 2 3 et cetera so the next philosopher is just philosopher plus 1 mod 5 so that when we're at philosopher 4 plus 1 5 mod 5 0. so we just kind of loop like that so that's the next philosopher what i'm going to do is i'm going to try to acquire the lock so remember this is getting called five times simultaneously by my five philosophers philosopher zero his lock is unlocked i didn't lock it up here so philosopher zero's lock is unlocked and he's just going to continue on right away he acquires his lock and aguirre just locks his lock and then returns execution back to him so what he does is he picks up his left fork picks up his right fork eats puts his fork down and then the next philosopher he unlocks that philosopher's lock so that's what happens for philosopher zero and remember he never unlocked his own lock and that's important because if n is greater than one that means our five threads are going to call wants to eat in times so there are five executions of this thread or sorry of this function if n is equal to one if n is equal to two there are ten executions of it three fifteen and so on okay so philosopher zero we just walked through how he worked um philosopher one what he's going to do uh his next philosopher of course is two philosopher one plus one is two mod five is two he's going to try to acquire his lock but remember that's going to fail because i locked it in line nine i locked everybody but zero in line nine so rather i shouldn't say it's going to fail it's going to block he tries to acquire his lock and you can think of it as this is just going to take forever he's not getting it back because it blocks so like this is a function that's going to take forever or when i say forever what i really mean is it's going to take until the loss for 0 has finished finished execution up to line 31. and then philosopher zero picks philosopher's zero's next philosopher which is one and philosopher zero when executing this function releases philosopher one's lock and so then philosopher one moves past line 25 and philosopher 1 picks up his left fork right fork eats left fork right fork and philosopher 1 releases philosopher 2. and then that just goes on a loop forever basically velocity for zero eats unlocks loss for one philosopher one locks his lock again picks up his forks eats puts his forks back down philosopher one unlocks two without unlocking himself and so you can think like okay if n is greater than two or if n is greater than one like we have multiple multiple plates of spaghetti philosophers zero and one are back at this line trying to acquire their locks again but remember when they acquire their locks they lock it and they never release their own lock you only release the lock of the philosopher next to you and so then that just enables you know this progression where you circle around eating so i think like the advantage of this solution is that it's really simple and like you can tell it's going to work uh for sure um because there's no there's no contention um there's no possible way to contend um like one one problem with locks is the idea of deadlocks so like what i was saying with uh with acquire a second ago you can imagine if two philosophers try to um acquire a locked lock it's never going to return for them or if if nobody is going to release your lock you're just going to wait forever um or like if i'm waiting on if philosopher 1 is waiting on philosopher 2 to unlock something and philosopher 2 is waiting on philosopher 3 to unlock something and philosopher 3 is waiting on philosopher 1 to unlock something you know you can just create this kind of deadlock where everybody's waiting on someone else and so nothing ever gets unlocked and my solution of just of just letting one philosopher eat at a time means that this can't happen so it's simple but of course it's slow and so then i having solved it you know the first time i submitted it i think i got like six percentile for speed so then i thought a bit more about i was doing and how i could you know i was doing and how i could you know solve it kind of the solve it kind of the the correct way and when i say correct the correct way and when i say correct way way i mean the way that um i mean the way that um the way that's that it's optimal to the way that's that it's optimal to solve solve so like let's always get two so like let's always get two philosophers eating at the same time philosophers eating at the same time and making that change i got up to 91.5 and making that change i got up to 91.5 percentile for speed percentile for speed but i'm pretty sure this is just a lot but i'm pretty sure this is just a lot of like it's also random variation in of like it's also random variation in here here um so i think i think probably all um so i think i think probably all solutions solutions other than the first one i showed you other than the first one i showed you all solutions that involve all solutions that involve two philosophers simultaneously eating two philosophers simultaneously eating going to effectively be about the same going to effectively be about the same speed speed but let me just walk through this two but let me just walk through this two philosophers eating simultaneously philosophers eating simultaneously so for this for this idea what we have so for this for this idea what we have to do to do we have to figure out how can we grab we have to figure out how can we grab forks forks without um without um ever getting into the deadlock scenario ever getting into the deadlock scenario so we can't say like hey everybody just so we can't say like hey everybody just grab your left fork grab your left fork uh let me erase all this stuff i don't uh let me erase all this stuff i don't know why i made arrows know why i made arrows these guys we can't say everybody just these guys we can't say everybody just grab your left fork or when i grab your left fork or when i when i think about it i think of um when i think about it i think of um grabbing the grabbing the the fork that matches your index so zero the fork that matches your index so zero philosopher grabs zero philosopher grabs zero one grabs one two is going to grab two one grabs one two is going to grab two three is going to grab three four is three is going to grab three four is going to grab four going to grab four the problem with this is they all the problem with this is they all succeed and they all grab their forks succeed and they all grab their forks and so if we want to grab the next fork and so if we want to grab the next fork like now everyone is going to have like now everyone is going to have condition condition so like like um nobody is going to so like like um nobody is going to eat nobody's going to eat eat nobody's going to eat nobody's going to give up a fork or if nobody's going to give up a fork or if they do they're all going to give up they do they're all going to give up the wrong fork so or they're just going the wrong fork so or they're just going to you know to you know pass forks back and forth so because the pass forks back and forth so because the philosophers have an index philosophers have an index what i s what i um decided was that the what i s what i um decided was that the even-numbered philosophers even-numbered philosophers would grab their fork meaning the fork would grab their fork meaning the fork that matches their index that matches their index and the odd numbered philosophers would and the odd numbered philosophers would grab the next philosopher's fork grab the next philosopher's fork meaning the fork that matches the index meaning the fork that matches the index of the next philosopher of the next philosopher so zero grabs zero one grabs one two is so zero grabs zero one grabs one two is going to try to grab going to try to grab two three is going to try to grab two three is going to try to grab four that's the next philosopher four is four that's the next philosopher four is going to try to grab going to try to grab four so like what this is doing is it's four so like what this is doing is it's um um it's guaranteeing that there's it's guaranteeing that there's there is multiple people trying to get there is multiple people trying to get the same forks the same forks and i should add that basically i have a and i should add that basically i have a lock for each of the forks lock for each of the forks so when i say they're trying to grab a so when i say they're trying to grab a fork what i mean is they're trying to fork what i mean is they're trying to acquire the lock acquire the lock that corresponds to that fork so we know that corresponds to that fork so we know zero is going to succeed he's going to zero is going to succeed he's going to grab his fork grab his fork and then he's going to well and then he's going to well two things might happen one possibility two things might happen one possibility is that one succeeds is that one succeeds and grabs fork number two in which case and grabs fork number two in which case philosopher two is going to be left philosopher two is going to be left hanging hanging waiting to acquire the lock and then one waiting to acquire the lock and then one is going to try to grab is going to try to grab fork number one assuming he got two fork number one assuming he got two now simultaneously philosopher zero is now simultaneously philosopher zero is going to be trying to grab it going to be trying to grab it so one of them is going to grab the fork so one of them is going to grab the fork and the other is going to be blocked and the other is going to be blocked but whoever grabs the fork is going to but whoever grabs the fork is going to have two forks have two forks which means they're going to eat their which means they're going to eat their plate of spaghetti and then they're plate of spaghetti and then they're going to put their forks back down going to put their forks back down and release their locks so if one grabs and release their locks so if one grabs it first he's going to eat his spaghetti it first he's going to eat his spaghetti release his locks or sorry if zero grabs release his locks or sorry if zero grabs it first he's going to eat his spaghetti it first he's going to eat his spaghetti releases locks and then one is going to releases locks and then one is going to get unblocked pick up the fork get unblocked pick up the fork and eat it and that that kind of logic and eat it and that that kind of logic is going to apply everywhere is going to apply everywhere so if one if like basically we're just so if one if like basically we're just making sure that making sure that whoever wins one fork will be able to whoever wins one fork will be able to grab the next fork grab the next fork um and that by um and that by by coordinating that even-numbered by coordinating that even-numbered philosophers philosophers grab a different kind of fork than grab a different kind of fork than odd-numbered philosophers odd-numbered philosophers we're making sure that we never get into we're making sure that we never get into the pattern of the pattern of everyone kind of doing exactly the same everyone kind of doing exactly the same thing thing which results in no food getting eaten which results in no food getting eaten because nobody can because nobody can can like overcome the the contention can like overcome the the contention to get both forks um and eat a plate of to get both forks um and eat a plate of spaghetti spaghetti and what it's going to result in is that and what it's going to result in is that like our our maximum throughput we'll like our our maximum throughput we'll get two philosophers eating at the same get two philosophers eating at the same time time so that um so that um yeah so that we can we can complete yeah so that we can we can complete the the task faster yeah so here i'm not locking any locks at the beginning and now i'm thinking of the locks not as mapping to philosophers but as mapping to the forks 0 through five or zero through four and none of them are locked at the start so what we do is we figure out who your next philosopher is and we know who your philosopher is and i'm just referring to these labels for forks so the zero philosopher's fork is zero the next philosopher's fork is one we're going to the first thing we're going to do is try to lock up both forks so we're going to use use um like this this little bit of math is just handling the evens and odds case so we're going to add on to the philosopher's number 1 if it's sorry 0 if it's even so philosopher mod 2 we'll add 0 if it's even and we'll add 1 if it's odd in the in the next line in 22 we're in the in the next line in 22 we're doing the same thing doing the same thing plus 1. so even philosophers try to grab plus 1. so even philosophers try to grab their fork first and then in the next their fork first and then in the next line line they try to grab the next fork odd they try to grab the next fork odd philosophers try to grab philosophers try to grab next fork first then on the next line next fork first then on the next line they try to grab their fork they try to grab their fork and when i say grab i mean acquire the and when i say grab i mean acquire the lock and then yeah then they just follow the same sequence of picking up their forks eating putting their forks back down and then releasing their locks the same locks they grabbed um so yeah i mean maybe this maybe this is a little simpler but you can imagine i mean maybe it's a little harder to imagine how execution simultaneously happens with some philosophers will get by line some philosophers will get by line two philosophers will get by lines 21 two philosophers will get by lines 21 and 22 and 22 without blocking and then they'll eat without blocking and then they'll eat their meal their meal and they'll release their locks and then and they'll release their locks and then the next philosophers will acquire the the next philosophers will acquire the locks locks and they'll eat so yeah that that's pretty much it for test cases what i did for this uh in their example they show you can have or sorry in their constraints they show that n can be between 1 and 60. so if you have very small constraints like this and you know n has to be an integer it's between 1 and 60. obviously the right thing to do is just to test all numbers between 1 and 60. because then you can be certain that you that you have produced the right thing that you have produced the right thing before you submit it before you submit it i think if i submit it again i expect i think if i submit it again i expect the time will vary i don't think 90 the time will vary i don't think 90 percentile for speed is going to be very percentile for speed is going to be very consistent consistent so yeah so we're a bit slower i think so yeah so we're a bit slower i think it's just going to be it's just going to be a little random depending on you know a little random depending on you know how the leak code servers are running how the leak code servers are running but when i ran it you know with the old but when i ran it you know with the old version one philosopher at a time version one philosopher at a time i think it was definitely slower i was i think it was definitely slower i was getting like six percentile speed getting like six percentile speed 20 percentile speed and now i'm getting 20 percentile speed and now i'm getting you know you know 80 90 60. um 80 90 60. um i think this is the solution that most i think this is the solution that most people must have so people must have so everyone's everyone's speed is going to everyone's everyone's speed is going to be kind of similar um be kind of similar um yeah if you if you like this video let yeah if you if you like this video let me know by clicking the like button me know by clicking the like button um if you want to see more elite code um if you want to see more elite code problems solved and kind of walked problems solved and kind of walked through like this through like this you should subscribe thanks for your you should subscribe thanks for your time bye | 2024-03-19 11:52:18 | 1,226 | LeetCode 1226 - The Dining Philosophers |
|
Oe0nSS7XWY8 | good evening everyone today we are going to do the problem of the day for 8 to do the problem of the day for 8 January 2023 that is question number 149 January 2023 that is question number 149 maximum points on a line they are saying maximum points on a line they are saying that we are given an array of points we that we are given an array of points we have a array of some points where points have a array of some points where points indicates the x coordinate and y indicates the x coordinate and y coordinate on a x y plane and we have to coordinate on a x y plane and we have to return the maximum number of points that return the maximum number of points that lie on the same straight line lie on the same straight line so here they are asking you to find the so here they are asking you to find the number of points that live on a same number of points that live on a same straight line same straight line means straight line same straight line means that they are having a same slope so let that they are having a same slope so let me draw it for you if I draw it for you me draw it for you if I draw it for you this is a straight line okay and if I this is a straight line okay and if I see that this point what will it be X1 see that this point what will it be X1 y1 y1 see and here it will be X2 Y2 see and here it will be X2 Y2 so these two points are on the same line so these two points are on the same line okay that means their slope is same and okay that means their slope is same and CM goes for a third Point here that will CM goes for a third Point here that will be X3 Y3 so they are all having the same be X3 Y3 so they are all having the same slope slope so if I write the formula for you let us so if I write the formula for you let us consider X1 y1 X1 y1 as the first point consider X1 y1 X1 y1 as the first point x 2 Y 2 as the second one and X3 Y3 as x 2 Y 2 as the second one and X3 Y3 as the third point so for that slope the third point so for that slope formula is y d y by D X you can say that formula is y d y by D X you can say that is tan Theta uh tan Theta and it is is tan Theta uh tan Theta and it is equal to Y2 minus y 1 divided by x 2 equal to Y2 minus y 1 divided by x 2 minus X1 minus X1 okay okay so now for here if I have to find the so now for here if I have to find the slope of between these two points and slope of between these two points and these two points I can write it as Y2 these two points I can write it as Y2 minus y1 divided by minus y1 divided by x 2 minus X1 is equal to x 2 minus X1 is equal to y 3 minus y1 divided by y 3 minus y1 divided by x 3 minus X1 that will be our slope and x 3 minus X1 that will be our slope and if these two points are equal the slopes if these two points are equal the slopes are equal then we can say the points lie are equal then we can say the points lie on the same line on the same line so that is the case here but there is so that is the case here but there is also another case that the parallel also another case that the parallel lines also have same slopes lines also have same slopes if there is a parallel line it would if there is a parallel line it would also have the same slope yes or no the also have the same slope yes or no the angle is same but the point here what we angle is same but the point here what we will do in the approach first approach will do in the approach first approach will be the very basic diet we will find will be the very basic diet we will find a a that will be of O and Cube complexity that will be of O and Cube complexity that we will check with every point the that we will check with every point the slope between these two points the slope slope between these two points the slope between these two points and we will between these two points and we will check whether they are same or not and check whether they are same or not and we will have a counter but that would be we will have a counter but that would be a very Nave approach and the interview a very Nave approach and the interview will ask you to optimize it so there will ask you to optimize it so there will be a n Square approach what we can will be a n Square approach what we can do do um uh let me tell you the first thing um uh let me tell you the first thing that there always exists a one point that there always exists a one point passing through the line and if there passing through the line and if there are two points they will also be passing are two points they will also be passing through the same line through the same line and the case is changing after the third and the case is changing after the third Point okay Point okay so that is our situation here so what we so that is our situation here so what we are going to use we are going to use are going to use we are going to use unorder maps unorder maps so in the map what we are going to do so in the map what we are going to do let me show you the code and explain you let me show you the code and explain you the exact points what is happening here the exact points what is happening here now so what we can do the constraints now so what we can do the constraints given are the maximum limits is 10 to given are the maximum limits is 10 to the power 4. so slope can be all slope the power 4. so slope can be all slope can also come out to be 1 by 0 in some can also come out to be 1 by 0 in some cases that is infinity and we cannot cases that is infinity and we cannot Define Infinity to our compiler ion code Define Infinity to our compiler ion code so we are using the out of limit bound so we are using the out of limit bound or you can use intermax as well or you can use intermax as well so here our index is one zero zero one so here our index is one zero zero one maximum number countries are just count maximum number countries are just count variable which will count uh how many variable which will count uh how many points are there on a straight line the points are there on a straight line the maximum one okay and now what we are maximum one okay and now what we are going to use for enter is equal to zero going to use for enter is equal to zero we are creating a loop that will uh we we are creating a loop that will uh we are creating a loop till the last point are creating a loop till the last point and then we are creating a map for every and then we are creating a map for every slope we have to create a map so what we slope we have to create a map so what we are doing here is we are storing on a are doing here is we are storing on a map that here will be our slope and it's map that here will be our slope and it's going to be like this slope and count we going to be like this slope and count we are storing it and hence the for as the are storing it and hence the for as the formula is in divide the slope can also formula is in divide the slope can also be in double okay it can also be in be in double okay it can also be in point point so we are using the double data type so so we are using the double data type so now we are iterating from first Loop now we are iterating from first Loop till the last and the second point is till the last and the second point is coming out to be I plus 1 yes or no and coming out to be I plus 1 yes or no and we are iterating that and the what is we are iterating that and the what is the worst condition we are having that the worst condition we are having that is when denominator is zero that is your is when denominator is zero that is your X2 minus X1 or X3 minus x 1 is 0. so we X2 minus X1 or X3 minus x 1 is 0. so we are dealing with that condition here are dealing with that condition here that if the points are seen that is X2 that if the points are seen that is X2 and x 1 are same or X3 or X1 are same and x 1 are same or X3 or X1 are same then it comes it goes to Infinity slope then it comes it goes to Infinity slope will be Infinity so we are uh uh create will be Infinity so we are uh uh create uh we are initializing it in the map as uh we are initializing it in the map as outer bound outer bound and if it is not the case then we can and if it is not the case then we can have the slope we are getting the slope have the slope we are getting the slope we are storing the slope in our map and we are storing the slope in our map and we are having a counter for it as well we are having a counter for it as well and now when finally we are done with and now when finally we are done with that we are checking what's the maximum that we are checking what's the maximum value count is maximum or X second Plus value count is maximum or X second Plus One X second one plus mean One X second one plus mean that the second point in the map we that the second point in the map we showed you now discount and Y plus when showed you now discount and Y plus when you ask because the counting starts from you ask because the counting starts from 0 but we have to and if you are counting 0 but we have to and if you are counting the points we will start from one two the points we will start from one two three four not zero one two three so three four not zero one two three so that's a second X plus one so that is that's a second X plus one so that is our overall approach so if I have to our overall approach so if I have to summarize it I will say if I have to summarize it I will say if I have to find this points on the line I will say find this points on the line I will say that if the slopes are equal then the that if the slopes are equal then the points lie on the same line and I have points lie on the same line and I have to calculate the number of points that to calculate the number of points that is our approach and we calculate that by is our approach and we calculate that by using unordered Maps okay using unordered Maps okay and for the parallel line question what and for the parallel line question what is happening if you found the flow is happening if you found the flow between these point the angle is between these point the angle is changing so that will be a different changing so that will be a different slope value and it hence it is not slope value and it hence it is not interfering with or the counter value interfering with or the counter value okay okay so that is how we are getting the number so that is how we are getting the number of points lying on the same line let me of points lying on the same line let me just run the code for you and check just run the code for you and check whether it is working or not uh case one is passed case 2 is fast let me and yes it is working and yes it is working so the time complexity for this question so the time complexity for this question will be o n Square which I have shown will be o n Square which I have shown you the solution and the space you the solution and the space complexity you can comment down in the complexity you can comment down in the comment section if you want me to solve comment section if you want me to solve another question you can drop a comment another question you can drop a comment on it and on it and please like and share the video please like and share the video And subscribe to get more updates on And subscribe to get more updates on lead code questions thank you for lead code questions thank you for watching bye | 2024-03-21 13:05:00 | 149 | 149 Leetcode | Max Points on a line | DSA buddy |C++ | Leetcode daily challenge |
|
YIKN6xeXQ7Y | hello everyone welcome back to lead coding coding the question which we are going to solve the question which we are going to solve today is delete node in a linked list today is delete node in a linked list the problem description is write a the problem description is write a function to delete a node in a singly function to delete a node in a singly linked list linked list you will not be given access to the head you will not be given access to the head of the list instead you will be given of the list instead you will be given access to the node access to the node which is to be deleted it is guaranteed which is to be deleted it is guaranteed that the node to be deleted is not the that the node to be deleted is not the tail node in the list tail node in the list so first of all before jumping into the so first of all before jumping into the solution solution let us look at the structure of the node let us look at the structure of the node there are two data members the first one there are two data members the first one is an integer which contains the value is an integer which contains the value of the node of the node the other one is a pointer of the type the other one is a pointer of the type list node it contains the address of the list node it contains the address of the node which is node which is just next to it and then there is a just next to it and then there is a constructor constructor which is going to initialize the value which is going to initialize the value with the given x and the pointer as with the given x and the pointer as null this is the initialization list so the structure something like this something like this there's an integer value and there is a so this is the format in which we have so this is the format in which we have our linked list our linked list this denotes a particular node in the this denotes a particular node in the linked list linked list and this pointer points to the address and this pointer points to the address of the node which is next to it and of the node which is next to it and similarly this is going to point similarly this is going to point to another node so this is how the to another node so this is how the structure of the linked list is structure of the linked list is now let us denote these nodes now let us denote these nodes using circles so let us say using circles so let us say this is our head and we are not given access to the head node this node from the given linked list this node from the given linked list we are given access directly to this one now okay let us say that for more clearity we have one more node all right so if you want to delete this all right so if you want to delete this node node then what we can do is we can directly then what we can do is we can directly connect connect the node which is previous to this node the node which is previous to this node and change the pointer of this and change the pointer of this to next of the node which you want to to next of the node which you want to delete delete so this way the node so this way the node you want to delete gets eliminated from you want to delete gets eliminated from the linked list the linked list and we can store it inside a temporary and we can store it inside a temporary variable variable and simply use the delete function to and simply use the delete function to clear the memory clear the memory but in this case we are not given access but in this case we are not given access to the node which is previous to the to the node which is previous to the node which you want to delete node which you want to delete so this is not going to work so this is not going to work but what instead we can do is but what instead we can do is let us say they have the value 1 2 3 let us say they have the value 1 2 3 four and five and we are asked to delete four and five and we are asked to delete the node which contains the value three the node which contains the value three now what we can do is as we have access now what we can do is as we have access to this particular node to this particular node we can swap the value of this to the we can swap the value of this to the next of this next of this as we have access to the node number as we have access to the node number three we will be having access to node three we will be having access to node number four and five as well number four and five as well and uh whatever is previous to three we and uh whatever is previous to three we will not be having access to those nodes and the next of three is four so we have and the next of three is four so we have access to four as well access to four as well we can swap the values so four will come we can swap the values so four will come here here three will go there and now as we have three will go there and now as we have access to access to 4 and we want to delete 3 we can 4 and we want to delete 3 we can do the attachment as this and we can store this inside a temporary variable before attaching 4 with 5 and we can simply so let us try to see the same using the code this node denotes the address of the node which you want to delete so let us first swap the values nodes value with the value next node and now we want to next node and now we want to store into temp store into temp nodes next now we can change the connections how we are going to do this nodes next is equal to nodes next next and then delete temp to clear the memory notes next is equal to notes next is equal to nodes next next it is giving us correct answer let us it is giving us correct answer let us try to submit this and it works so in terms of space complexity as we have just used uh two variables to uh one one in the swap function and another one the temporary variable which you want to delete so this is basically a constant space solution in terms of time we are just doing a swap which is a constant time operation and then we are just changing the connections and then delete so these are all constant time operations and the time complexity will be big often as so this is it for the solution if you so this is it for the solution if you like the video please subscribe to the like the video please subscribe to the channel channel thank you | 2024-03-22 11:29:08 | 237 | Leetcode 237. Delete Node in a Linked List |
|
Nf2J7sJOXpo | hey hey everybody this is larry this is day 20 of the lego daily challenge hit day 20 of the lego daily challenge hit the like button hit the subscribe button the like button hit the subscribe button join me on discord let me know what you join me on discord let me know what you think about today's prom actually that's think about today's prom actually that's funny because i was just looking at this funny because i was just looking at this problem because i've been working on a problem because i've been working on a on um on um on a binary search uh video um so this on a binary search uh video um so this one i i think maybe to be honest i might one i i think maybe to be honest i might keep it a little bit short just because keep it a little bit short just because i might i might um end up using this problem anyway um um end up using this problem anyway um so i actually do know how to solve this so i actually do know how to solve this as a result um because it wasn't as a result um because it wasn't it's really commercial dental but um it's really commercial dental but um but yeah uh i do have one minor big news but yeah uh i do have one minor big news which is that i have a new keyboard so which is that i have a new keyboard so if it's a little bit cracky crack let me if it's a little bit cracky crack let me know how loud it is if it's or whatever know how loud it is if it's or whatever but yeah but for this problem um but yeah but for this problem um yeah i mean i'm not gonna go over it too yeah i mean i'm not gonna go over it too much to be honest um because i'm gonna much to be honest um because i'm gonna have a video coming hopefully soon to have a video coming hopefully soon to to kind of just go over how i sell to kind of just go over how i sell binary search forms because i solve binary search forms because i solve every binary search form more or less every binary search form more or less the same the same um and i feel like um and i feel like there are some details that like you know i'm recording these live and these are kind of like almost like a daily relog type thing of me solving these problems um and and one thing that i always find a little bit hard to do to be honest as part of these videos is to kind of figure out like you know the balance between going really deeply into a problem or or you know um or not as much right but because at this point i probably have like literally a hundred videos on binary search and it is like like i i ask myself what is the um what is the returns on me explaining the same binary search for example as an example um every video like as in depth as possible right like i'm okay with being in depth but at a certain point i'm just doing the same thing and and you know maybe i could do a special video on on this instead and these are kind of things that i've been thinking about so this one um this video may be a little bit shorter and maybe not as detailed but but the ideas that will still be here and we'll figure it out um let me know what you think in the comments about my keyboard my my binary search way concern dental uh problem uh and stuff like that so yeah um cool let's get started so yeah um actually i don't i remember looking this up or looking this problem but i actually don't remember the details so it'll still be live a little bit um but yeah and maybe this is actually a good um warming or not warming up a preparation for that video but yeah so coco loves bananas as we all like bananas uh the end piles the i power has powers you guys have gone and come back can decide you you challenge somebody else and you came if that one doesn't use all of that instead without you anymore this hour okay um so yeah so one thing the first thing to notice for this problem is that um maybe i won't use this one for the video just because it's a little awkward to kind of be so close about it but the first observation about this problem is that it doesn't matter which order um the order you need to pause in right so you have something like this and then um oh you have to find k okay but let's oh you have to find k okay but let's just say you have given uh you're trying just say you have given uh you're trying to find well you're trying to say four to find well you're trying to say four at a time right um it doesn't matter at a time right um it doesn't matter whether you get to three and uh from whether you get to three and uh from it doesn't matter where you eat from the it doesn't matter where you eat from the three first and then to six twice and three first and then to six twice and then the seven twice and then eleven then the seven twice and then eleven three times right um because the order three times right um because the order doesn't matter it only matters is that doesn't matter it only matters is that in total it it in total it it sorry still adjusting to the keyboard sorry still adjusting to the keyboard locations of stuff i'm so used to my old locations of stuff i'm so used to my old keyboard you've stood for like keyboard you've stood for like let's say almost 10 years so yeah so now let's say almost 10 years so yeah so now you have one day you have one day two days two days and three days right two days two days and three days right and this of course sums to to eight days um and it doesn't matter whether you know you you interlock or what or whatever um and you could kind of prove to yourself that this is the case um this will take eight days right so here um one thing that i would like to do is to write a function of okay let's say we have the answer can we figure out a way to see how um whether um we can finish in h days right and you know there's given different ways naming it but uh yeah so then the first thing i would say is let's say we have some target um [Music] i probably will explain this better in the binary search video not not to spoil that a little bit but yeah um but let's say we have some target that we're trying to target and and i do use this okay i don't want to be too sloppy on this one i do want to do a technique called binary search on the answer um and and basically the the answer can be any number from [Music] from let's see right let's think figure that out the answer in this case can be this 10 to the fourth of each power can be 10 to the ninth um so that means that uh the number of total piles um yeah yeah yeah the number of total piles will be yeah the number of total piles will be 10 to the 13th right so that means that 10 to the 13th right so that means that okay so that means that the answer can okay so that means that the answer can be from be from that is it zero or one one of those two that is it zero or one one of those two say for now it doesn't matter as much 0 say for now it doesn't matter as much 0 to 10 to the 13. um so then here to 10 to the 13. um so then here we know that we know that our sketch of an algorithm this is going our sketch of an algorithm this is going let's say we have this magic function let's say we have this magic function which we will implement which we will implement and it's going to take a loop through and it's going to take a loop through that away every time then this is going that away every time then this is going to be o of n times to be o of n times times log of times log of the the universe is what i call it which the the universe is what i call it which is the size of this thing is the size of this thing right right which is of course roughly speaking um which is of course roughly speaking um i don't know like oh well it's i don't know like oh well it's a log of you in this case even for 2 to a log of you in this case even for 2 to the 64 is just 64. right so let's just the 64 is just 64. right so let's just say i'm lazy right now in the math um say i'm lazy right now in the math um and so then this is just going to be and so then this is just going to be roughly speaking o of n times 64 and of roughly speaking o of n times 64 and of course n is 10 to the four so this is course n is 10 to the four so this is the math for me to kind of figure out 10 the math for me to kind of figure out 10 times uh 10 to the six times uh 10 to the six ten to the fourth times 64. so this is ten to the fourth times 64. so this is roughly roughly an estimate for me to figure out whether an estimate for me to figure out whether i need to uh i need to uh um um whether this is going to run in time whether this is going to run in time right right okay so now that we have that um you okay so now that we have that um you know we do a feasibility study and then know we do a feasibility study and then we go okay let's say we are given a we go okay let's say we are given a target target what is the um what is the um you know how you know and you can you know how you know and you can implement this in any way but the way implement this in any way but the way that i would implement this function um that i would implement this function um and i always label it good maybe it's and i always label it good maybe it's not a a good name for it per se but not a a good name for it per se but but uh maybe you could count or like you but uh maybe you could count or like you know is getting speed enough right let's know is getting speed enough right let's say this is say this is let's say we're given this target speed let's say we're given this target speed and is this speed enough and and is this speed enough and so then now we just count the number of so then now we just count the number of days where days is zero for x in piles days where days is zero for x in piles uh days we added which is of course uh days we added which is of course equal to equal to well x x divided by the speed that we're eating it and then we want to round up and of course in rounding up in um in discrete is this is how i would do it for rounding up in the screen and then oops and i'm still not using this new keyboard they're like page up buttons and a weird price maybe i need a different keyboard but yeah um but yeah um and then now and then now this is enough if the number of days this is enough if the number of days that it takes to eat this is smaller that it takes to eat this is smaller grade or less than h right so okay so grade or less than h right so okay so now we have this and this is the now we have this and this is the function that we have right um i think function that we have right um i think maybe i want to give this a try where i maybe i want to give this a try where i explain this backwards right where okay explain this backwards right where okay now now we implement this function now now now we implement this function now instead of kind of asking um the first instead of kind of asking um the first true the first or the last true or true the first or the last true or whatever i have this function that i whatever i have this function that i know i want to binary search on so then know i want to binary search on so then the question is what am i looking for the question is what am i looking for right am i looking for and i actually right am i looking for and i actually don't use these terms because i don't don't use these terms because i don't think of it this way per se but think of it this way per se but but i think that's what a lot of people but i think that's what a lot of people do right so then i go okay um let me let do right so then i go okay um let me let me take a look at this property of this me take a look at this property of this function which is that okay let's say function which is that okay let's say speed is equal to one what does that speed is equal to one what does that mean well if speed is equal to one then mean well if speed is equal to one then then this will be a lot of days so it's then this will be a lot of days so it's not gonna it's probably gonna start off not gonna it's probably gonna start off force and then force and then as as you kind of as as you kind of increase the speed days goes down right increase the speed days goes down right so that means that uh analyzing this so that means that uh analyzing this function function um um as days goes from a big number to as days goes from a big number to smaller smaller smaller this is going to smaller smaller smaller this is going to be we eventually it's just going to be be we eventually it's just going to be first resolution first and then it first resolution first and then it becomes small enough to be true right so becomes small enough to be true right so this is the the function that we're this is the the function that we're given um and this is just analyzing this given um and this is just analyzing this function that we wrote um and of course function that we wrote um and of course there are a lot of ways to kind of there are a lot of ways to kind of represent this in um in the negative way represent this in um in the negative way which we'll talk about in a sec but which we'll talk about in a sec but let's say that we we went this function let's say that we we went this function like this because that's the for me the like this because that's the for me the most intuitive way to write it for you most intuitive way to write it for you you may write it differently right maybe you may write it differently right maybe you're right is this is is the is the you're right is this is is the is the using speed too slow for example it may using speed too slow for example it may look the same and then you would maybe look the same and then you would maybe have a different um operator here or have a different um operator here or something like that right but here something like that right but here so now we're given this function right so now we're given this function right and what do we want from this ends uh and what do we want from this ends uh the question so we read it again maybe the question so we read it again maybe or maybe you already know it without or maybe you already know it without reading it again run the minimum case reading it again run the minimum case such that such that can eat all the bananas in h hours that can eat all the bananas in h hours that means that we want the minimum means that we want the minimum thing where this is true because the thing where this is true because the speed and now this if the speed is good speed and now this if the speed is good enough then we do eat all the bananas so enough then we do eat all the bananas so that means that we want the first true that means that we want the first true say right so we're trying to find say right so we're trying to find oops oops so we're trying to find this position so we're trying to find this position right so right so um um yeah maybe that's good enough for now uh yeah maybe that's good enough for now uh for you know for you know find this right so that's basically our find this right so that's basically our goal and of course like i said you can goal and of course like i said you can use the vocabulary of this is first use the vocabulary of this is first truth i don't really think of it this truth i don't really think of it this way per se and you'll see why in a way per se and you'll see why in a second um so then now we declare our second um so then now we declare our ranges um one thing that i sometimes is ranges um one thing that i sometimes is a little bit sloppy about is about the a little bit sloppy about is about the ranges um about the lower bound and ranges um about the lower bound and upper bound uh it's very intuitive to to upper bound uh it's very intuitive to to oops uh do something like you know let's oops uh do something like you know let's just say this but just say this but but but depending on the way you write it it is depending on the way you write it it is critical to have um and critical to have um and maybe the way that i would like to write maybe the way that i would like to write it anyway is to at least have one force it anyway is to at least have one force in the range and one true in the range in the range and one true in the range so that things can be um resolved a so that things can be um resolved a little bit easier right um and what i little bit easier right um and what i mean by this is that let's say you have mean by this is that let's say you have a a equivalent function where equivalent function where you know running it for all your range you know running it for all your range if you get ch if you get ch to choo to choo um in a weird way um in a weird way you don't know that this is the first you don't know that this is the first truth because in theory maybe if you truth because in theory maybe if you started too late um there were more started too late um there were more choosing to the left right um so that's choosing to the left right um so that's why i don't like doing it this way why i don't like doing it this way or that's why i want to make sure that or that's why i want to make sure that there is a force so that there is a force so that you know and sometimes that will take us you know and sometimes that will take us out of balance maybe it will take us to out of balance maybe it will take us to negative one or something i don't know negative one or something i don't know if that's the k well in this case i if that's the k well in this case i don't think that makes sense because um don't think that makes sense because um if you have a heating speed of zero this if you have a heating speed of zero this would go outbound so actually we won at would go outbound so actually we won at least one um and then maybe we have to least one um and then maybe we have to take care of it a little bit but ideally take care of it a little bit but ideally this is what i would like to do and of this is what i would like to do and of course the other the other case is true course the other the other case is true as well right if we have all fours how as well right if we have all fours how do we know that do we know that you know this you know this this value is going to be true we don't this value is going to be true we don't right so that's why i want to make sure right so that's why i want to make sure at least one force and one true is in at least one force and one true is in the bound so that we can guarantee the bound so that we can guarantee ourselves that's where i make the most ourselves that's where i make the most mistakes to be honest um and here um mistakes to be honest um and here um yeah so left is equal to one means that yeah so left is equal to one means that we're almost guaranteed to have a force we're almost guaranteed to have a force except for if except for if h is like really big i guess um so in h is like really big i guess um so in this case actually we're really this case actually we're really um yeah in this case i guess we're actually um a little bit sketchy on this part you can maybe have a have a edge case of okay let's start at zero uh if our speeding z speed is zero then you could say maybe if theta is equal to zero we have some infinity value which will just have like i don't know something really big right um so that oh uh and this is less than h of course um which means that uh i'm actually pretty okay with the home keys on this new keyboard but but they're like arrow keys and stuff like that i still have to get used to because it's a little bit different layout um but yeah uh and of course this ideally should be four so we just return force so that basically saves us time here to kind of figure it out so we always have a force in the beginning and and given a fast enough speed this is always going to be true so i think i think maybe this should be good enough but maybe we can add add like a small number or something right um because that's the the most number of things here or something like that um okay so then now we um this is a thing where you know you see some people as as you know this or or some or something like this um the difference is that one of them is in exclusive brown and the others inclusive bound um i'm not going to go over the rice and house because i'm going to save that for that video um it's going to be a longer video and it will have a lot of details hopefully but um but yeah but uh but this is an inclusive bound which leads to a couple of meaning right um because this is an inclusive bound that means that this is our range which means that every number inclusive of the left number and the right numbers out range that means that this becomes false when left is it goes to to right we terminate right terminate so we terminate when this happens so so we terminate when this happens so that that means that the answer is going that that means that the answer is going to be to be left right left right um because um because because when we terminate when it because when we terminate when it happens um happens um we terminate when this happens we terminate when this happens which is another way of saying now which is another way of saying now left right me implies left right me implies left is equal to to left which means left is equal to to left which means that that there is only one number in the range there is only one number in the range our correct answer so that's why i write our correct answer so that's why i write it this way right um and then here we just have mid as you go to left plus right over two um at least that's why how i write it to begin with um we'll go over some nuances you know in the future but this is just the midpoint of these two um we in this case we round down because it is discrete and yeah um and to facilitate so that now we go oops if good of mid um and then now we this is the part where we kind of figure out how to answer this right so let's say we have this thingy and the only two scenarios right one is okay let's say if this is mid is here if mid is here if this is okay actually if mid is here if this is okay actually i i wrote it like this first so it i i wrote it like this first so it doesn't really matter but let's say mid doesn't really matter but let's say mid is here then because this is you know is here then because this is you know this is true what happens if this is this is true what happens if this is true if this is true true if this is true then mid is a possible answer right then mid is a possible answer right if true mid is a okay actually let me if true mid is a okay actually let me write it here instead right write it here instead right uh mid is a possible answer uh mid is a possible answer um to our solution so we don't want to um to our solution so we don't want to eliminate it so we want to keep this in eliminate it so we want to keep this in the range um and also the other thing is the range um and also the other thing is that okay if mid is good what does that mean that means that everything to the right of the mid is also going to be good as we kind of have this diagram um everything to the right of the mid uh or higher than mid bigger than mid bigger than mid is also good so but in this case of course we want to get the first true in this case right we're looking for this so that that means that everything to the right of this thing cannot be first true by definition because the current value is already the first true or it's not the first truth but it is already by definition this is a possible first true that means that everything to the right of it is not for for is true so that means that we want to move the range um you know from from here and here to to here so here all we have to do is do right is equal to mid right um and then else what happens um yeah that means that right is inclusive still it write is still a possible answer that's right right is equal to mid and then now we move to left in that case in theory um okay because we basically chop off everything to the right of mid um okay and then now the other thing is okay what if mid is false right if mid is force then one thing right well two things mid is not a possible and also and also um everything to the um everything to the um um well just a little bit awkwardly well just a little bit awkwardly the page up key is too close to my the page up key is too close to my to my backspace key yeah and then now every so now every eye so now every eye smaller than smaller than mid is also mid is also uh not good right uh not good right so now so now mid is no good and everything smaller mid is no good and everything smaller than mid is no good so we want to move than mid is no good so we want to move left which of course used to be here say left which of course used to be here say um we'll move left okay let's actually um we'll move left okay let's actually maybe i'll draw it here instead oops maybe i'll draw it here instead oops so let's say this is left right now we so let's say this is left right now we want to move it to here because we know want to move it to here because we know that everything to the left is not a that everything to the left is not a good answer and of course mid is also good answer and of course mid is also not a good answer so then that left is not a good answer so then that left is equal to mid plus one so that's equal to mid plus one so that's basically the idea behind this and basically the idea behind this and that's pretty much it that's pretty much it we run the code oh did i not define oh i change i usually use the the function name good but i forgot that changes for this case uh cool so this looks good that's one of the different cases um and that's pretty much it i mean we did the complexity at the beginning so i'm not gonna go over it again um but yeah but this is a good warm up to my binary search video i suppose i actually haven't solved this before huh i it feels very familiar to another problem that i solved or many other ones so i don't know but yeah but it turns out i haven't solved this before so it's a good idea but yeah um that's yeah that that's basically all i have um yeah that that's basically all i have um let me know what you think let me know what you think you could hit the like button hit the you could hit the like button hit the subscribe button join me on discord subscribe button join me on discord leave me a comment in the comments if leave me a comment in the comments if you really want to see a binary search you really want to see a binary search video i think i'm going to end up doing video i think i'm going to end up doing it but you know you never know so you it but you know you never know so you know know put some likes if you really want that put some likes if you really want that to happen to happen uh yeah uh yeah that's all i have with this one stay that's all i have with this one stay good stay healthy to good mental health good stay healthy to good mental health i'll see you later bye | 2024-03-22 17:23:46 | 875 | 875. Koko Eating Bananas - Day 20/31 Leetcode January Challenge |
|
NEeqvv464k8 | okay it's the best time to buy and sell stock stock elite code question one two one so elite code question one two one so you're given an array of prices where you're given an array of prices where price i price i is the price of a given stock on life is the price of a given stock on life day you want to maximize your profit by day you want to maximize your profit by choosing a single day to buy one stock choosing a single day to buy one stock and choosing a different day in the and choosing a different day in the future to sell that stock return the future to sell that stock return the maximum profit you can achieve from this maximum profit you can achieve from this transaction if you cannot achieve any transaction if you cannot achieve any profit return zero what we need to do is profit return zero what we need to do is we need to we need to return return max max profit when anything concerns max profit or an optimal what we usually go for is dynamic programming so in this example what we need to do is we need to find the smallest value so in this case it's one and then just determine where the next largest value is in this case we can easily see that it's six and then we just return that profit which is five the difficulty comes in when trying to program that out so the best way to look at it is if you draw it out okay so here's the graph and what i've done is i've plotted each point so we have seven one five three six and four and the points that we really need to take into consideration is this point and this point so we need to assign a variable to this point let's just call it current min and then with this let's just call it current max right so with this problem what we can do is we can kind of set to this value here so to the first price to this value here so to the first price in the array so that will equal seven in the array so that will equal seven and then current max and then current max we can set to zero because what we're we can set to zero because what we're going to end up doing is we're going to going to end up doing is we're going to end up returning this and remember as it end up returning this and remember as it said in the question if you cannot said in the question if you cannot achieve any profit you need to return achieve any profit you need to return zero so starting off at zero is great zero so starting off at zero is great because it covers that and then what because it covers that and then what we'll do is we'll loop through the we'll do is we'll loop through the prices right so we'll look through the prices right so we'll look through the prices and we'll update the current min prices and we'll update the current min and the current max and the current max so at this point so at this point the current min is seven current max at the current min is seven current max at initial position is going to stay zero initial position is going to stay zero right so then we move on to the next one right so then we move on to the next one current min current min is currently seven is currently seven what we'll do is we'll change that to what we'll do is we'll change that to one because one is definitely smaller one because one is definitely smaller than seven than seven and with current max what we can do and with current max what we can do leave that at zero because we haven't leave that at zero because we haven't got anything to compare it to yet got anything to compare it to yet because this is the new current min so because this is the new current min so we move along to five now current we move along to five now current minimum is still one so this is where minimum is still one so this is where the interesting part is in order to get the interesting part is in order to get the current max here is we take this the current max here is we take this point take the price at this point point take the price at this point and we minus and we minus the current min the current min so it's going to be five minus one and so it's going to be five minus one and then we do this consecutively throughout then we do this consecutively throughout so three is going to give us two so what so three is going to give us two so what we need to do is we need to work out the we need to do is we need to work out the maximum current max is going to be equal maximum current max is going to be equal to math current current max and the current value we're on minus the minimum so it would be prices at i minus min or current min sorry and that'll be the comparison there so this is the dynamic approach here so we're always using previous values in order to computate the current max so then we'll move along we'll go to six and we'll subtract one from that and that becomes the new max because the current max is four six minus one is five five is greater than four so five goes there move along four minus one is three so that doesn't matter and then we just return this value and that is the answer we're looking for so let's jump into the code and see how it's implemented okay so we need to set the variables for the current min and current max so current min is equal to prices at zero so the first value of prices so we can start the comparison and then the current max is set to zero and the reason for this is because the question asks us that if we don't find a maximum profit return zero and at the end we're going to be returning current max so that covers us there we go to the last value we go to the last value and then within the for loop we are just and then within the for loop we are just going to be updating current in going to be updating current in and current max and current max so current min is the minimum and then current max and then current max is going to be the maximum is going to be the maximum between current max between current max and prices are and prices are i minus current minimum i minus current minimum now in terms of time and space now in terms of time and space complexity we've only got one loop or complexity we've only got one loop or one pass over this entire array one pass over this entire array so that's going to be o of n so that's going to be o of n and space complexity is going to be one and space complexity is going to be one constant space because we aren't constant space because we aren't allocating any extra space and that allocating any extra space and that should hopefully run okay so let's pass let's submit it | 2024-03-21 11:09:03 | 121 | Best Time To Buy And Sell Stock - LeetCode 121 - JavaScript |
|
Ex9mDGK17M4 | Hello gas, how are you all so while discussing this question, it has been who will have higher number in the last, we have to find out, if there are chances, then It's time to It's time to It's time to happen, so we have to return true, happen, so we have to return true, or Jal, that name is Length - 1, this is right, most Erickson, light, most. Whoever is going to choose, he will give his most. Whoever is going to choose, he will give his score. score. score. di game aur when dewar is no more element jab sare element player one Yadav player tu jab sare element player one Yadav player tu le liya hoga [ That usam tha That usam tha playing optimumlay meaning apna apna it means ultra in the game and That both are playing correctly That both are playing correctly That both are playing correctly means both are right and that no one is taking a wrong step, that both of them taking a wrong step, that both of them are at the same level as both of them and whether he can win in that are at the same level as both of them and whether he can win in that or not, it remains to be seen whether player one can win. or not, it remains to be seen whether player one can win. No, if player one can win then No, if player one can win then we have to return true otherwise we have to burn it so we have to return true otherwise we have to burn it so player here who is player one is player here who is player one is going to take the first turn if it is a game then it will be going to take the first turn if it is a game then it will be player one's turn first so player one will either player one's turn first so player one will either player one's turn first so player one will either what am I doing what am I doing here 3 you and one player one is going to have first turn what will happen and in the last 1002 will be left then what will player one do with 1002 You thought, you have to do You thought, you have to do You thought, you have to do a hundred. Well, we could have said that we will win all the time only by Well, we could have said that we will win all the time only by taking more numbers. Left is taking more numbers. Left is happening. For this, we have to see the whole game. So let's see this one. What is the If we If we If we can, then two will come in it, how can two, then can, then two will come in it, how can two, then this will happen this will happen here, if we say that here, if we say that its value will be one, the value of player one will be its value will be one, the value of player one will be in this, what else will be left is five and you, plate from here too, then What is how do we solve it, how do we solve it, what is the approach going to be, what is the approach going to be, this is also such a question of game type this is also such a question of game type in which there is less meaning of whether someone can win in the game in which there is less meaning of whether someone can win in the game or not, or not, then this type of question is then this type of question is then this type of question is This is a game strategy question. To solve it, we have to keep two things in mind: when it is player one's turn, it is it means that we have to take max like above, if we are here. like above, if we are here. like above, if we are here. we do, maximum good one, cash was we do, maximum good one, cash was taken, taken, fiber, you are a player, you are five, you are fiber, you are a player, you are five, you are five, why is it so much, what does it mean, what does flair Gan have, You will have You will have You will have less turn, when it is your turn, the player will less turn, when it is your turn, the player will come to us. Hey kid, what will he do from minus one and if he is taking i, then if he here what did we do in this, and what happened here, here There should be a loss, yes, which option can be correct, whether we will take player one's left or right and make plus, if we are with him, then there were so many approaches and this game is a strategy question, in every question, the Simply now, if we say no then what will we do in Simply now, if we say no then what will we do in general, we will take I and jet, we will take general, we will take I and jet, we will take I, we will take its yes and we I, we will take its yes and we will plus the rectangle with it, which will plus the rectangle with it, which means that if we are taking I, then means that if we are taking I, then how will we make it? how will we make it? how will we make it? check the minimum that yes, this is the minimum, how are we doing this, how will we make this different minimum, how will we make the minimum in this one, we will plus it with the rectangle, the minimum which is A, it will be added to the jet. minimum which is A, it will be added to the jet. minimum which is A, it will be added to the jet. and this will be the max of what happened between these two, this will be the max here, here we will find that what we have to do now, what we have to do now is that I is the what we have to do now, what we have to do now is that I is the minimum, which is the minimum which will go from I + 2 to K minimum, which is the minimum which will go from I + 2 to K and I + 1. and I + 1. and I + 1. we will plus the value of the lake in which the minimum will come with I and the maximum value that will come from it will be the score of p1, so this will be p1. How to get the score of p2? with the score of p1? you all to watch the code from the beginning, if you understand it then try the code once yourself, if even after that it is not working, then I have put a video for the code for you further and can So I hope So I hope So I hope that all of you have tried to code once and if it is not possible then it does not matter, and if it is not possible then it does not matter, we who code here we who code here do it, so as we saw in Across, What do we have to do? What do we have to do? The What do we have to do? What do we have to do? The first index will be taken, the last first index will be taken, the last index will be taken once, what can happen to the minimum count p1, we have to find out the We We We will see what is the value of A will see what is the value of A and whatever will be the and whatever will be the maximum between them, we will store it in it, that will maximum between them, we will store it in it, that will be the score of p1, if we know then what will we do, we will find the score of p2, minus one, okay do. this is the code, but what do this is the code, but what do we have now, what do we do now, if we create a we have now, what do we do now, if we create a function for p1 score, then for this we create these p one we will we will take I here and see once Jai, so that's why mean here. so that's why mean here. so that's why mean here. [music] [music] is tax score will be name will be Jai going on here is to i take score i take score and will be which will be aids its will be got will be stored after that stored after that stored after that do with p2, we will make it equal to p1 and we will check whether p one is greater than A or equal or equal to A, if it is A then well and good return true, will it be true or If there is a this was this question and it was said that yes, question like the player given and question like the player given and who among these is going to win, who among these is going to win, in this question, in this question, put this question with a blindfold and this approach, okay so for today. put this question with a blindfold and this approach, okay so for today. put this question with a blindfold and this approach, okay so for today. everyone has understood then see you in the next list code question, till then bye. | 2024-03-22 15:36:08 | 486 | 486 Predict the Winner || Leetcode 486 |
|
4AyrReJ9jFI | welcome back for another video we are going to do another vehicle we are going to do another vehicle question question the question is the question is 22a 22a summary summary ranges you are given a salty unique integer array nonce a range ap is set of own integers from a to b inclusive we don't smell this sorted list of ranges that cover all numbers in array exactly that is each element of nouns is covered by exactly one of ranges and there is no integer x such that x is in one of ranges but not in nouns each range a b in this should be output as a to b if a is not equal to b a if a equal to b for example one nouns is 2 1 2 4 the output is the output is g two two g two two four two five four two five seven the ranges are g two becomes zero to 2 4 5 becomes 4 to 5 7 7 becomes for example 2 for example 2 nouns is nouns is 0 0 2 2 3 3 4 4 6 6 8 8 9 9 the output the output is is 0 0 2 2 4 2 2 4 6 6 8 2 9 8 2 9 the ranges are the ranges are 2 0 2 0 becomes 0 becomes 0 2 2 4 becomes 4 becomes 2 2 4 2 2 4 6 6 6 6 becomes becomes 6 6 a a nine nine because because a two nine a two nine four constraints four constraints all the values of nouns are unique all the values of nouns are unique nouns is sorted in ascending order now let's work through the code arrange covers consecutive elements if two adjacent elements have difference larger than one they do not belong to sand range the array is sorted out without duplicates therefore two adjacent elements have difference either one or larger than one if the difference is one they are in the same range else they are separate range we use two indices for each element we check if it extends the column range if not we also need to put less branch we also need to put less branch into the list into the list time capacity is time capacity is o n o n space capacity is 0 1. and the solution works thank you if this video is helpful please like this video and subscribe to the channel | 2024-03-22 11:06:50 | 228 | Summary Ranges - LeetCode 228 - Java Solution |
|
vlrxs-LPni4 | it is very popular [music] solution bhi patna hota slogan fast point based question hai linked list cycle tu theek hai liquid mein 142 medium level questions and everyone knows This This This is the approach that was taught in college too, to is the approach that was taught in college too, to detect cycles, so it is detect cycles, so it is not me but the company, it is okay, I have not me but the company, it is okay, I have not written all of them, you will get not written all of them, you will get all the companies in the description, either go to my getup all the companies in the description, either go to my getup profile and profile and click on this question. click on this question. click on this question. Okay, so let's see the input output of the question and understand what the question is. It is a very simple question that we have given you a link. We have to detect whether there is a bicycle in Linkluf or not. If there Return it. If there Return it. If there Return it. If there is a bicycle then you have to tell where it is. is a bicycle then you have to tell where it is. Neither did the bicycle come here nor the bicycle. Look, you Neither did the bicycle come here nor the bicycle. Look, you are on the starting point of the bicycle. You have to find out from here if there is a bicycle then where it is. No, No, No, I will try to tell you how it happens, I will try to tell you how it happens, but what is more important than that, why does but what is more important than that, why does brother do it less, why is it the brother do it less, why is it the method, which I will tell you now, it is method, which I will tell you now, it is more important then you will understand the process, okay then let's more important then you will understand the process, okay then let's start, if it is start, if it is slow then Understand the Good Force, it will be very simple Understand the Good Force, it will be very simple Understand the Good Force, it will be very simple that you stand here at this point, that you stand here at this point, take it as 'Mother', 'It's okay', name it 'P', take it as 'Mother', 'It's okay', name it 'P', okay, so first you check okay, so first you check whether I have ever seen 'Three' nearby. whether I have ever seen 'Three' nearby. I will make a map. Okay, if there is a map then I will I will make a map. Okay, if there is a map then I will make a set. I have made a set in which I am not make a set. I have made a set in which I am not putting a note or link. Okay, putting a note or link. Okay, so here I have never so here I have never seen three nearby, meaning it has not been repeated, seen three nearby, meaning it has not been repeated, so let's three. so let's three. so let's three. moved the pointer forward. 'Have I ever seen you before, no? Look, you are not in the set, otherwise you are there. Then you moved 'P'. Have I ever seen 'Zero'? Have I ever seen 'Zero'? So also zero. Okay, after that, A went here, A went here, Okay, so have I ever seen -4, I have n't seen, so let's put it here, Okay, after P, the next step will go, so back Look, yes, Look, yes, Look, yes, I have already seen you, that is, I have I have already seen you, that is, I have got the cycle, it is okay, there is a got the cycle, it is okay, there is a cycle, so on whom is the cycle, this is the cycle, so on whom is the cycle, this is the cycle above, the cycle is starting from here, cycle above, the cycle is starting from here, so I will simply note the return of this one, that's so I will simply note the return of this one, that's it. it. it. then it is obvious that our linked list would have looked like this - you would have been zero-4, after that there would have been a tap, otherwise he would have enough but barf force, you write it, do enough but barf force, you write it, do n't miss it friend, practice it. n't miss it friend, practice it. Practice never goes waste. Practice as much as you Practice never goes waste. Practice as much as you can. Write the route four by yourself can. Write the route four by yourself and check it on the approach. Then you will remember what happens in the technique of slow and fast points. The It is there It is there It is there in the starting point and the fast pointer is in the starting point and the fast pointer is also in the head, okay, also in the head, okay, this is called toys on hair, in which what is slow, it will in which what is slow, it will move one point once, the fast one will move it twice, okay, so see. okay, so see. okay, so see. here it is slow, here it is fast, now both are pointing to the head, slow has moved once, okay, fast will move it twice, it came here once, then it will come here, okay, so let me If slow will If slow will If slow will move only once then slow came here move only once then slow came here and what will happen fast will come here then come here and what will happen fast will come here then come here ok ok why came here because why came here because why is there on you near mines four because there was a cycle here and why is there on you near mines four because there was a cycle here and here the pointer is pointing next. here the pointer is pointing next. here the pointer is pointing next. again slow will come here and will move ahead but the fast one will move twice, so see where will fast come, come to zero and then come here, okay and pay attention to one thing, After After After coming and meeting, it is okay, both of them came and met at one place, it coming and meeting, it is okay, both of them came and met at one place, it means it is a cycle, means it is a cycle, okay it is a cycle, then it is okay, we have come to okay it is a cycle, then it is okay, we have come to know that it is a cycle, the cycle has been detected know that it is a cycle, the cycle has been detected and when the cycle has been detected, as long as when and when the cycle has been detected, as long as when It has become It has become It has become equal to fast, so it is known that equal to fast, so it is known that means it is known that brother, it is a bicycle, it is a bicycle, that is why what happened is that the bicycle, that is why what happened is that the password has been changed to one place, it goes round and round, but sometimes but sometimes but sometimes if there is a bicycle then why will we always meet, okay but I will make that in a separate video in which I will explain to you that if there is a bicycle in the link list and we are And if we do fast points, then And if we do fast points, then And if we do fast points, then why will fast and slow always meet at why will fast and slow always meet at one place, okay, so that is a different one place, okay, so that is a different concept, okay, I will make it in a separate concept, okay, I will make it in a separate video, if you want to know, video, if you want to know, then okay, slower, fast, met at one place. then okay, slower, fast, met at one place. then okay, slower, fast, met at one place. means that the bicycle must have been there somewhere. Okay, this thing is clear. Now we have to find out where the bicycle must have been. Mother, the question is the same. If the bicycle is found then it is good. If the bicycle is found then it is good. But So you have to find it, are you okay So you have to find it, are you okay So you have to find it, are you okay and if mother takes fast which is fast which is while walking while walking and if it comes and if mother takes fast which is fast which is while walking while walking and if it comes to the tap to the tap then it means it is not a bicycle, I then it means it is not a bicycle, I will simply check that if my fast which is will simply check that if my fast which is equal to the tap, then brother I equal to the tap, then brother I equal to the tap, then brother I not happened here, here if fast is equal to slow, then I will break my for loop and now what will I do to find out where the bicycle is, so tell me what for this. I will do it, I will take one more point for this, okay, I will take one more read for this, I name it, if you name the entry point, then keep it anything, I will give P, I have after this I don't know what to do, after this I don't know what to do, after this P From here to here, slow from here to here, A From here to here, slow from here to here, A will go. Okay, now see where P and S will be will go. Okay, now see where P and S will be found. Wherever P and S will be found, that will be found. Wherever P and S will be found, that will be my starting point of the cycle, so my starting point of the cycle, so quietly I will return P. quietly I will return P. Return P. Return P. Return P. opening both of them. I will return it to P. Okay, so let me tell you again what I did. As soon as I made the match, I came to know that brother, the bicycle has been Now what will I do, I will Now what will I do, I will Now what will I do, I will leave the S here and take a new point leave the S here and take a new point which I will start from the head. This is the head, which I will start from the head. This is the head, right? I will start from the head and right? I will start from the head and will increase each of them by one. Remember, I will increase one each but it is equal here, that is. Cycle is the starting point of the cycle. Okay, so what happens is that this will be my starting point where P and S meet. Okay, so this is the code. So, write it quickly. I have The The The idea behind the story should be that why P and S are idea behind the story should be that why P and S are matching, I am saying matching, I am saying that brother, that is the starting point, okay, that brother, that is the starting point, okay, proof is needed for that too, so brother, proof is needed for that too, so brother, this is the most important question which this is the most important question which will be asked from you in the interview. will be asked from you in the interview. will be asked from you in the interview. slow and fast points. Go keeping the Intion in mind. So let's see what is the intuition behind it. Why P and S. Where I matched will be my starting point. Okay, so let's understand this. If you have taken this example, If you have taken this example, If you have taken this example, then first of all do what then first of all do what I taught you, slow starts from here, I taught you, slow starts from here, fast starts from here, fast starts from here, slow one will go, it will go here, slow one will go, it will go here, fast two will go, one will go here, fast two will go, one will go here, okay then slow one will do. okay then slow one will do. okay then slow one will do. okay, if two fast ones will do, A will go here, A will go here, okay, if two fast ones will do, A will go here, A will go here, okay then A will go here, then the slow one will go here, let me do a race and if two fast ones will do, then fast will also come here, so what have I fast ones will do, then fast will also come here, so what have I Told that if both of them Told that if both of them Told that if both of them come to one place then it means that the cycle will definitely happen. come to one place then it means that the cycle will definitely happen. Now we know that we have to find out Now we know that we have to find out from where both the cycles started. Before that from where both the cycles started. Before that what I had said was that the pointer named P what I had said was that the pointer named P will start from here from the head and slow down. will start from here from the head and slow down. And we will move P one by one. Okay, so if And we will move P one by one. Okay, so if P is moved one, then P is here. If Slow is P is moved one, then P is here. If Slow is moved one, then Slow is here. If P is moved here, then moved one, then Slow is here. If P is moved here, then Slope is here. If one is moved, Slope is here. If one is moved, then this is here. then this is here. then this is here. met, that is my starting point, this is correct, this is the starting point, so my answer will be three, till now it is clear, but I have to explain why this thing is reducing me, So remember, So remember, So remember, this one was my meeting point, this this one was my meeting point, this red one, this was red one, this was my meeting point, this is where the slow my meeting point, this is where the slow and fast font is, I meet the mother, this distance is the album, it is okay and this cycle is this Which is the starting point, from here, Which is the starting point, from here, Which is the starting point, from here, both of them both of them meet at L2 distance, if both of them meet, then the slow one, which is slow, at what distance is the mobile van plus L2 speed is running, is it slow or fast from here, speed is running, is it slow or fast from here, can be a very pointer. can be a very pointer. can be a very pointer. it must have rotated many times, okay, after that it must have covered L2 here and came near it here, okay, so I believe that it must have done 11 + L2, it must have You must have You must have You must have done the complete round, right, and how many times will it go round, done the complete round, right, and how many times will it go round, mother, let's check the end time mother, let's check the end time and cycle this circle, mother, let's say and cycle this circle, mother, let's say that this many slow one Whatever it Whatever it Whatever it is, it is running at D speed, slow is, it is running at D speed, slow is fine, so the distance covered in slow, if I put it is fine, so the distance covered in slow, if I put it in the throttle, the same amount of fast will come out, in the throttle, the same amount of fast will come out, but I have already put out the fast here, but I have already put out the fast here, see, this one is fine, so see, this one is fine, so what does it mean? what does it mean? what does it mean? i.e. 2 * 11 + L2 must be equal, you are 11 plus N, so you can do it like this, then L1 + L2 will become equal, after mincing it will become so now look at the most important one After that, if you go again then leave it, you are After that, if you go again then leave it, you are marking it, so what is left, you are looking at this portion, child, I am making this portion clear by erasing it again, I am making it clear again by erasing, Which means N means Which means N means Which means N means complete cycle completed, complete cycle completed, multiple times and times, it is ok in that multiple times and times, it is ok in that L2 - I am doing it, ok L2 - I am doing it, L2 - I am doing it, ok L2 - I am doing it, so see will this part be left, will so see will this part be left, will this text be saved and what does this text appear to be equal to? this text be saved and what does this text appear to be equal to? I am seeing it equal to the album, so you I am seeing it equal to the album, so you see this L1 is equal to this distance and this too which came here while walking, so this is my starting point of my cycle, so this is the proof that if I take the mother But But But P and S will be found here. If P and S are found P and S will be found here. If P and S are found then this will be my starting point. then this will be my starting point. We have proved the cycle mathematically. It is okay. You must have seen this We have proved the cycle mathematically. It is okay. You must have seen this in college too. We were in college too. We were told this told this is right. The If If If we do then let's code this, we do then let's code this, okay okay then let's code like this, look, we then let's code like this, look, we will do exactly what the story tells, we will will do exactly what the story tells, we will not do anything extra, okay, so not do anything extra, okay, so what I said that we have to take 2 pointers, let's what I said that we have to take 2 pointers, let's take two pointers, list a little stress take two pointers, list a little stress one. one. one. slow which will be pointing to the head and there will be a fast finder which will also be pointing to the head and simply write for loop until fast is Nal ho end and Nal ho end and Nal ho end and fast is connected only then what have I derived from fast ka next ka next. It is then what have I derived from fast ka next ka next. It is okay to pay attention to the person who is okay to pay attention to the person who is running fast. If you running fast. If you write about his bad condition then you will be safe. write about his bad condition then you will be safe. write about his bad condition then you will be safe. is then you will have to check the next also, it is not equal to tap, it is okay and first of all, write one more thing, there can be two reasons for coming out, either then brother, it is not equal. We would have stopped only then and would have gone out of the way i.e. we would not have found the bicycle, right? If it would not have been equal to slow-fast, and if it would have been equal to slow-fast, it would mean that it is a bicycle and if it is a bicycle, then it would be less of us to search for it. Where is the cycle started from? So what did I say, if P is taken from Ram, then it will start from starting, it will start from head, slow will not be equal, both will keep moving forward, P = P's next because That is, now we have got the bicycle, That is, now we have got the bicycle, That is, now we have got the bicycle, here we fast and brake, so it here we fast and brake, so it means that we have got the bicycle, here means that we have got the bicycle, here we have put the check, okay, so we are definitely going to we have put the check, okay, so we are definitely going to get the bicycle, right, let's do the get the bicycle, right, let's do the next move of slow as soon as we stop and slow down. next move of slow as soon as we stop and slow down. next move of slow as soon as we stop and slow down. comes equal then it will break the vicious loop. At the end if we make return P then we will slow it down. Look at the thing because if both are equal then only the break will happen. Volume is ok, the story told is exactly what is written, nothing extra is ok, it was more important than You understand why the engine is reducing, You understand why the engine is reducing, You understand why the engine is reducing, then mathematically I have explained to you then mathematically I have explained to you why this brother is reducing the look, why this brother is reducing the look, why P = when it is slowing down, why P = when it is slowing down, then only that is the starting point, then only that is the starting point, mathematically I have explained it, okay, it has mathematically I have explained it, okay, it has also been submitted. also been submitted. also been submitted. | 2024-03-21 12:32:57 | 141 | Linked List Cycle II | Complete Intuition | Leetcode - 142 | Amazon | Microsoft |
|
KiFPAsc7DY0 | hey hey everybody this is larry this is day day 16 16 or 17. 16 16 or 17. why is my computer so slow okay day why is my computer so slow okay day 16 of the leco day challenge hit the 16 of the leco day challenge hit the like button hit the subscribe button like button hit the subscribe button join me on discord let me know what you join me on discord let me know what you think about taste farming as you can see think about taste farming as you can see i'm back in new york yay i'm back in new york yay um um i i i i i i i got in really late after about 12 i got in really late after about 12 hours of uh flying and stuff like this hours of uh flying and stuff like this no that's actually not 12 hours of fine no that's actually not 12 hours of fine but just 12 hours of being in the but just 12 hours of being in the airport and all this other stuff so airport and all this other stuff so i'll i'll make it up with another video i'll i'll make it up with another video uh with a better aruba uh with a better aruba video intro tomorrow but also follow me video intro tomorrow but also follow me on instagram if you want to check out on instagram if you want to check out how that went but um how that went but um anyway yeah let's do today's problem anyway yeah let's do today's problem longest paradromic substring okay longest paradromic substring okay um um let's see the first thing that i look let's see the first thing that i look for to be honest is uh the length so for to be honest is uh the length so that means that there's gonna be n that means that there's gonna be n square um there is square um there is there uh what's it called manager's there uh what's it called manager's algorithm algorithm well i i don't know i still kind of well i i don't know i still kind of refuse to use so refuse to use so yeah i am gonna you know put it here i yeah i am gonna you know put it here i think that's how you spell right right think that's how you spell right right uh yeah uh so uh yeah uh so google this if you like google this if you like for cancer linear uh yeah so that's basically the idea but that's not i don't think that is necessary here so we can just do it in a naive way i'm not sure why it's a medium but i guess it's from way back when but and also if it required a manager's album i don't think it's a medium per se though i don't know it's just like you know like a very uh uh very specific algorithm that i find is not very practical uh to or like it's not worth my time to to learn and i still don't know it uh if i am doing competitive and i'm seeing this i'm saying that i need this i would just google it and you can maybe say cheat a little bit you know but but that said you know knowing the name of it is good enough for me because i don't know i just don't find it that useful per se but i guess you can say that about a lot of things that's just me and i know what you're going to ask uh for some of you anyway maybe not all of you so maybe i don't know why i say it like that but so yeah so the question is should i learn this from my interviews right my answer is going to be no i actually uh i'm thinking about doing a video about these kind of weird not weird just like you know maybe advanced algorithms if you want to call it that but just these algorithms that are not fundamental per se right um and the answer i would say for you if you're still working it out if you're still learning how to do dfs better bfs better dynamic programming better binary search better just regular sorting better and all these other algorithms right uh there's probably a list somewhere um if you're still learning how to do them better i i would rather work on pushing those things better as well right because look the truth is you know no one cares that you know i mean what you know you could even do like a conditional probability thing right like what is the chance that you know you're going to get this on an interview and then you nail it out and that you're able to know it enough to explain to the interviewer how and why and all this other stuff right um i don't know i i i have probably less than one percent in terms of just even getting this specific problem and then the other question is well you know like let's say you get um let's even like just say you have 50 50 percent chance of getting a bfs problem or a manager's algorithm problem right well the key thing there then is not to be average in both because being average probably isn't good enough or maybe not average average but like an average interviewer maybe or interview esi not an average like engineer um with a job or something but you know you're being average in two things you know like that doesn't that's not impressive right yeah you know i'm just saying that's not you know my thing but if you're like really good at bfs then you have 50 chance of really impressing someone right anyway that's my spiel that's why i i still haven't used or i think i've used it before like once literally um but otherwise i just and that time i googled because i knew the name and i knew what to google for so i don't know take it as you will uh anyway i will do this tonight way we're just for i feel like i've done something like that maybe not this particular one i feel like i i've done something like this in uh recently but i think maybe there was one that was just like binary but yeah so basically there are two types of pattern drums right sorry i if you were not thinking about manager's algorithm and you're here just for the basics um then i will go over that right now there's two two type of uh uh pattern drums right there's either an odd one right like this is five characters is odd so then the middle is the center and then there's an even one which is i guess like something like this where the middle is in between characters right so that that's basically the idea and you could just prove first per both uh let's let's let's do it for odd ones first uh then now you know left is to go to center right as you go to center uh while left uh while well let's make sure this is greater this is within bounds and this is then and s of left is equal to s of right then we move left to the left and we move right to the y right and then at the very end we have a best um here i just noticed that we have to return the string but that's okay uh are there multiple solutions huh i mean it could have multiple solutions i mean it could have multiple solutions if it's like if it's like even literally like a b right without even literally like a b right without multiple solutions it doesn't really say multiple solutions it doesn't really say so hopefully it doesn't come into play so hopefully it doesn't come into play but uh but uh but yeah so then now the length is equal but yeah so then now the length is equal to right minus left plus one right you to right minus left plus one right you could kind of do the math and then if could kind of do the math and then if l is greater than best l is greater than best then s is equal to l start is you go to then s is equal to l start is you go to left left right right and then even ones and then even ones so for center in range of n so for center in range of n uh left is equal to center right oops uh left is equal to center right oops did it the british by accident center did it the british by accident center plus one and then you could hear see plus one and then you could hear see that this is you know because it goes that this is you know because it goes out otherwise um and then basically the out otherwise um and then basically the same thing here same thing here uh maybe we could do a little bit better uh maybe we could do a little bit better with with you know you know uh uh code duplication but for now i'm going code duplication but for now i'm going to do this and then at the way end we to do this and then at the way end we just return just return s s from left to left press best from left to left press best i think that's right-ish i'm really bad i think that's right-ish i'm really bad at string thingies so maybe that's off at string thingies so maybe that's off by one i don't know by one i don't know okay that's not okay that's not good did i miss oh oh this is a d not a b i got confused okay but that's okay uh oh well well i'm silly this is stored oh well well i'm silly this is stored that she said that she said i don't know if that fixes it but i don't know if that fixes it but hopefully that does hopefully that does okay that does not in fact hmm oh this is awkward because we don't check because we don't check to begin with so this may not be right to begin with so this may not be right okay right i just have to be a little okay right i just have to be a little bit lazy or bit lazy or it's a little bit more checking but i it's a little bit more checking but i think this is fine also this is wrong think this is fine also this is wrong because now this is even i copy and because now this is even i copy and paste without thinking about it i mean paste without thinking about it i mean and the the sad thing was i was thinking and the the sad thing was i was thinking about this while doing it but then after about this while doing it but then after i copied and pasted i forgot about it i copied and pasted i forgot about it was then right oh no this is was then right oh no this is let's see am i doing this one i think let's see am i doing this one i think this one is the one with the plus one this one is the one with the plus one and this one and this one is where am i right let's think about this right so these should be inclusive bound so if you add number you have say zero to two then that's three numbers so that's plus one uh here this should be more right actually right because if you have now zero and one it should have two no i guess they both should have this i'm just being silly um yeah because i was thinking about doing off the center but that said i'm still really wrong for some reason i i need to do this after the check i i need to do this after the check that's one man very sloppy today sorry friends i just got off a very long trip so that's my excuse uh i have excuses for everything but you know oh there you go that was the the funny thing is i made the same mistake on the by wiggly q4 uh uh like yeah i just had things in the wrong order and not paying attention just going really fast because it is easy and you know as you and as i said you know it's the easy things that will get you uh that's how i lost my drone so anyway uh oh let's give it a submit wow i have i hope i don't get a wrong answer again i'd have wrong answers before okay 807 day streak yeah yeah yay uh this is going to be quadratic time and square uh and o of one space i mean the space part doesn't we don't really use much space uh oh i guess technically o n for here depending how you want to say it but other than the output uh what did i do well here wow oh i was trying to be cute before i said the same thing last time too uh cool uh yeah i mean i guess just easy off by once uh cool cool cool let me know what you think hit the like button hit the subscribe button join me on discord i'll see you later stay good stay healthy to good mental health | 2024-03-18 11:18:42 | 5 | 5. Longest Palindromic Substring - Day 16/30 Leetcode June Challenge |
|
mAEhMxPHOyc | cool 7:30 count different palindromic pollute public subsequences chemistry pollute public subsequences chemistry gas find a number of different non-empty gas find a number of different non-empty powder omics of sequences in s and we powder omics of sequences in s and we turned that number module 10 to the nine turned that number module 10 to the nine plus seven which I guess is a prime a plus seven which I guess is a prime a subsequence of a string s is obtained by subsequence of a string s is obtained by deleting zero or more characters from s deleting zero or more characters from s sequences palindromic if it's equal to sequences palindromic if it's equal to the sequence we were okay two sequences the sequence we were okay two sequences are different if there's someone which a are different if there's someone which a sub I see that you got a piece of I I sub I see that you got a piece of I I guess that means that mmm that they guess that means that mmm that they could return the same string but they could return the same string but they used a different cup or two me and I I used a different cup or two me and I I guess something like that okay yeah I guess something like that okay yeah I mean I think so the first thing that mean I think so the first thing that leaps at me is that if you have to leaps at me is that if you have to return a number module 10 times 9 or 7 return a number module 10 times 9 or 7 that means as a comet or a problem I that means as a comet or a problem I mean I guess that's also to define a mean I guess that's also to define a number for it so it's coming to a farm number for it so it's coming to a farm and usually these are dynamic and usually these are dynamic programming without even reading programming without even reading anything else but obviously that's not anything else but obviously that's not the whole point I mean like just saying the whole point I mean like just saying someone who's done having four gramming someone who's done having four gramming doesn't mean you solve it and your doesn't mean you solve it and your interviewer would be impressed for half interviewer would be impressed for half a second we were like okay now and okay a second we were like okay now and okay Oh way to hide that India which is Egypt Oh way to hide that India which is Egypt countenance as sub I in the note of it countenance as sub I in the note of it just like after two examples why don't just like after two examples why don't you just put on the top I don't know but you just put on the top I don't know but anyway anyway each character a survivor being a set a each character a survivor being a set a B C and D so here's a for again is a B C and D so here's a for again is a four character alphabet the link of a four character alphabet the link of a sub R or s is okay so s is less than a sub R or s is okay so s is less than a thousand strings okay okay I mean so thousand strings okay okay I mean so yeah so it's definite dynamic yeah so it's definite dynamic programming but the question is how to programming but the question is how to and they're just one thing example that and they're just one thing example that I mean it tells you the numbers but then I mean it tells you the numbers but then here okay and you took these and it called a thousand yeah - hmm I mean it step in town over both webbing I think the intuition for me is maybe a little instead basically your map would be and instead basically your map would be and you basically have a table or lookup you basically have a table or lookup table an N square table which you know table an N square table which you know it's a million and and that's most and I it's a million and and that's most and I will be going your substrings is just will be going your substrings is just subproblems and yeah I mean I think the subproblems and yeah I mean I think the function is just I mean there is a cup function is just I mean there is a cup of cases and that's how we have to of cases and that's how we have to consider it but I think you have like consider it but I think you have like okay given a string gasps yes okay given a string gasps yes so how do you construct a power jump so how do you construct a power jump when I show you for example let's just when I show you for example let's just say BCC be the first way to do it is say BCC be the first way to do it is okay well let's say you take off the okay well let's say you take off the piece on the edge weight so that so it piece on the edge weight so that so it just means it's something like so do so just means it's something like so do so if this is you go to the summation of if this is you go to the summation of some other stuff way which is like let's some other stuff way which is like let's say you take off the P in the edge or say you take off the P in the edge or you take it off and it is part of the you take it off and it is part of the string and then you also have to count string and then you also have to count that it is not part of the string so I'm that it is not part of the string so I'm still trying to formulate this in my still trying to formulate this in my head but I say something like this and head but I say something like this and then it's not even true I don't know then it's not even true I don't know I mean roughly I mean we have to figure I mean roughly I mean we have to figure out the different cases I think that's out the different cases I think that's quite a tricky point about it and then quite a tricky point about it and then and you kind of Quinns from the exam and you kind of Quinns from the exam well actually I think this is a way oh well actually I think this is a way oh we see note that please no actually huh ash I was a little bit wrong about Am I why why does it only count it once to sequence different it is some language oh I misread just one okay so do so yeah anyway I mean that's just edge cases so anyway I mean that's just edge cases so we have to figure it out it's gonna be a we have to figure it out it's gonna be a tricky one and then just one step in the tricky one and then just one step in the middle you could say well you know I middle you could say well you know I don't we use or FCC you and then maybe F don't we use or FCC you and then maybe F of and then you maybe just ignore the of and then you maybe just ignore the first character so in this case maybe first character so in this case maybe you someone like that and then maybe you someone like that and then maybe also even have a PC or something like also even have a PC or something like that some combination maybe not quite that some combination maybe not quite like that though because it's you have like that though because it's you have to you have to have some sort of to you have to have some sort of ordering to it otherwise you know you ordering to it otherwise you know you some of these will kind of double count some of these will kind of double count in some ways so I mean there's in some ways so I mean there's definitely a lot of things out to be definitely a lot of things out to be careful about here so maybe as someone careful about here so maybe as someone like that and then try to think about like that and then try to think about what's the right to it so I mean there's definitely some way of so I mean there's definitely some way of constructing this but I'm also kind of constructing this but I'm also kind of you know in terms of you know giving you know in terms of you know giving bounds and some of it in the notes is bounds and some of it in the notes is kind of maybe hints and that's where I kind of maybe hints and that's where I would kind of maybe think about is in would kind of maybe think about is in this case actually I think the this case actually I think the interesting thing is that each character interesting thing is that each character of that supplier should be in this sad of that supplier should be in this sad way and even though it's something to way and even though it's something to quench over I think what you know in in quench over I think what you know in in some of these problems it's important to some of these problems it's important to solve the problem as specifically as solve the problem as specifically as possible possible and what that means is in this case like and what that means is in this case like we don't just like village and Derrick we don't just like village and Derrick string thing maybe it's too easy right I string thing maybe it's too easy right I think the thing we can maybe think about think the thing we can maybe think about figure out how to do is reframing some figure out how to do is reframing some of this in terms of the four alphabet of this in terms of the four alphabet right and what does that mean that means right and what does that mean that means in a way you can figure out how to in a way you can figure out how to compress the rest of this string so that compress the rest of this string so that instead of having like a thousand instead of having like a thousand characters you could compress it with I characters you could compress it with I don't really have a compression thing in don't really have a compression thing in my head yet but in theory you could my head yet but in theory you could represent it with in some way by just represent it with in some way by just the fact that s for help and alphabets the fact that s for help and alphabets way and in that case it would kind of way and in that case it would kind of make the search space a lot smaller or make the search space a lot smaller or maybe not search which is like the maybe not search which is like the counting dynamic programming sub number counting dynamic programming sub number of subproblems a lot fewer I think about of subproblems a lot fewer I think about I would work so I'm just thinking a little bit and I'm not you I think yeah I should have taken it a little bit better but I think one thing I'm playing around with is the idea that or the question I'm asking myself is that's ordering matter I think for each count in the beginning maybe this isn't even right necessary way but the question is okay let's say you have I'm in the poem I'm also having a little I'm in the poem I'm also having a little trouble with its kind of to kind of it trouble with its kind of to kind of it to that some sequence could be to that some sequence could be duplicated and how we factor that in how duplicated and how we factor that in how do we hmm this is a tricky one I mean having a nut more naive thing is for this just can I mean the tricky thing for me is try to I mean the tricky thing for me is try to figure out how to do in a way that figure out how to do in a way that doesn't double count some of these doesn't double count some of these duplicate ones and I'm not really so duplicate ones and I'm not really so that I can do it Oh okay yeah haven't ya the tricky part for me is still trying to figure out how to remove the topic it's yeah what's even just PCP way I mean you could just how just for me I would PI identities to see just for me I would PI identities to see something like some like X you know something like some like X you know something like that and we'll have to something like that and we'll have to figure that out but in this case just figure that out but in this case just people I would apply a usually double people I would apply a usually double Cal wait for what usual one by each Cal wait for what usual one by each character and this is and hmm ninis and you could even buy it up more complicated examples where we see CPA bczp then you're gonna get this PCP sequence way too many times I'm in the other way just to be a little I'm in the other way just to be a little bit better articulation the other way I bit better articulation the other way I would think about it would think about it that I was thinking about it which I that I was thinking about it which I don't know how to cut it to convincingly don't know how to cut it to convincingly is it's kind of like almost like a is it's kind of like almost like a pillow reverse there like a you know pillow reverse there like a you know like a graph to kind of breadth first like a graph to kind of breadth first search to kind of add in the string search to kind of add in the string maybe in a thousand it doesn't take that maybe in a thousand it doesn't take that much but I don't even know how I don't much but I don't even know how I don't think that really that tractable think that really that tractable intractable intractable anyway I don't intractable intractable anyway I don't think that's possible just to did a huge think that's possible just to did a huge amount of non empty powdered room amount of non empty powdered room subsequences let me take a look at this how would I let me take a look at this how would I solve that you know I mean the little solve that you know I mean the little bit matter is that these problems are bit matter is that these problems are always a little tricky and you can tell always a little tricky and you can tell that I'm it's hard to kind of take late that I'm it's hard to kind of take late in an interview if you're walking I mean in an interview if you're walking I mean obviously maybe the interviewer may give obviously maybe the interviewer may give me hints but in some cases like it would me hints but in some cases like it would not be good enough maybe they'll be like not be good enough maybe they'll be like I remember it's an alpha base the size I remember it's an alpha base the size of the album is 4 but but it's hard to of the album is 4 but but it's hard to kind of know I did you can deter you kind of know I did you can deter you down sometimes right and I mean down sometimes right and I mean sometimes it takes a long time to work sometimes it takes a long time to work for it but it's hard to kind of see for it but it's hard to kind of see someone's toy process so that I and in a someone's toy process so that I and in a very pious kind of very probably the very pious kind of very probably the problem like this is an interview problem like this is an interview question as we saw mr. Nickleby perfect question as we saw mr. Nickleby perfect search but when a professor just string search but when a professor just string coding okay in the interest of time I'm just okay in the interest of time I'm just gonna cheat a little bit and let's see gonna cheat a little bit and let's see what the answer would care for this 20mm we pull you in and this isn't even that hmm can i rephrase this problem can we can we go from middle out it sounds like I'm from Pied Piper or [Music] okay well that's assuming that it is a dynamic program form then we will let's figure out the base case when this case it's just well empty string I don't even to no place maybe this is one you see mmm no that's not sure this is blue which means test records a this is blue which means test records a little bit hmm because you could get p CP CP oh that's so this one is using and then CP movie I mean I think this one is the one that I'm actually not sure about because in theory we double counted you love this yeah so I think these problems that were yeah so I think these problems that were how I would kind of slowly kind of yeah how I would kind of slowly kind of yeah we construct on base case just to I mean we construct on base case just to I mean I uses the last we sold almost but I uses the last we sold almost but that's how I would kind of try to see that's how I would kind of try to see him there's any insight into the him there's any insight into the structure of the form that I can kind of structure of the form that I can kind of think about so this represents see this think about so this represents see this purpose ants PCP now this is also just really weird now this is also just really weird recurrence that I'm doing here recurrence that I'm doing here because that's what you want is to just because that's what you want is to just subproblems action mmm because C is just subproblems action mmm because C is just let's say this is this one and have a let's say this is this one and have a second see it's in theory PCP you just second see it's in theory PCP you just kind of wrap it around but then how do kind of wrap it around but then how do you get P and B well you can't even get you get P and B well you can't even get PP how do you get PP in theory that's PP how do you get PP in theory that's baked into one just f sub C which has baked into one just f sub C which has two years or use not so me so maybe two years or use not so me so maybe there's another dimension here but there's another dimension here but that's also that but that would make that's also that but that would make things maybe that's okay actually things maybe that's okay actually because only one count there could be in because only one count there could be in the coin called the middle so you either the coin called the middle so you either you don't you don't sell okay so I think you don't you don't sell okay so I think that also makes it so that maybe that's that also makes it so that maybe that's the missing piece but it's still a the missing piece but it's still a little tricky to kind of figure out as little tricky to kind of figure out as in this case I would have something like I'm ringing and stuff just this function I'm ringing and stuff just this function based on one parameter you need a second based on one parameter you need a second parameter where the second parameter is parameter where the second parameter is just whether you used you use the just whether you used you use the character as the middle piece the single character as the middle piece the single piece that's inferi not too bad we're piece that's inferi not too bad we're going to figure how to articulate that going to figure how to articulate that way also there's some like weird how do way also there's some like weird how do you get from PCP to be maybe just test you get from PCP to be maybe just test and I don't know that's not quite as and I don't know that's not quite as easy so I think some of the easier easy so I think some of the easier dynamic programming problems is just dynamic programming problems is just different ways of kind of constructing different ways of kind of constructing things so that it's exhaustive way like things so that it's exhaustive way like you know for me it's you know you tried you know for me it's you know you tried all possibilities and well if you try all possibilities and well if you try all possibilities it's easy to kind of all possibilities it's easy to kind of figure out what like you tried a more figure out what like you tried a more like if it's an optimization problem or like if it's an optimization problem or something like that in this case because something like that in this case because you're trying to count and it's clearly you're trying to count and it's clearly you can't even double count is a little you can't even double count is a little trickier to kind of make sure you get trickier to kind of make sure you get some of them right like you can't just some of them right like you can't just like in some cases ways like I say like in some cases ways like I say you're trying to get the max of you're trying to get the max of something or the min of something I even something or the min of something I even if you say you you you sir you solve the if you say you you you sir you solve the same subproblem a couple of times same subproblem a couple of times pick a maximum change way because max of pick a maximum change way because max of you know two numbers were always you you know two numbers were always you know like you match the same numbers X know like you match the same numbers X I'm like I still have the same answer I'm like I still have the same answer where we're encounted well then you're where we're encounted well then you're double triple counting so that's why double triple counting so that's why it's a little trickier than usual but to it's a little trickier than usual but to do kind of these kind of things versus I think definitely we definitely need I think definitely we definitely need dimension of middle which brings our dimension of middle which brings our size complexity from from N squared size complexity from from N squared still to n square but now we at least still to n square but now we at least double that way in size so yeah hmm and actually maybe I D bathing okay let me night hmm Oh dad said I okay let me night hmm Oh dad said I still try to figure out how to do this still try to figure out how to do this you know you know [Music] so okay yeah I'm having an I've been proving yeah I'm having an I've been proving some of the stuff is kind of hard I some of the stuff is kind of hard I think we just have to still we I can do think we just have to still we I can do something exhaustive about it and I something exhaustive about it and I think I mean I think the problem that this reminds me the most is kind of suffering the number of was it distinct sub-sequences way but man by man and to be honest I don't remember how to do it or not I okay let me I think in what I need to do okay let me I think in what I need to do is kind of you know take advantage of is kind of you know take advantage of the fact that it's four characters how the fact that it's four characters how did I do that right did I do that right okay to be is critically enough okay that's a well I mean okay so well let's dumb it down for me a little bit let's say well only our alphabet is only two characters what would change well I mean I guess my example already only had two characters but I need to be slightly smaller than that I think maybe this is confusing me a little bit but because as I say we would it would quiet I mean we apply a just used indices okay that's in that case let me mm-hmm which I just see so that stuff mm-hmm which I just see so that stuff it's slightly cleaner well I wouldn't it's slightly cleaner well I wouldn't say quite no necessary say quite no necessary [Music] now let's say hmm so the base case is now let's say hmm so the base case is that let me we have from the beginning okay I mean we fresh my head a little bit well we store my head anyway ah so my inclination is still gonna be laughing way let's say F of hi that's the base case of one character that's gonna be one let's say you have two characters that's still one assuming that they are the same I mean that's I mean maybe I don't even know if this I mean maybe I don't even know if this is actually necessary maybe good is actually necessary maybe good question mark don't know [Music] so what is f of left and ever why did you go - okay okay well let's just say I mean in the very basic one is zero to five minus one if yes you go - that's a boy I mean that's what we said before where you chopped off to stop at the end if not and it's no way is that No well it's actually probably someone No well it's actually probably someone like again this is I'm still trying to like again this is I'm still trying to think about how to to it's been a while think about how to to it's been a while cutting a number of distinct subsets in cutting a number of distinct subsets in conscious in general not really in the conscious in general not really in the powered room though this stuff may add powered room though this stuff may add up okay and if they're not the same and up okay and if they're not the same and what do we do well I guess we just come what do we do well I guess we just come to same a member mm something like that that make sense now that I know you - this because I think this maybe that's how you take care of the overlapping oh man because you - to stuff tats and [Music] yeah because I think if you're you know your side characters are the same and you can just take one off and add it to the powder room and if they're not the same then you have to subtract because okay I mean is that enough so so this I mean that's enough ish for the number of distinct sub Queen sequences maybe but I think or maybe I understand them of sub sub sequences and now that the factor and now we have to factor in the fact that the brigade which is the part that I've had issues how do we incorporate the up of it so I how do we incorporate the up of it so I since it's only four alphabets get to since it's only four alphabets get to can we have them or character just Angie can we have them or character just Angie coaching work well then I got kicked up the internet was I can do so what does this look like what does this mean well first of all this one if I surprise well first of all this one if I surprise you go to character otherwise otherwise you go to character otherwise otherwise you just say what I guess and now this you just say what I guess and now this case will be well I guess this is still the same actually I think this this one you still but how about this hmm if it is the but how about this hmm if it is the counter then and you have say someone counter then and you have say someone like CCP laughing worried and you just like CCP laughing worried and you just us because not sure fine now you have to us because not sure fine now you have to mmm I guess we just too and you just kind of do that after each and you just kind of do that after each letters of alphabet probably but I'm only time okay well I'll just Academy cardova means that this is already on the border don't go sorry Eisen having troubled this one more than I am usually hopefully well I mean maybe sometimes I'm always into a I think this part is very with it yeah I think this part is very with it yeah to count the love it's not you go to to count the love it's not you go to have carried away tell you some weird have carried away tell you some weird pocketing things going on and you just pocketing things going on and you just keep the same character and then you keep the same character and then you count the ones and then you subtract out count the ones and then you subtract out over counting or whatever it is this over counting or whatever it is this what that is you go to write and then what that is you go to write and then it's you go to and then I guess you it's you go to and then I guess you could try all the possibilities which is which in this case because it's only for alphabet so if this is the case maybe you do something like well you - two borders and then you do some and then a that maybe should be okay now mmmmmm nope now the one will be here okay okay well sorry I think I'll explain my logic a little bit I think I kind of jumped a little bit from time to time I so I think the plot so my logic was that and maybe I should you know like I feel like one goes supervillain giving a monologue before solving a form so like it could actually totally be okay I don't know but my first intuition okay I don't know but my first intuition one of the more recent intuition is to one of the more recent intuition is to kind of just count the number of testing kind of just count the number of testing sub sequences which is how I got the sub sequences which is how I got the first formula kind of and subtracting it first formula kind of and subtracting it but taking advantage of kind of but taking advantage of kind of character which is which adds a character which is which adds a dimensional of kind of would like what dimensional of kind of would like what is the last character to be of what is is the last character to be of what is the number of distinct eyelid from the number of distinct eyelid from drumming sub sequences given that drumming sub sequences given that characters to the war you know and then characters to the war you know and then inside you could kind of figure it out inside you could kind of figure it out and and if if took out on the edge are and and if if took out on the edge are not the same then you either you know not the same then you either you know move on to laugh or move on to their way move on to laugh or move on to their way and then you kind of subtract this stuff and then you kind of subtract this stuff in the middle I mean maybe I could draw in the middle I mean maybe I could draw a diagram but you can imagine like but a diagram but you can imagine like but like you have like a big thing so this like you have like a big thing so this one ends up counting let's say this one ends up counting let's say this chunk and then this and then this chunk and then this and then this recurrence will count just chunk or recurrence will count just chunk or actually I think I got them backwards actually I think I got them backwards but you get the point and then this but you get the point and then this chunk will kind of subtract out over chunk will kind of subtract out over counting from counting from this chunk because we over counted dad this chunk because we over counted dad over there over there and so that's of the two edges are not and so that's of the two edges are not the same if they're the same then we can the same if they're the same then we can just chop them off and then and they're just chop them off and then and they're two ways to chop it off right one is to two ways to chop it off right one is to use the edges like like like I was use the edges like like like I was saying earlier like if you say have say saying earlier like if you say have say DCP to to a stitch so that you could DCP to to a stitch so that you could chop off to Abbey's which is to see chop off to Abbey's which is to see which leads to someone like see but the which leads to someone like see but the answer we have essentially either PB or answer we have essentially either PB or oh sorry in this case so I don't PPO or oh sorry in this case so I don't PPO or PCP or just C itself because you chopped PCP or just C itself because you chopped it up and then not use it well so your it up and then not use it well so your two possibilities are chopping it off two possibilities are chopping it off and use it or chopping off and then and use it or chopping off and then don't use it so those are kind of two don't use it so those are kind of two things I'm so actually maybe this is two things I'm so actually maybe this is two then yeah then yeah so that's kind of the way I would think so that's kind of the way I would think about it and now that we have this about it and now that we have this recurrence it's I mean I mean or it recurrence it's I mean I mean or it that's love to do it's kind of code it that's love to do it's kind of code it up this is I mean yeah I mean I think up this is I mean yeah I mean I think one thing to note is that both left one thing to note is that both left first one and I mean laughs it's always first one and I mean laughs it's always gonna be left first one and white is gonna be left first one and white is always gonna be Y minus one so you can always gonna be Y minus one so you can do something that takes advantage of do something that takes advantage of that right now I'm very fearing a level that right now I'm very fearing a level a disease I'm just gonna do it with a disease I'm just gonna do it with memorization and also I'm not actually memorization and also I'm not actually super to be honest super confident about super to be honest super confident about this problem this problem and in those cases doing it with and in those cases doing it with memorization allows me to kind of play memorization allows me to kind of play around the recurrence a lot easier I around the recurrence a lot easier I need to change the order and even of how need to change the order and even of how to do the recursion or something like to do the recursion or something like that that I'm gonna have a base tariff on was that thousand oh my god yeah I know I didn't think right yeah [Music] that's a negative one that's what's and awhile you and then in this case we just need to kick it off using COBOL for recursion not sure I recommend it for quick okay now that what we do only need alphabet it's oh okay fine maybe there's multiplication somewhere maybe I'm missing something and I'm gonna screw this up number of and I'm gonna screw this up number of sales let's try that well guys what that sales let's try that well guys what that point is that's the one implement with point is that's the one implement with this chunk [Music] this is gonna be a mess to read mmm it is in the cleaner okay now I have to there's a subtraction okay like I have to check the alphabet I not if it said sure we'll play around just [Music] it's more like that maybe let's see it compounds first [Music] oops I knew that yeah I was thinking about to use to go sometimes I forget see my to use to go sometimes I forget see my conan's now God is it works I mean well conan's now God is it works I mean well it compares I mean okay hmm let's try it it compares I mean okay hmm let's try it easier case for us back to the basics easier case for us back to the basics okay so I'm double counting something okay so I'm double counting something for sure um okay how would I get eight well it is just to to deform tutors to know hmm how do I get a that's a good Kush oh one other thing I need to do but totally forgot and somehow it still won some time it's memorizing stuff we had that okay so at least it's consistently wrong okay so at least it's consistently wrong which is all you can ask for sometimes hmm yes this is supposed to be in there no careful there's some weird stuff about casting possibly but I know what and always forget seems like it because why does to with seems like it because why does to with my diet to three alphabets okay my my diet to three alphabets okay my kickoff is no wrong it's double-check some still position not count four times probably not it should only be giving me a B so it's you know I never check for house we're you know I never check for house we're here somewhere that's not quite okay here somewhere that's not quite okay well how did that happen - how cuz well how did that happen - how cuz Maltese are doing this yeah I think I got these backwards yeah I think I got these backwards that's why and where's my cup no well I that's why and where's my cup no well I guess I'll look at the locks but this guess I'll look at the locks but this doesn't make sense it's a bit ashamed doesn't make sense it's a bit ashamed and we could chop them off otherwise and we could chop them off otherwise then we to that overlapping thing yeah I then we to that overlapping thing yeah I know I'm just some type of code here but okay I mean it's not white but at least it under counts which is good maybe Helena okay and the one thing that I don't maybe here is because you have to chop it off into two parts of Peru so let us play around guy so I think that's the thing that I had some doubts about face cases are hard well okay I mean that just seems to be right but I mean anyone could be right on one problem so let's try this another one and one test case about it we should try to see easier month Luis okay well I don't know how that worked it okay well let's try some empty strings and stuff like this there - magic form you demand it no okay hmm well then these it's wrong hmm well then these it's wrong I call it beforehand hahaha dumbass how did this even mmm how do I dumbass how did this even mmm how do I get this big thing right if i hears wait what was i even right okay I mean like maybe I maybe saw fly some stuff that wasn't out it oh yeah that's what I mean sometimes I okay when you get it get things white by accident you still want to know why huh I have no time another - you submit and then see what I get one one but okay well I didn't even know what to say sometimes you just get things right but okay yeah I'm yeah so I so yeah so uh this took way longer than I really want to spend on this problem to be honest but uh yeah I think so so the we added two extra dimension because so that we can Chi make sure that you know I'm having much really much earlier we were talking about kind of coding strings kind of in a distinct way and and kind of keeping the character this allow us to kind of make sure that at each time that's the number of that's like how do you say this because you only carrying each possible pairs of or on the edges of characters once that's how you kind of keep it this thing I'm not probably not saying it quite right but but you can think of it yeah I mean I don't know this is kind of yeah I mean I don't know this is kind of tricky but hopefully it helps me work on tricky but hopefully it helps me work on next time and that's now football but next time and that's now football but and that's why we keep on practicing a and that's why we keep on practicing a little bit and but I think you took little bit and but I think you took their components makes sense it's just their components makes sense it's just that I'm really rusty and slow and that I'm really rusty and slow and putting them together I think so good putting them together I think so good so how I would it improve this code I so how I would it improve this code I mean this is a standard memorization mean this is a standard memorization code the tough part in dynamic code the tough part in dynamic programming problems is not really the programming problems is not really the coding per se it's always and kind of coding per se it's always and kind of the construction of the recurrence and the construction of the recurrence and in this case you you can note that left in this case you you can note that left or is only go well there's left over or is only go well there's left over right and the right of only go left so right and the right of only go left so you could build things kind of based on you could build things kind of based on the fact that you only use the previous the fact that you only use the previous row in the matrix that way and then you row in the matrix that way and then you could from - good constructive could from - good constructive occurrence to pair with dynamic work occurrence to pair with dynamic work when in a time in a dynamically when in a time in a dynamically programming leeway but so there's some programming leeway but so there's some optimizations there to quit but I think optimizations there to quit but I think this is actually easier to understand as this is actually easier to understand as an interviewer I think I've mentioned it an interviewer I think I've mentioned it earlier I don't like the problems like earlier I don't like the problems like this because there's some culture I mean this because there's some culture I mean it's not really a catcher for saying it's not really a catcher for saying this you know a lot of time in program this you know a lot of time in program form that some of them has like a little form that some of them has like a little bit of insight that it's just such a bit of insight that it's just such a huge advantage if you've kind of seen it huge advantage if you've kind of seen it before so and it doesn't really usually before so and it doesn't really usually help me think about like it doesn't let help me think about like it doesn't let me see how to nwe things about problem me see how to nwe things about problem so I don't really like this problem for so I don't really like this problem for that reason and specially if comet or that reason and specially if comet or icky stuff it's sometimes tricky if the icky stuff it's sometimes tricky if the recurrence it's not like straightforward recurrence it's not like straightforward like in this case it takes a furniture like in this case it takes a furniture of just a bell which is the size of the of just a bell which is the size of the alphabet which alphabet which which like maybe if you already which like maybe if you already understand why certain things that understand why certain things that distinguish Elvis or not and it makes distinguish Elvis or not and it makes things a lot easier which is that things a lot easier which is that something that I don't know it's no something that I don't know it's no tricky but and like I said me tricky but and like I said me definitely I'm a little biased and definitely I'm a little biased and although I took him maybe if I have although I took him maybe if I have worked on this like five six times and worked on this like five six times and it would have been okay but like the it would have been okay but like the with enough practice on similar problems with enough practice on similar problems but given that I just don't like these but given that I just don't like these kind of problems which we choirs like a kind of problems which we choirs like a almost like a light Bobby a moment where almost like a light Bobby a moment where like I got this where a lot of things like I got this where a lot of things we're like well you know I certain we're like well you know I certain constraints forces you to think a constraints forces you to think a certain way and then you know maybe certain way and then you know maybe that's okay that's okay no no but uh I mean it does I guess for no no but uh I mean it does I guess for me anyway there that it is a hard me anyway there that it is a hard problem problem I probably in a in a post-mortem kind I probably in a in a post-mortem kind when I apply chef's think about in terms when I apply chef's think about in terms of distinct subsequence is a little bit of distinct subsequence is a little bit earlier I think I was probably the idea earlier I think I was probably the idea of kind of first principles a little bit of kind of first principles a little bit too much and try to like derive it from too much and try to like derive it from that way but I think as we served my that way but I think as we served my explanation but this form is probably explanation but this form is probably and maybe if if you haven't uh you know and maybe if if you haven't uh you know got two distinct subsequent qualms got two distinct subsequent qualms before | 2024-03-21 11:41:21 | 730 | 730. Count Different Palindromic Subsequences (Leetcode Hard) |
|
FYho45iq68Y | Hello Hi Everyone Welcome to my channel let's all the third problem of house road and series all the third problem of house road and series for this is a problem solved different in for this is a problem solved different in first attempt and less tourist first attempt and less tourist problem problem like this time to stealing money problem problem like this time to stealing money from big boss house hair in this time from big boss house hair in this time is so face is so face is so face Website Do Exams Housefull-2 Directly Connected Houses No Deep In The Same Night Directly Linked House Which Means From This Root Subscribe Zura Den Roop Can Only Subscribe Zura Den Roop Can Only After Delivery Child Veer Life Child Veer Life Child Veer Life Is The Root Apne Can Have To Is The Root Apne Can Have To Wander Around 120 Wander Around 120 Three-In-One Total Romney Examples Pay 7 Three-In-One Total Romney Examples Pay 7 Plus Subscribe Don't Be Rudra Roop Dedh-Dedh Can Do Plus Subscribe Don't Be Rudra Roop Dedh-Dedh Can Do Subscribe My Channel Subscribe The Maximum Money Can You Solve This Or Or Or exclude maximum possible for this problem exclude maximum possible for this problem no maximum from tree and tree no maximum from tree and tree for true history for this problem for true history for this problem subscribe thank you will always be subscribe thank you will always be pimple we can show this day route pimple we can show this day route 200 from the route which can first robert e 200 from the route which can first robert e dravid and will have to record meanwhile dravid and will have to record meanwhile Directly connected with Android Soen Virudh Directly connected with Android Soen Virudh is not wrong in this can go to the child subscribe my channel subscribe will definitely solve this way crop will rock go to the child subscribe my channel subscribe will definitely solve this way crop will rock you can develop plus absolutely this and eggs subscribe and 10th shampoo first chapter of water of You can go to The Child Crying Child Died From The You can go to The Child Crying Child Died From The You can go to The Child Crying Child Died From The Day The Left Ki And Arun Dot Left And Similarly The Ki And Arun Dot Left And Similarly The Light of the Channel and subscribe the Channel Light of the Channel and subscribe the Channel Root Dot Right Ki Dot Left Ki And Other Is Dot Right All Types Of Some words of all Some words of all Some words of all decision and you will also find default decision and you will also find default from difficulties for daughter Daughter is from difficulties for daughter Daughter is arriving from this point when skin no no Veer arriving from this point when skin no no Veer Veer Veer will get value from difficulties subscribe for Live Wedding of Dainik Rudolph is not null bank Android System from Divine Presence of Witch Runes on.net Platform Root subscribe The Channel subscribe Child With E Do No Evil Returns 10th Maths Cheese From Root From Road Root Subscribe Quote Pants Iss Zameer District Court Can Be Accepted His Mother Language Day Observed In The Cases Not Asli Task Complexity of Complexity of Complexity of dissolution and every time you for every day and dissolution and every time you for every day and time complexity and see the receiver which rules so let's time complexity and see the receiver which rules so let's root rot in the bluetooth root rot in the bluetooth incident will grant from the day God bless you incident will grant from the day God bless you that don't left and don't love life like father of and right that don't And Right Dot Right Choice And Right Dot Right Choice And Right Dot Right Choice Awards For Schools Will Make In Case Of Fear Of Awards For Schools Will Make In Case Of Fear Of Being Rooted Radhe At All Root Don't Being Rooted Radhe At All Root Don't Love Affair F-18 Android Love Affair F-18 Android That Shows Father Is This Is Zaroor Lage In Root And That Shows Father Is This Is Zaroor Lage In Root And A Call From Chronic Hydride Noida Will A Call From Chronic Hydride Noida Will Not Prove It's An At All Not Prove It's An At All Not Prove It's An At All That Not Left Sufi This Is Repeated All Problem Already Have A Girl As Well As Her Subscribe Solve Problem Will Subscribe Solve Problem Will Result In A Very Fatal Attraction And Result In A Very Fatal Attraction And Deposit That Note New Year Will Check Were Deposit That Note New Year Will Check Were That This Map Already That This Map Already That This Map Already The Current Cry Will Return map.com Water Value For The Too Tall And Ever Saw This Will Be Written In Otherwise Will First Calculated In The Map Map Root And You Will Come From Fear And Will Return Value From This Is Subscribe Subscribe Subscribe Loot Subscribe Subscribe Subscribe Loot Subscribe Subscribe Subscribe Loot For Every Time You Will Not Only For Every Time You Will Not Only Give One Time Complexity Subscribe Impress Doosri Give One Time Complexity Subscribe Impress Doosri Side Inko D Memory Yasmin Side Inko D Memory Yasmin District Magistrate Sudesh Isi Every District Magistrate Sudesh Isi Every Time You Have Two Options Like Thanks Time You Have Two Options Like Thanks For The Ruk Kar Loot And Institute Of Going To For The Ruk Kar Loot And Institute Of Going To Result First Same Subscribe Vijendra 109 The Result Of Root Will Make You For The Result Of Ruth Hai A Dot Right Like Share And Of Verses Warning To And Brothers Who Don't Know The Results Subscribe Now To Receive New Updates Root Subscribe Song The Will get the results from including is Will get the results from including is Will get the results from including is reading will return to maximum reading will return to maximum number of this to and every time number of this to and every time he z10 otherwise absolutely celebs result he z10 otherwise absolutely celebs result debit the receiver appointed not including a debit the receiver appointed not including a maximum of from the subscribe The maximum of from the subscribe The Channel and subscribe the Channel Please Channel and subscribe the Channel Please subscribe this Video give yaar subscribe this Video give yaar subscribe this Video give yaar Quality is only about values from where it Quality is only about values from where it is not like and subscribe Amount of is not like and subscribe Amount of money drowned in school on Thursday subscribe money drowned in school on Thursday subscribe The subscribe like this problem problem problem The subscribe like this problem problem problem problem subscribe The problem subscribe The Channel thanks for watching | 2024-03-24 10:50:22 | 337 | house robber iii leetcode | house robber III leetcode | leetcode 337 | tree + dp |
|
flBef_8dXNs | hey yo what's up guys babybear4812 coming at you one more time today with coming at you one more time today with problem number 1054 problem number 1054 distant barcodes so this problem came up distant barcodes so this problem came up in in earlier this year in 2020 in one of the earlier this year in 2020 in one of the weekly or bi-weekly contests weekly or bi-weekly contests and it looks like it's been picked up by and it looks like it's been picked up by uh bloomberg predominantly so uh bloomberg predominantly so they've asked this one a couple of times they've asked this one a couple of times and i think it's a really good problem and i think it's a really good problem with a uh with a uh a bit of a clever solution really uh a bit of a clever solution really uh pretty unique pretty unique i'd argue so i haven't really done one i'd argue so i haven't really done one like this before personally i don't know like this before personally i don't know what happened there i haven't done one what happened there i haven't done one like this before personally so i thought like this before personally so i thought it'd be a really good one to it'd be a really good one to to go over and maybe uh pick up a few to go over and maybe uh pick up a few tricks from so yeah tricks from so yeah if you haven't yeah if you haven't tried if you haven't yeah if you haven't tried it yet pause the video give it a read it yet pause the video give it a read give it a try and then come on back all give it a try and then come on back all right right so uh 1054 distant barcodes we're told so uh 1054 distant barcodes we're told in a warehouse there's a row of barcodes in a warehouse there's a row of barcodes where the ith barcode is barcodes vi where the ith barcode is barcodes vi rearrange the barcodes so that no two rearrange the barcodes so that no two adjacent barcodes are adjacent barcodes are equal you may return any answer and it equal you may return any answer and it is guaranteed an is guaranteed an answer exists all right so if we look at answer exists all right so if we look at an example like this one here where an example like this one here where we've got we've got one one one two two two easy to one one one two two two easy to represent a barcode represent a barcode uh what we could potentially return is uh what we could potentially return is um um maybe here what we could potentially maybe here what we could potentially return return is two one two one two one uh is two one two one two one uh they're also saying you can't return any they're also saying you can't return any answers so that means you could also do answers so that means you could also do something like something like one two one two one two all right so one two one two one two all right so both of those are both of those are are acceptable we're good uh are acceptable we're good uh similarly we've got one one one one two similarly we've got one one one one two two three three two three three they went with one three one three two they went with one three one three two one two one again i i think it's one two one again i i think it's it's a very easy problem to understand it's a very easy problem to understand not an easy one to solve but easy to not an easy one to solve but easy to understand understand so every single bar code now does not so every single bar code now does not have any have any it doesn't have a a matching barcode to it doesn't have a a matching barcode to itself in either of its itself in either of its adjacent positions all right adjacent positions all right so how do we do this well maybe we can so how do we do this well maybe we can uh uh let me walk you guys through at least let me walk you guys through at least kind of what my first attempt was and kind of what my first attempt was and how i how i i failed horribly at it um and then i'll i failed horribly at it um and then i'll give you guys give you guys the correct answer and really like i'm the correct answer and really like i'm only half joking but but truly i do want only half joking but but truly i do want to walk through the to walk through the walk through the logic and see how we walk through the logic and see how we can actually get to answering this can actually get to answering this question all right question all right so one one one two two two is what we so one one one two two two is what we got got so one potential way of thinking about so one potential way of thinking about and this was again kind of my and this was again kind of my my first thought um was to sail me my first thought um was to sail me you know maybe i was i think i was you know maybe i was i think i was modifying this in place but what i'll do modifying this in place but what i'll do is for the sake of this example and for is for the sake of this example and for the final answer the final answer i'll keep a separate result array and i'll keep a separate result array and build my answer in there build my answer in there uh what i was doing was saying okay well uh what i was doing was saying okay well i can i can bring this first element i can i can bring this first element down and then down and then let's start from the second element let's start from the second element element element element element and iterate onwards all right and iterate onwards all right so i start iterating from here and i so i start iterating from here and i what i do is i ask myself is this what i do is i ask myself is this element the same as element the same as the element before it if the answer is the element before it if the answer is yes yes then what i'm essentially going to do is then what i'm essentially going to do is to jump ahead and say okay let me keep to jump ahead and say okay let me keep moving some pointer up until i find my moving some pointer up until i find my first non-identical element which would first non-identical element which would be this one right over here be this one right over here and then what i said was okay well in and then what i said was okay well in that case let me let me swap those two that case let me let me swap those two let me let me make this a two let me let me make this a two and and let me make this a one and then and and let me make this a one and then okay we're good so we've got this like okay we're good so we've got this like one two one situation and i'll again one two one situation and i'll again i'll kind of keep this here separately i'll kind of keep this here separately um but this is a this is a two all right um but this is a this is a two all right so so we um no i apologize that's a one we um no i apologize that's a one that's still one i'm sorry i swapped that's still one i'm sorry i swapped these this is now one all right it's no these this is now one all right it's no longer two longer two um so i keep on going i i kind of place um so i keep on going i i kind of place this item here now this item here now i'm doing some double tapping so this is i'm doing some double tapping so this is immediately gonna become quadratic immediately gonna become quadratic anyways it kind of felt wrong but anyways it kind of felt wrong but you know you might think okay well this you know you might think okay well this is fine now you know the the one is is fine now you know the the one is different from the two and then different from the two and then oh we got another adjacent one here so oh we got another adjacent one here so let's let's do the same thing let's kind let's let's do the same thing let's kind of traverse along until we find a of traverse along until we find a non-one element non-one element which we do here so we say okay wicked which we do here so we say okay wicked let's swap those let's swap those this becomes two this becomes one we get this becomes two this becomes one we get something like two something like two one we check these numbers they're all one we check these numbers they're all good it's like cool all right we got a good it's like cool all right we got a solution i forgot to write this down solution i forgot to write this down but you know it all kind of lines up i but you know it all kind of lines up i know i'm a bit messy and quick in my know i'm a bit messy and quick in my explanation but explanation but i think generally you guys get get what i think generally you guys get get what i'm getting at i'm getting at the problem i found there was what if we the problem i found there was what if we had an example like two had an example like two one one all right so one one all right so we we look at the two we drop that down we we look at the two we drop that down then we say then we say well this one's not the same as a two so well this one's not the same as a two so everyone's happy everyone's happy one goes down we get to this one and one goes down we get to this one and realize realize okay well you know this one is is not okay well you know this one is is not the same the same or sorry this one is the same we need to or sorry this one is the same we need to swap it with something else i take a swap it with something else i take a step forward step forward whoops we're out of bounds we end up whoops we're out of bounds we end up returning this and this ain't right returning this and this ain't right all right and it's inefficient so this all right and it's inefficient so this solution didn't work very well so solution didn't work very well so how heck with this i'll start a new one how heck with this i'll start a new one so that one didn't work all that well so that one didn't work all that well for us and then for us and then essentially what we need to realize in essentially what we need to realize in this problem is this problem is uh is as follows actually there's one uh is as follows actually there's one piece of information they give us piece of information they give us which can kind of trigger a hint in our which can kind of trigger a hint in our in our minds and in our minds and and this hint isn't necessary you can and this hint isn't necessary you can still solve the problem without it still solve the problem without it but what they do say is that an answer but what they do say is that an answer is guaranteed to exist is guaranteed to exist all right so if an answer is guaranteed all right so if an answer is guaranteed to exist to exist and i give you a list of length and and i give you a list of length and okay how many times can the most okay how many times can the most frequent element appear frequent element appear if i give you a a list of length six if i give you a a list of length six right and again same question how many right and again same question how many times can the most frequent element times can the most frequent element appear appear well if we want to start you know we've well if we want to start you know we've got an even number of elements and got an even number of elements and there's guaranteed to be an answer we there's guaranteed to be an answer we can at most have three ones can at most have three ones if i've got anything more than three if i've got anything more than three ones ones i won't be able to do this and so if i won't be able to do this and so if that's the case we've got you know we that's the case we've got you know we can get can get up to three ones if i had five elements up to three ones if i had five elements let's think about if i had five elements let's think about if i had five elements could i slap three ones yeah if i had could i slap three ones yeah if i had you know six i could have something like you know six i could have something like this x x x this x x x and then if i had something similar and then if i had something similar except an odd number i could have except an odd number i could have one x one x one so at most we're going one x one x one so at most we're going to have to have you know n plus one maybe we'll have n you know n plus one maybe we'll have n over two over two or um n plus one or um n plus one over 2. that's the maximum number of over 2. that's the maximum number of times we can see the most frequently times we can see the most frequently occurring element occurring element so why am i making a big stink over this so why am i making a big stink over this well well if we realize that that's the case then if we realize that that's the case then no matter what if no matter what if i wanted to fill my array with my most i wanted to fill my array with my most common common element let's again let's go with a element let's again let's go with a let's go let's go if we had five for example if i had five if we had five for example if i had five elements in total and i potentially most elements in total and i potentially most frequent up here up to three times frequent up here up to three times okay the maximum possible where do i okay the maximum possible where do i have to put those have to put those right i would have to put them in the right i would have to put them in the first position first position zero with index then i'd have to put in zero with index then i'd have to put in the second the second index then i'd have to put in the fourth index then i'd have to put in the fourth index once that reached the end index once that reached the end i would then have to go back and start i would then have to go back and start filling in these other odd elements with filling in these other odd elements with other things and and this other things and and this is exactly where the trick lies in this is exactly where the trick lies in this question you're not even the trick but question you're not even the trick but just the key to getting it just the key to getting it if i had something even longer so let's if i had something even longer so let's say i had say i had one one one two two one one one two two three three three four five six seven three three three four five six seven eight four and i'll do something like eight four and i'll do something like this i'll do five just we have this i'll do five just we have an awe i forget the five we don't need an awe i forget the five we don't need it we'll do we'll do a an even number it we'll do we'll do a an even number this time this time all right one is my most frequently all right one is my most frequently occurring element occurring element so five two three four five six so five two three four five six seven eight how i would playing again seven eight how i would playing again we'll obviously go through the code but we'll obviously go through the code but logically to fill this in what i have to logically to fill this in what i have to start from left to right start from left to right in the zeroth index position and start in the zeroth index position and start filling every other filling every other every other element so i've done one one every other element so i've done one one one okay i filled those one okay i filled those now i've got the rest these elements to now i've got the rest these elements to fill fill how do we ensure now what is so we could how do we ensure now what is so we could get in a situation where let's say i had get in a situation where let's say i had something like something like oh well i'll you know i'll take these oh well i'll you know i'll take these and i'll start filling them from left to and i'll start filling them from left to right so i'll go two right so i'll go two two three and then maybe let's say we two three and then maybe let's say we didn't have the four for example all didn't have the four for example all right just right just to kind of prove my example then i'm to kind of prove my example then i'm like oh damn i'm out of space like oh damn i'm out of space so what do we do here how do we make so what do we do here how do we make sure that we don't fall into this sure that we don't fall into this situation situation well what we'd have to do is we'd have well what we'd have to do is we'd have to say to say let's do almost like a i like to think let's do almost like a i like to think of doing a two pass of doing a two pass fill through the result array skipping fill through the result array skipping an element every single time so first an element every single time so first we're going to fill in the even we're going to fill in the even indices and then the odd indices i indices and then the odd indices i filled in all my ones filled in all my ones let me keep skipping two indices at a let me keep skipping two indices at a time and fill this thing time and fill this thing so i skip another two from here i fill so i skip another two from here i fill in this two we got that in this two we got that now i skip another two whoops i'm out of now i skip another two whoops i'm out of bounds reset my index back to one we're bounds reset my index back to one we're now going to start filling the odd now going to start filling the odd indices indices we're gonna fill in the two that's gone we're gonna fill in the two that's gone we're gonna fill in the three that's we're gonna fill in the three that's gone we're gonna fill in the three gone we're gonna fill in the three that's gone we're gonna fill in the four that's gone we're gonna fill in the four that's gone you passed your interview that's gone you passed your interview you're working at google you're working at google thank you later does that make sense let thank you later does that make sense let me know down below if it does or me know down below if it does or of course if it if it doesn't as well of course if it if it doesn't as well but this is the key to solving this but this is the key to solving this thing is understanding that we need to thing is understanding that we need to find find i'll write these steps down we need to i'll write these steps down we need to find the most frequently occurring find the most frequently occurring element element all right we need to find we don't all right we need to find we don't necessarily need to find how much necessarily need to find how much you know how many times each of them and you know how many times each of them and they backtrack they backtrack we need to find the most frequently we need to find the most frequently occurring element in order to do that occurring element in order to do that what we've got to do is to find the what we've got to do is to find the frequency of all of these so we'll do frequency of all of these so we'll do one pass through one pass through and we'll keep track of of of the and we'll keep track of of of the frequency of how many times they come up frequency of how many times they come up of course the data structure we should of course the data structure we should use for that will naturally be a use for that will naturally be a dictionary or a hash table dictionary or a hash table okay to keep track of that we will then okay to keep track of that we will then go and identify what the highest go and identify what the highest occurring occurring highest frequency element is and we highest frequency element is and we could potentially do that in one pass i could potentially do that in one pass i think i'll break it on just two steps think i'll break it on just two steps just uh just uh just just for clarity of explanation but just just for clarity of explanation but we find the most frequently occurring we find the most frequently occurring one one and we start filling from the zeroth and we start filling from the zeroth index on every two spaces index on every two spaces and we keep filling we keep doing we and we keep filling we keep doing we keep going when we run out of that keep going when we run out of that element we start element we start filling in with the rest of the filling in with the rest of the frequencies until frequencies until we kind of reach out of bounds here the we kind of reach out of bounds here the first time then we jump back first time then we jump back to this first index and now we fill the to this first index and now we fill the the odd indices the odd indices all right i hope that makes sense i hope all right i hope that makes sense i hope i didn't go through that too quickly i didn't go through that too quickly but like i said it at least for me this but like i said it at least for me this was my first time seeing a was my first time seeing a seeing a problem like this and i thought seeing a problem like this and i thought that it was a i thought it was a really that it was a i thought it was a really clever solution clever solution so i think at this point we've hammered so i think at this point we've hammered out the logic enough to out the logic enough to to kind of take a pause here jump back to kind of take a pause here jump back to the code and uh and see how to make to the code and uh and see how to make this thing happen right now as per usual first thing i'll do is i'll do my error checking though i think the error checking might be redundant here might be i think the code would work without it but i'll i'll put it in here for now um if not barcode so for given an empty list or none or something i'll just say let's return barcodes all right so we've done our error checking now next thing we need to do is to say uh find frequency of all numbers all right so uh essentially what we'll do is we'll create a let's say a dictionary and in this dictionary we'll loop through the barcodes now and circling frequencies and what i'll do is i'll say for for all the numbers in in barcodes what we'll say is this if the number is not the barcode so if i'm not in barcode uh sorry if it's on the dictionary already it's not in the dictionary then we're going to want to put it in there so we're going to want to say a dictionary of of num and we'll set it equal to zero because what i'm going to do out here is just going to say we'll take dictionary of of num and increase it by one so this way if a number is already in there we won't jump the safe statement we'll just increase the the frequency by one otherwise throw it in first then increase the frequency all right so again i understand that as you're going through this you could potentially pick out the most uh frequently occurring element in that one step again i'm just gonna break it out here and then you know if you'd like optimize away let me know in the comments down below if there's a there's a way to make this a lot nicer and cleaner um so then i said here uh identify uh max occurring element so maybe what we can do is we can find the max num and we'll keep track of the max frequency as well and we'll set both those equal to zero just by default right off the bat and what we'll do is this is we'll essentially say let's think so we want to go through all of the all the numbers in the dictionary so we'll say for number dictionary uh if the if the frequency of that number so if if dictionary of oops none and maybe you actually know what let me just create a variable say frequency is equal to dictionary of num okay if frequency if it is greater than max frequency then what we want to do is we want to say uh maximum is equal to no and we'll say that max frequency is equal to frequency and i believe that's it so in that step not like for the problems thanks guys for watching but uh i think that's it in in this step because again what we're doing is i'm just initializing these variables here and i'm saying if the frequency of this number in the dictionary if it's greater than the max frequency we've seen then we'll say that's our our most occurring element all right so now what we want to do is we want to create a uh create a result array so let's maybe create result array and from there we want to or create a result or okay maybe that can be its own stuff so i'll say a result and we want to make it of size the same as barcode and maybe i'll fill it with zeros for now it doesn't really matter so i'll say zero for some underscore in uh in barcodes just so they're the exact same length so put a list comprehension there and now what we want to do is to start so we'll start filling list with most frequently occurring elements all right so what we're going to do that first and what we're going to do is let me write out the next step after that we'll say um fill out rest of elements right we can't forget those then after all that we're going to return the the result at the end period or at the end of the the problem so returners on that's over like crushing a ladybug with a sledgehammer um but being crystal clear here so we we start filling this thing from like we said the zeroth index so i'm gonna say we'll start at index equals zero all right and what we're going to want to do is we're going to say let's do the following we're essentially going to want to say while um let's say this uh while max frequency is greater than zero what we'll do is we'll we'll decrement that that max frequency as we go and then eventually we'll we'll get to zero so i'll say well max frequency is e uh is greater than zero we're going to say uh result at index is going to equal the max number that we had so we're going to be filling that in once we fill it in we want to jump the index up by 2 index plus equals 2. and so at this point what we've done up and max frequency minus equals 1. right i almost forgot that part i said it out loud if we had let's see our element occurred three times so max frequency was three we set result at zero to be our number and x goes up by two frequency goes down two all right we try it again we fill in the second index because it goes to one we fall on the fourth the next greeks goes to one um our frequency goes to zero excuse me and and we're good there so we've jumped our first second third um and so now we've we've filled in the result with our maximum occurring element what i'm going to do is i'm going to take that element actually and delete it from the dictionary and the reason i'm going to delete it from the dictionary is as follows i'm going to want to iterate through the rest of the dictionary and get the frequency of all those numbers as well i don't want them iterating through it i don't want to pick up this max number because we finished with it already so delete uh dictionary of maximum so that's going the way of the dodo that's gone and what we're going to say is this if we look at the example that we had here when i filled in when we were filling out this area here we had one one one and by the time we got here to the end if we went back to start filling in the twos we would have already had to have jump back to the first index conversely if you know we had we had this scenario we filled in the ones then we still had space to keep going so we're not sure yet that if that index is out of balance or not so what we can simply say is if if index is greater than or equal to the length of the result then we simply want to set index factor to equal one all right otherwise what we want to do is this is we want to say four uh again four num in a dictionary and again these two steps i'm sure we can make uh maybe a cleaner way to merge these together into one i just i i really wanted to do it i wanted to do it this way again to separate the logic because the other way to do this thing is to pull all the items with their frequencies um pull like a dictionary.items or something and sort them by frequency sorting would take and log n time i wanted to do an in end time so that might make the the steps seem a touch clunkier but it's the performance will be better so that's why that's how i opted to do this so for the for the numbers in the dictionary we are going to say following uh we're going to say uh result of index or maybe let me say this i'll say while the even better let me do this again frequency of that number okay we want to know how many times we got to fill it in so i'm going to take the frequency of that number by saying frequency is equal to dictionary of num i'm then going to say that while the the frequency is greater than zero so similar to the trick i did above i will say that result of index is equal to the number i'll then say that the frequency or the index needs to jump off by two frequency needs to go down by one now the index i said two i typed one the index needs to jump up by two and every time we jump up by two we risk jumping out of bounds again so every single time i check this for example imagine we just got to this so we started here right then we realized we're going we're going going down to that second while loop the one that starts right here we fill this thing in okay cool we're happy we jumped the index up by two after we filled it so we filled in this two we jump the index up by two but now we realize if we try to fill it again we're going to get out of balance so what we've got to do is again to do the same check that we had up here if we've gotten there then let's go back to index one and and start filling from there and then that'll that'll take us straight to the end and so again this point is overkill i don't need that there um i do need to align this though and i think that this will do it so let me i'm going to run and make sure that i didn't make an error oh boy that is surprising very very pleasantly surprising and you love to see that happen 98 percent okay around in 97.59 super quick um memory usage i i did create a result array a separate one there is a way to do this without one i believe um and it will it might require a bit a bit more thinking so i'll leave that with you guys maybe as in it's an exercise left for the reader uh to play around with that if you're interested this is this all kind of fits just on one screen here so i'll leave the code if you want to take a look at it any questions about this any other questions you want me to solve you've heard this bill before drop in the comments down below like subscribe share with your your best friends your teachers your mom your pet dog everybody everybody should see this i think um yeah let me know what you think guys is always something to mess around with you | 2024-03-25 16:23:23 | 1,054 | DISTANT BARCODES (Leetcode) - Code & Whiteboard |
|
KuE_Cn3xhxI | Hello Hello Guys Welcome Back To Decades And This Video Will See The Valid Parents Is Trick This Video Will See The Valid Parents Is Trick Problem Typical From List To Problem Typical From List To Dresses For Wedding Challenge So Let's Look At Dresses For Wedding Challenge So Let's Look At Problem Problem Subscribe Tanning Problem Problem Subscribe Tanning Only Three Types Of Characters Which Tend To Check Only Three Types Of Characters Which Tend To Check Weather This Is The Subscribe Weather This Is The Subscribe Like Like the Channel and subscirbe the Channel and subscirbe Temples in the First Example You Can See Reduce Temples in the First Example You Can See Reduce Opening Practice Bank Balance Opening Practice Bank Balance Bakons Racket Sufism If Star Justin Bakons Racket Sufism If Star Justin MT Strings and Destroys Balance by MT Strings and Destroys Balance by 0.2 In the Second Example You Can See This 0.2 In the Second Example You Can See This Practice Bank Balance Subscribe Button Practice Bank Balance Subscribe Button Last But Not The Least To Interest Balance Last But Not The Least To Interest Balance Thursday This Is The Most Of The Distinct Will Thursday This Is The Most Of The Distinct Will Not Possible To Balance Balance Balance Subscribe Must Subscribe And Bell Quote Here Of Minister's Intervention In Brackets Solar System That We Can Be Taken To Battery Interesting Net Balance This Battery Interesting Net Balance This Battery Interesting Net Balance This Poster Will Get Converted To May In This Poster Will Get Converted To May In This Tree To Understand This Problem subscribe Tree To Understand This Problem subscribe to subscribe our The Validity Problem The Thing Which Comes To to subscribe our The Validity Problem The Thing Which Comes To Mind Can We Do Subscribe To My Channel Must Open Half Open In Brackets But They Need To Take Half Open In Brackets But They Need To Take Care of ministers will be costlier option Care of ministers will be costlier option see here also opening racket according racket see here also opening racket according racket in this string will make the position in this string will make the position of the subscribe like this is not away be like this is this what is this of the subscribe like this is not away be like this is this what is this subscribe and subscribe subscribe and subscribe the Channel Please subscribe and subscribe the Channel subscribe Positions instituted of putting a characters so let's just traverse through this interesting the subscribe now to the value of Quote 9 You can directly raw elements in the OpenStack so will look into the time because they can always convert Dual App Disclosing Racket in 250 Assume that we can convert into doing so will give they to learn adherents directly can be maintained a to the Page if you to the Page if you to the Page if you liked The Video then this text will be achieved its nt strings in this case basis of string and go through latest look at the next example2 example2 is vansh and will start from subscribe The Channel and subscribe The Channel and subscribe The Channel and character can be written letters in hindi where already subscribe subscribe Video the second step is to balance there opening the second step is to balance there opening racket sunavai travels and the leftovers open racket sunavai travels and the leftovers open in brackets in this openstack and tried to in brackets in this openstack and tried to balance by converting textbox balance by converting textbox using back end using back end using back end left 100 will start setting this star no you can see the district has also arranged in ascending order because while passing from left to right with just the right most element will always be the highest value is 0 0 0 balance subscribe and subscribe the Channel and subscribe this gain welcome per it is the current tax balance gain welcome per it is the current tax balance star delicious top-10 stories have star delicious top-10 stories have value 410 relying on the right side of this value 410 relying on the right side of this opening credit the forest scam opening credit the forest scam balance subah pau this element saudi operation balance subah pau this element saudi operation will be performed will be performed will be performed open subscribe and will not possible to balance the open floodgates and subscribe exposed and subscribe chittor dual and closing brackets and balance no the second step is to balance the Opening Racket Sorry for open traffic jam daily and practice positive balance otherwise it is not lead and will balance sheet using sisters show in this it is not empty so will have to balance and so will start balance in from right to left days from Down Now They Are At Down Now They Are At Down Now They Are At The Side Three Opening Racket And They Want To The Side Three Opening Racket And They Want To Balance By Using Star So Will See The Balance By Using Star So Will See The Star The First Service Presented At Star The First Service Presented At Index 29 The Position Of The Star Should Always Index 29 The Position Of The Star Should Always Be To Right Hand Side For Opening Be To Right Hand Side For Opening Racket If You Want This Opening Racket If You Want This Opening Racket If You Want This Opening Balance And Because You Can Convert Text To According Racket In This Is It Back Side Reaction Band This Is Not Available To Celebrate This Is Not Possible To Distract Him From Left To Right Brothers Pushing The Index Values To A Faint Satisfy Satisfy Satisfy his condition given element in best actor his condition given element in best actor will be able to satisfy software will just will be able to satisfy software will just returned all lands at distic will returned all lands at distic will not be quite a few important cases which are not be quite a few important cases which are necessary for solving this problem using this necessary for solving this problem using this problem can be solved in just to problem can be solved in just to enter traversing distic only one does subscribe The Channel Please does subscribe The Channel Please subscribe and subscribe this This Is The subscribe and subscribe this This Is The Industry And Processing Subscribe Industry And Processing Subscribe From Here This Opening Racket Center Both Are From Here This Opening Racket Center Both Are Finished And You Encounter Using Back Finished And You Encounter Using Back And You Will Just To Return Forms For And You Will Just To Return Forms For This Is The Hills On This Number Balance Singh This Is The Hills On This Number Balance Singh Bablu Singh Rackets will also subscribe to Bablu Singh Rackets will also subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe the Channel and subscribe the Veer Vikram Balance This What is This What is This Channel Radhe-Radhe Quid Faster in This Can Not Balance This Valid Backlink Edition in Valid Backlink Edition in Valid Backlink Edition in Vancouver Destroyer of Losing Its Own This is the Third K Vancouver Destroyer of Losing Its Own This is the Third K Switch Returns for Proving That Everything and Switch Returns for Proving That Everything and Finally Will Return Truth Finally Will Return Truth No Matter How Many Star Subscribe Center No Matter How Many Star Subscribe Center Code with Different Approach and This Solution in Code with Different Approach and This Solution in Different Languages Then You Can Come and Different Languages Then You Can Come and Everyone Can Everyone Can Like, share and subscribe Benefit from YouTube channel. | 2024-03-20 16:00:36 | 678 | Valid parenthesis string | Leetcode #678 |
|
JlBSoswl87c | Hello everyone welcome to my channel, today we are going to do video number 13 of our maths playlist. today we are going to do video number 13 of our maths playlist. Lead code number is Lead code number is 1359 hard but I will explain it in such a way 1359 hard but I will explain it in such a way that it will become very easy for you. It is that it will become very easy for you. It is important to understand that tuition is necessary, that I am important to understand that tuition is necessary, that I am definitely clear. definitely clear. definitely clear. count is fine, the valid pickup and delivery options are fine, let's see what the question is, the question is to say that you have placed n orders and you must have given a value of , and there are two things in every order. Obviously you would know that in order to complete any order, there is a Example, okay, first one order, then the first order is picked up and delivered. There is There is There is no other way to write, isn't the no other way to write, isn't the first one written dog, after that first one written dog, after that not the other one, how can you do delivery without first picking up, not the other one, how can you do delivery without first picking up, now first delivery is done and then there is now first delivery is done and then there is some pickup, this will be wrong, isn't some pickup, this will be wrong, isn't this wrong? this wrong? this wrong? means there is only one possible sequence of doing this order n = 1 order, which is what is p one the one is ok for n = 2 let's see the answer They think it's okay, so They think it's okay, so They think it's okay, so look, first of all, one way is visible to look, first of all, one way is visible to me that p2d2 is this is also valid, after that what is p one p tu di tu di one what else is there sorry Understand intuition and see in general Understand intuition and see in general Understand intuition and see in general how to deal with such questions. See in general, how to deal with such questions. See in general, such problems are very such problems are very brain-wrenching because you do brain-wrenching because you do not have a direct approach in your mind as to not have a direct approach in your mind as to what can be done. Either way, the worst what can be done. Either way, the worst way is to way is to way is to you are there, then make one, okay one, make it of kar size, because what is the make of p1 p2 p1d2, okay, then make an area of kar size, zero, one, three, first write p1 d1d2 After that, take out as many possible d1d2 After that, take out as many possible d1d2 After that, take out as many possible combinations as possible, take out as many possible combinations as possible, take out as many possible permutations as possible, take out as many permutations as possible, take out as many possible in the beginning, you can say in the beginning, you can say that this bread force method will be yours, that this bread force method will be yours, if you do not understand anything, then you will if you do not understand anything, then you will root. root. root. take out all the permutations and whatever valid permutations are there, how will you check the well permutations, see that if p1 is shown here, then story d1 should come only after p1, if it is p2 Okay Okay Okay like ma take a permutation of this like ma take a permutation of this ma take this happened t tu p tu di one to ma take this happened t tu p tu di one to p one dikha di one later very good di tu p one dikha di one later very good di tu dikha di u p2 so till now we have not seen it dikha di u p2 so till now we have not seen it so brother this is a wrong permutation so so brother this is a wrong permutation so so brother this is a wrong permutation so saying, you will have to take out all the permutations and check and that method will be yours, it is fine but we have to see what is the best way to solve it, see, I know how I have approached it, Try Try Try this, how do I think about it, this, how do I think about it, I saw such problems that N = 1 I saw such problems that N = 1 means p1 and one is given one, means p1 and one is given one, then I saw that okay, there is only one then I saw that okay, there is only one way, first you have to pick up and way, first you have to pick up and then you have to deliver. then you have to deliver. then you have to deliver. one was there because this is the only sequence possible. one was there because this is the only sequence possible. Right, one second is possible, so I write it here. Now coming for N = 2, I was asked that there must have been two orders p1 p2 and given one, you are right, there So there are two orders, that is, I write that So there are two orders, that is, I write that 1 of order one, so I already know the answer, 1 of order one, so I already know the answer, now one more extra order has come, the second one has to be now one more extra order has come, the second one has to be adjusted, right here, it adjusted, right here, it is okay, Okay Okay Okay and let's draw this clearly, either here or this, right here, let's reduce one, how many possible spaces do I have, one, this how many possible spaces are there, three possible, You can also put deto here, You can also put deto here, You can also put deto here, okay so p2 next it was okay so p2 next it was p one it was this was last me di tu kar diya p one it was this was last me di tu kar diya in the last space so three way a in the last space so three way a went if I had chosen this p2 to keep it okay okay good now ma good now ma good now ma if I keep p2 here, how many now I am writing p2 here in the middle, so I have now I am writing p2 here in the middle, so I have written p2 here, I will do the same with d2, okay and there is nothing further, okay now. count, a total of six possibilities, I got count, a total of six possibilities, I got 32516 3251 right, so why did it happen, think about why, fixed, so remember, it could have been either here or here, here are these three ways, because three spaces were visible to me. 30 pages were visible ahead, so three ways were found, then when I said no, if we keep p2 here, then one or two ways were found, then look, if I one or two ways were found, then look, if I said no, 5+4. 5+4. 5+4. showed you that when you tried to select p2 here, how many spacecase children are there, for d2, one, two, three, three specials, added here, Similarity Similarity Similarity happens in the case of five. We can know the number of space in it. happens in the case of five. We can know the number of space in it. Okay, Okay, look, this is the time of first natural numbers. Remember, look, this is the time of first natural numbers. Remember, what is its formula? Remember N in N + 1 / 2 space account here. Friends, it is five plus one by you, till now it has been cleared, look at N = 2, we have taken out the total, its difference was six, so we have taken out six, now you will come to N = 3, otherwise one more important thing will be cleared, look ahead, now look There are two very important parts, now There are two very important parts, now There are two very important parts, now you are going to understand, okay for N = 3, then remember we had calculated for N = 2, so remember what I said and saw how much space is there, then I had placed the order there, so I had placed the order there, so I had placed the order there, so when I have to remove it for N = 3, I will see when I have to remove it for N = 3, I will see what are the possible options for N = and I what are the possible options for N = and I will put the third third order in it. I will will put the third third order in it. I will try to do so. For N = 2, brother, try to do so. For N = 2, brother, six. six. six. laying down one, after that people will see the others. First, I have placed this one on p2d2, is it okay, I am writing p tu di tu p one di one is okay, how many spaces are possible For the order, there is talk of third powder, For the order, there is talk of third powder, For the order, there is talk of third powder, one, two, three, five, there is one, two, three, five, there is talk of third order, because talk of third order, because I have taken out up to N = 2, here are so many, so I have taken out up to N = 2, here are so many, so I am picking all of them one by one, I am picking all of them one by one, first. first. first. look at it, let's see one, two, three, three, five, one, two, three, three, five, five, it is visible, you can find that too, see, it is working on the formula, is okay, you subtract one from it. okay, you subtract one from it. Multiply it by 1 then do plus one and see, the Multiply it by 1 then do plus one and see, the number of space will be calculated. It is simple maths number of space will be calculated. It is simple maths and is based on observation or pattern or you can also find it. and is based on observation or pattern or you can also find it. If you look at more examples, if you look for N = 4 If you look at more examples, if you look for N = 4 and if you look for five, then and if you look for five, then you will get the count of space. you will get the count of space. you will get the count of space. you are not able to find it, then look and what is the value of N? Three is three minus one, you are 2 * 4 + 15 A. Look, the number space is five, so now we can find the space also. Very Yes at the place, Yes at the place, Yes at the place, see here also how much space was there in N = 2, see here also how much space was there in N = 2, remember there were three spaces, let's see remember there were three spaces, let's see [Music] [Music] Neither 2 - 1, it becomes 1 * 2 + 1 3, remember there were 3 spaces, Neither 2 - 1, it becomes 1 * 2 + 1 3, remember there were 3 spaces, see, it is correct. see, it is correct. see, it is correct. space has been taken out, it's good, now let's move ahead, just remember, I have only read this, I have to pay attention to this, I am only 15 ways to only 15 ways to insert the third order. insert the third order. insert the third order. date is taken out, just for this, then this is also long, so here also there are five spaces, for this also 15th date will come, then for this also there will be 15 ways, for this also there will be 15 ways, 15 for this, How many times did we add 15? We added it six How many times did we add 15? We added it six How many times did we add 15? We added it six times. Remember, what was the addition of six? What was the answer for n = 2? times. Remember, what was the addition of six? What was the answer for n = 2? What was the answer for n = 2? It was six. What was the answer for n = 2? It was six. And for n = 3, when I And for n = 3, when I came out with a special formula, 15 was came out with a special formula, 15 was applicable for this. applicable for this. applicable for this. 15 * 6 = 90 should be like this, what was the answer of N, one was one, six, one, okay, great, I wrote it here, I tried to solve a pattern for N = 3. That is, 15 is fine as per the space, so there were 6 possibilities in N = 2, then 15 sixes, 90 total, with 90 possibilities, it is fine for three. This thing is very important for you to It is It is It is important to important to understand one thing, why multiply? understand one thing, why multiply? Many people get confused as to Many people get confused as to why they are multiplying. It is very why they are multiplying. It is very important to understand this thing. I am repeating it again. important to understand this thing. I am repeating it again. Look, I had raised this. There are 6 total possibilities of N = 2. Look, I had raised this. There are 6 total possibilities of N = 2. Here I had taken it Here I had taken it out and saw how many ways are there to put the third order in it. It turned out that there are 15 ways to put it in this too. There would be 15 ways to put it in this too. So * 6 = 90 will be * 6 = 90 will be * 6 = 90 will be written, this is clear till now, this thing written, this is clear till now, this thing should be clear, you should know the reason of each and every thing, should be clear, you should know the reason of each and every thing, why multiplied why multiplied here, I know why I was wrong in the beginning that this is a question of Math I saw that okay, I saw that okay, I saw that okay, here there are spaces, here there are spaces, number of spaces and I have to adjust the number of spaces and I have to adjust the chapter on spaces in my maths, there was such a thing that there are so many empty spaces, if you have to fill something in it, then how will you fill it, the If that is If that is If that is okay, then in such questions always okay, then in such questions always understand that DP, don't think about anything, always understand that DP, don't think about anything, always think in terms of mathematics. If it is okay in such questions, think in terms of mathematics. If it is okay in such questions, then you see, our problem has become very simple, then you see, our problem has become very simple, so its solution will also become very simple, you know this. you know this. you know this. First, I am writing in the result that First, I am writing in the result that yes, I know the answer of N = 1. What was yes, I know the answer of N = 1. What was one? Now I have to find out the answer from where to where because N has been asked. attend, friend, how much space will there be, the formula of space, I had come to know that by doing N - 1 * 2 + 1, the formula of space comes out, how much space will there be, okay now it is clear, after that Also my possible result will be, Also my possible result will be, Also my possible result will be, not the result yet, that means for now, current possibility was found, the current possibility is ok, current possibility was found, the current possibility is ok, 15 was taken out, 15 and remember what was the answer of the previous one, it was six, every one, there are For everyone's sake, For everyone's sake, For everyone's sake, multiplying those six by 15 is fine. It is possible that the value may be a very big question. It is also saying that apply modulo mode because a very big value will come. You can enter it easily I am telling you I am telling you I am telling you till here, that is why I have to say each line, you should till here, that is why I have to say each line, you should know the meaning of why the space was taken out, know the meaning of why the space was taken out, how much will be according to the current possibilities how much will be according to the current possibilities and why it was multiplied here, and why it was multiplied here, you should also know this in the result which I have you should also know this in the result which I have explained above, now your explained above, now your explained above, now your exercise as to why the formula for space will be the same, you can derive it yourself, if you think a little then you will understand, it is okay, this is an exercise for you, otherwise I will put it in the comment, which will help in the butt due to doing the exercise. You had to understand that, you have already understood, do a small work, this is a five line code, it is quickly let's finish and finish this code, so let's start, it is quite good but so let's start, it is quite good but you should make it once. you should make it once. Otherwise, without making such a question, if such a question does Otherwise, without making such a question, if such a question does not come new in the future, then it cannot be made. not come new in the future, then it cannot be made. Generally, it is okay, you should make this type of combination Generally, it is okay, you should make this type of combination first. Okay, so let's start. We have first. Okay, so let's start. We have given a very big value in the question, so given a very big value in the question, so first. first. first. power of 1 A in the same module, it has been said to take 9 plus 7 plus 7 modular, here it is if it is equal to one, then the answer is going to be my one, if it is equal to one, then the answer is going to be my one, okay okay return band. return band. return band. what do I do after this, long long result is equal, you keep one here, whose answer was n = 1, one is neither, then the result of last n, I have started, now in What has to be done is to find out from tu to i What has to be done is to find out from tu to i What has to be done is to find out from tu to i <= n till <= n till i++ i++ ok, first let's calculate the count of space, ok, first let's calculate the count of space, what will be the account of space i - 1 what will be the account of space i - 1 * 2 + 1 ok, whatever is the value of n, do * 2 + 1 ok, whatever is the value of n, do minus one tu plus one. minus one tu plus one. minus one tu plus one. see the current possibility, result in this possibility * They have this question was a very good question, if you have doubt then comment area Ultra | 2024-03-21 00:36:55 | 1,359 | Count All Valid Pickup and Delivery Options | CLEAR INTUITION | META | Leetcode - 1359 |
|
2owpaafBIgw | Hello everyone welcome to my channel Codesari with Mike, so today we are going to Mike, so today we are going to do video number four of our bit manipulation playlist. do video number four of our bit manipulation playlist. Okay, the lead code number is Okay, the lead code number is 1356, it is easy, that is why I have kept it more 1356, it is easy, that is why I have kept it more informative, meaning informative, meaning you will learn more extra things from this video. you will learn more extra things from this video. What do we learn? The name of the question is Sort What do we learn? The name of the question is Sort Integer Sort by the Number of One Bits. Ajan has Integer Sort by the Number of One Bits. Ajan has asked this question. It is a very simple asked this question. It is a very simple question. You have been given an Array of Integer Sort. You have to sort it in ascending order by the number of ones. Sort. You have to sort it in ascending order by the number of ones. Sort. You have to sort it in ascending order by the number of ones. representation and in this case, if any two numbers are found whose number is one, if they are the same in their bit representation, then it is okay to sort those two numbers in ascending order. Let us As if I were assuming that As if I were assuming that As if I were assuming that this was your input, I have just this was your input, I have just done the binary representation of everything and have written it. done the binary representation of everything and have written it. See See how many one bits are there in the binary representation of five. Two, how many one bits are there in the binary representation of five. Two, here one bit is one. Here one bit is two. Here one bit is one. So here one bit is one. Here one bit is two. Here one bit is one. So in ascending order. in ascending order. in ascending order. least one bit will come first, so who has the least one bit, this and this, both have the same, but one is one, so what to do in that case, we will write in ascending order, first we will write two, look, it First after that we will First after that we will First after that we will write 8, okay after that, look at this, they have write 8, okay after that, look at this, they have two, two one bits, okay, two, two one bits, okay, so first we will write three because three is so first we will write three because three is small, I said to write in ascending order, then after that we will small, I said to write in ascending order, then after that we will write five, okay so it is the write five, okay so it is the same. same. a Comparator and Lada for Sort a Comparator and Lada for Sort Utility. Look, I know that you are going to use the sorting function, you have to Utility. Look, I know that you are going to use the sorting function, you have to sort, sort, you have to sort utility, I think in all. you have to sort utility, I think in all. you have to sort utility, I think in all. happens in C+, it is also in Java, you can use it directly, okay, earlier it was very simple, we used to do it in ascending or descending order, but here we have to sort in a different way, So the obvious So the obvious So the obvious thing is that we will have to write Comparator or Lada. thing is that we will have to write Comparator or Lada. Okay, so we will learn Okay, so we will learn how to write it today and will understand it in great detail. how to write it today and will understand it in great detail. Everything is fine. So it is Everything is fine. So it is very simple. All you have to do is write it, you just have to very simple. All you have to do is write it, you just have to sort it. sort it. sort it. but if you want to do it in a different style, then you write 'Lada', there is no Comparator for that, you either write 'Lada', 'You do the sorting in my way, okay, so I will write 'Lada' here now and explain the whole thing by writing. One thing is fine, so let's start writing the code. Here, first of all, let's write what is the return type of our code expression. Then I leave it to the compiler. Let's write The The The compiler itself deduces compiler itself deduces what the return type will be, otherwise you what the return type will be, otherwise you can also write the boolean, because we are going to can also write the boolean, because we are going to compare, it is there inside, so compare, it is there inside, so I have written auto and left it to the compiler, I have written auto and left it to the compiler, after that the name of the argument is there. after that the name of the argument is there. after that the name of the argument is there. can see the name as my function or anything, I generally write Lada, whatever I have written here is fine, this is your return type, this is my name Lada, whatever you We give it equal We give it equal We give it equal to OK, now pay attention to the very important thing here, you to OK, now pay attention to the very important thing here, you will understand that this is a capture clause. will understand that this is a capture clause. What is the meaning of capture clause? What is the meaning of capture clause? Understand what it means. I am writing Understand what it means. I am writing here that capture clause means here that capture clause means that if the value that if the value that if the value defined any variable or any data structure outside Lada, whether it is a vector or anything else, you can capture it here so that you There is int a, so There is int a, so There is int a, so if I write a here, then if I write a here, then I can use a within this thread. I can use a within this thread. Okay, and if you write this and a, it Okay, and if you write this and a, it means you are taking a by reference, is means you are taking a by reference, is n't it extra? n't it extra? n't it extra? only reference is taken. Generally, if you take by reference here then if you make any change here, if you make a = 5 then the same exact change will come in it too, this will also become equal to f. Capture Capture Capture clause is fine, if you leave it blank, it clause is fine, if you leave it blank, it means nothing will be captured. Okay, means nothing will be captured. Okay, generally I leave it blank. Okay, have you generally I leave it blank. Okay, have you understood what this is, this is your understood what this is, this is your capture clause, so I am underlining it. Capture clause is fine. Capture clause is fine. Capture clause is fine. return type? This is the name of your Lada which you have given. Okay, after this comes the actual expression of Lada. Okay, how do we write the expression of Lada like this? Okay and open bracket, close bracket Semicalculus is fine, now look pay attention to Semicalculus is fine, now look pay attention to Semicalculus is fine, now look pay attention to this part, it this part, it takes parameters. takes parameters. Okay, here I write the Okay, here I write the receive receive parameters. Okay, that means whatever parameter parameters. Okay, that means whatever parameter you have to take, whatever you are passing here, you have to take, whatever you are passing here, int A, int B. int A, int B. int A, int B. here you are seeing the whole 'Hey, isn't it? Hey, you have passed 'Hey', so what will it do internally? But what will I do, int a, int b, I have taken two But what will I do, int a, int b, I have taken two numbers, they will be compared, only then numbers, they will be compared, only then sorting will happen, so I write end and end here sorting will happen, so I write end and end here so that a copy is not made by reference, I prefer passing the so that a copy is not made by reference, I prefer passing the parameters, so parameters, so this is my parameters. this is my parameters. And these curly braces here And these curly braces here define the Lada expression, meaning this define the Lada expression, meaning this is your body, okay, now do whatever you want to do inside it, is your body, okay, now do whatever you want to do inside it, now remember when you now remember when you wanted to sort in ascending order, hey, wanted to sort in ascending order, hey, what did you check brother? what did you check brother? what did you check brother? is less than b then it is okay to return true then it was sorted in ascending order ascending and if you had to do this in descending then a was greater than b then it was okay it was descending but this time What we have to do this time is What we have to do this time is What we have to do this time is how many number of bits are there in a and b how many number of bits are there in a and b and we will find out the count of one number of and we will find out the count of one number of set bits count of one in a so I will set bits count of one in a so I will write a function and take it out from there ok find one write a function and take it out from there ok find one bits count one bits count one bits count one and send it to a there, it will find out how many bits are counted in this a, it will take out and give the similar count of one, this was in a, this was in b, let's take out the count of one bit, we If I pass it If I pass it If I pass it then how will I know then how will I know how many number of one bits are there in both of them. how many number of one bits are there in both of them. Okay, so it is given in the question that if we take Okay, so it is given in the question that if we take it as C, we have written a very big it as C, we have written a very big variable. Let us take it as C. variable. Let us take it as C. Okay. Okay. Okay. is equal to the count of one bits in B then remember what is said in the question that brother please sort it then what I will say is ok A lesson B which is smaller will come first i.e Sort it okay and Sort it okay and Sort it okay and if it is not so then what do I have to do whose if it is not so then what do I have to do whose count of one bits is smaller will count of one bits is smaller will come first C take C B okay ascending come first C take C B okay ascending on the basis of count of bits is Na Na on the basis of count of bits is Na Na bits Now see if this which is the count of A bits Now see if this which is the count of A bits Now see if this which is the count of A means that if the one bit in A is reduced then A lesson C will be returned to C and B will return true. Okay, if it returns true then first it will take A, whatever is the sorting, after that it will So this is what we have So this is what we have So this is what we have written our lda and we just don't have to do anything, written our lda and we just don't have to do anything, in short look at this lda, in short look at this lda, I have called it, I have passed the lda parameter, I have called it, I have passed the lda parameter, okay, it was quite simple, now here you must be seeing okay, it was quite simple, now here you must be seeing that I have called a function. that I have called a function. Well find one bits count means now I just have to do one last thing that brother find the count of one bits in any number and write its function ok this is also very simple which will give me the number of one bits First of all, let's start by First of all, let's start by First of all, let's start by counting int. Count is equal to counting int. Count is equal to 0. Now look, it is a very simple method. Almost 0. Now look, it is a very simple method. Almost many people would know this thing, but now I will many people would know this thing, but now I will teach you. Let's assume teach you. Let's assume there is some number. Let's take your value and it there is some number. Let's take your value and it is is 10. 10. 10. three? Total, so I have to find out the value of how many number of one bits are there. So look, know what I will do. I will simply take one and end operator. This is one, isn't it? If you This is one, isn't it? If you This is one, isn't it? If you take one to AND operator, then see what answer will come. take one to AND operator, then see what answer will come. 0 0 0 Okay, what is the benefit of doing one to AND operator, 0 0 0 Okay, what is the benefit of doing one to AND operator, otherwise all the rest will become zero otherwise all the rest will become zero and look here, the last bit, this one and look here, the last bit, this one and this one will get one. and this one will get one. and this one will get one. its value. If you get one, okay then if you get this one, what does it mean that the right most bit of this number was the one, that is why this and this together gave one, so I took it, okay I took it, okay I took it, okay till now it is clear, now see what I till now it is clear, now see what I will do, this number was mine, first I will do, this number was mine, first I will hit right shift on it because this one's work is will hit right shift on it because this one's work is done, this one's work is done, I done, this one's work is done, I counted from this one and then take counted from this one and then take butt. butt. butt. this one zero will come here this one here this one here then zero one one is ok and zero will come on the left side it is ok to be pad Shifted right Let's Let's Let's do it, okay like this, the do it, okay like this, the right shift will happen. Okay, now we have done the right shift, now right shift will happen. Okay, now we have done the right shift, now our number is done, we will do the same again, take one from the end our number is done, we will do the same again, take one from the end operator, this is what happens, operator, this is what happens, right, take the end operator, right, take the end operator, look, all these are zeroes. look, all these are zeroes. look, all these are zeroes. because it is zero but will be saved, this last digit is zero and one is zero, what does it mean that the bit here was zero, okay, if there was not one bit, then we will count, otherwise the count is still What is one's one is one, one bit What is one's one is one, one bit What is one's one is one, one bit 's count is one, 's count is one, okay now again which was my Nam, let's okay now again which was my Nam, let's right shift this again, then see what will happen Nam is right shift this again, then see what will happen Nam is equal to two yew will come here equal to two yew will come here and this one will come here, okay this is and this one will come here, okay this is zero here. zero here. 10, OK, so 1 has come, the rest are all zeros, so 10, OK, so 1 has come, the rest are all zeros, so here if the answer is one, it means I have here if the answer is one, it means I have got one more bit, I have got two bits, OK, got one more bit, I have got two bits, OK, again right. again right. again right. my name is right shift, so it is ok, it is gone, right shift again, take one to end, will it come, see what is it, it is one, meaning this one Again Again Again got another one, now if you shift right then got another one, now if you shift right then see what will happen, it will become 00 G, okay if it see what will happen, it will become 00 G, okay if it becomes zero, then stop now, look, now it becomes zero, then stop now, look, now it becomes zero, if you shift right, becomes zero, if you shift right, now stop, okay now? now stop, okay now? now stop, okay now? so see how many bits have we counted. So, we have counted three bits and it is correct. Look, what was our reason number, this was the slogan, tap number, this is how many bits are there in it. If By By By taking shift from one to end, we taking shift from one to end, we can easily get one. Okay, can easily get one. Okay, think about what will be its time complex and I will think about what will be its time complex and I will show you further. Okay, what I said, show you further. Okay, what I said, I will keep taking right shift till the I will keep taking right shift till the number which is not equal to two. number which is not equal to two. number which is not equal to two. till it becomes zero, I will keep taking right shift and how will I count? What did I tell you that brother, I will take the simple and moist one and will take the end operator from one. If the one comes, it If it is right most then I will If it is right most then I will If it is right most then I will add it to the count because only one will come, add it to the count because only one will come, count plus equal to nam and one count plus equal to nam and one one, if one comes then the count bit will increase by one, one, if one comes then the count bit will increase by one, ok and I have to right shift nam also. ok and I have to right shift nam also. Keep doing that then. Keep doing that then. Keep doing that then. zero, story ends, what will we do from here, return count, okay, so see, we used this function in Lada, what will it give me, count bit one, okay, now look, give time You see, I am You see, I am You see, I am iterating over all the bits of any number. Let's iterating over all the bits of any number. Let's assume it is 10. So once I have assume it is 10. So once I have seen it, it is one. Well, I have counted it. I have seen it, it is one. Well, I have counted it. I have looked at this. I am looking at all the bits. looked at this. I am looking at all the bits. So, So, how many bits are there in any number? how many bits are there in any number? how many bits are there in any number? in binary equation there are log of num to the base two. If there are so many bits then how many times will this while loop run, what will be its time complexity of log of num. Okay, remember from where we were calling this function, We were calling from We were calling from We were calling from Lada, here it is ok and we have passed the sorting here, so it will take Lada, here it is ok and we have passed the sorting here, so it will take n for sorting, it will n for sorting, it will definitely take place, but look definitely take place, but look inside Lada, we are calling it every time, inside Lada, we are calling it every time, which is taking so much time. which is taking so much time. Log of Nam to the Bastu, so the overall time Log of Nam to the Bastu, so the overall time complex will be so complex will be so clear, you will clear, you will get to learn a lot, it is an easy question, but you have get to learn a lot, it is an easy question, but you have learned a lot, you have learned the complete details of it, learned a lot, you have learned the complete details of it, then how to calculate the count of one bits then how to calculate the count of one bits in a number. in a number. in a number. clear to you till now and you have also understood the time complex very well, now let me teach you one more thing, my approach to this is the first approach, it will be submitted and it will also be accepted. Now you are seeing here that I have written a separate function, I had to work very hard here, right if he says in the interview that can you do it without writing this function, that means any other better function which you know, if you know If you know STL or know anything then If you know STL or know anything then If you know STL or know anything then tell me yes I know an STL which can give me a more tell me yes I know an STL which can give me a more efficient count by calculating one bit count efficient count by calculating one bit count which is my approach to which is my approach to see what happens in c+ p Underscore see what happens in c+ p Underscore Underscore built in pop Underscore built in pop count count count call it directly, pass any number in it, you do n't know what it will do to you, how many bits are there in one bit, in its binary representation it will give you immediately O of one time, remember this it Of the size of the number, it will give Of the size of the number, it will give Of the size of the number, it will give you in one go, you will find the details there, it is ok, it is clear to you ok, it is clear to you that the built in pop count that the built in pop count can directly give you the number of numbers in one time. can directly give you the number of numbers in one time. Off one bit sets is similar to C Off one bit sets is similar to C plus plus, similar to what plus plus, similar to what happens in Java, it is like this in Java, yes, happens in Java, it is like this in Java, yes, integer zero dot bit count, you will also pass num in this, integer zero dot bit count, you will also pass num in this, it gives you how many numbers in O off one. it gives you how many numbers in O off one. it gives you how many numbers in O off one. off one bits, okay, so what will we do, we will try to make it in both the ways, that is, here I have already written my function which will calculate the count of off one bits, but I am saying that you can I will take once the underscore I will take once the underscore I will take once the underscore built in pop count and integer cow bit in Java, built in pop count and integer cow bit in Java, both are approachable. You do not use this function and use the underscore built in popcon. If you remove it in offv, then all the operations here are offv only. So okay, so we did not take extra time in the log, this time remember the last time, the log off seemed moist because we had written our own separate function to extract one bit but here it will be in the offv, so in this case My time completion in 2 is n, it will seem like the overall time complexity because this time the log off number which was supposed to be found has not been found, I have taken it out in wow, so let's code with both the researchers and finish it, so Let's code it with the Let's code it with the Let's code it with the explained method, we will do it exactly the same in both the ways, explained method, we will do it exactly the same in both the ways, so first of all what I said was that so first of all what I said was that we don't have to do anything, we just have to sort from the beginning of a RR till the end of a RR, we just sort in a different way. sort from the beginning of a RR till the end of a RR, we just sort in a different way. sort from the beginning of a RR till the end of a RR, we just sort in a different way. separate lda, in the end I will return ARR only. Okay, now I am going to write lda. I am ok, it is auto return type. I have named lda as lda. You Claus Claus Claus parameter will be taken here Lda expression parameter will be taken here Lda expression is ok so here int and a int and is ok so here int and a int and b will be comparison on two numbers ok b will be comparison on two numbers ok int count of bit one bit a ok and int count of bit one bit a ok and I will write the function count one bits ok I will write the function count one bits ok a passed a passed a passed also find out the count of one bits in B and here we have passed B. Okay, now look in the question it is given that if count of one bits in A is equal to I, equal to B If there are two numbers B If there are two numbers B If there are two numbers whose number of one bits account is same whose number of one bits account is same then brother go in ascending order then brother go in ascending order ok in ascending order i.e. first A will ok in ascending order i.e. first A will come then B will come ok if A is lane B then come then B will come ok if A is lane B then first A then B after that if it does not happen first A then B after that if it does not happen So brother whose count is smaller will come first So brother whose count is smaller will come first Count A Lesson Count B If it is true then Count A Lesson Count B If it is true then A will come first B will come later If it is false A will come first B will come later If it is false Count A take B false then B will come Count A take B false then B will come first then A will come Okay so I fought this first then A will come Okay so I fought this too too too what do we have to do now, we have to write our function, count bits is ok, count bits int number, this is also very simple, we had learned int nam equal to zero, sorry count equal to 0 I I I will keep going till it becomes not equal to zero, okay, you will keep going till it becomes not equal to zero, okay, you can write it like this also, the only thing is the same, can write it like this also, the only thing is the same, okay, okay, count plus equal to two, and one, count plus equal to two, and one, I told you to do the end operation, okay, I told you to do the end operation, okay, after that just Nam. after that just Nam. after that just Nam. right to Okay and what to do in the last one is return count and that's it, we just have one thing here, you pay attention, this is inside the body of Lada, you called a function count one bit which is in the body of Lada. I told you that if you have to access something from outside then you have to use capture clause. Okay, so if you just write on m here, then who knows what will happen, whatever thing is outside the lda. Everything will be accessible by reference, so now if you call count one bits, then the error will not come. See, I will call without M and see if the error will come. Okay, that too is important to understand, so I Look, Look, Look, here the error is coming, now here I here the error is coming, now here I give m but ok, now see it will be accepted give m but ok, now see it will be accepted ok because I used the external ok because I used the external function inside lda, see it function inside lda, see it is accepted ok now see is accepted ok now see what I said that what I said that what I said that complex. complex. Okay, built in Okay, built in underscore pop count. Probably something like this. underscore pop count. Probably something like this. Okay, let's use it similarly here too. From Okay, let's use it similarly here too. From here, take out this in our O Offv. here, take out this in our O Offv. Will give Will give how many number of one bits were set bits were how many number of one bits were set bits were see in our number the see in our number the same exact java code will be accepted you will get it same exact java code will be accepted you will get it in the description of my get hub link is there any in the description of my get hub link is there any doubt raise in the comment doubt raise in the comment section come try to help you out see you section come try to help you out see you section come try to help you out see you next video thank | 2024-03-21 00:34:42 | 1,356 | Sort Integers by The Number of 1 Bits | 2 Approaches | AMAZON | Leetcode - 1356 |
|
YLUVx8lXe90 | hey what's up guys this is sean here so today uh let's take this is sean here so today uh let's take a look at a look at this problem number 354 this problem number 354 russian doll envelopes uh i think you russian doll envelopes uh i think you have have some of you may know this russian though some of you may know this russian though right basically right basically so this is like a a door inside another so this is like a a door inside another door right right which is another dough door right right which is another dough which is another dough so you have a which is another dough so you have a number of envelopes with number of envelopes with width and height given as a pair of width and height given as a pair of integers integers with w and h and one envelope with w and h and one envelope can fit into another only even only if can fit into another only even only if both the width and the height of the one both the width and the height of the one of the one on one envelope is is greater of the one on one envelope is is greater than the width than the width than the other one one envelope into another one if the one envelope into another one if the both the both the if both the height and the weight is if both the height and the weight is strictly smaller strictly smaller than the other one and then it asks you than the other one and then it asks you to find the maximum to find the maximum number of envelopes you can you can number of envelopes you can you can can you russian doll right put in put can you russian doll right put in put one inside the other one inside the other note the rotation is not allowed note the rotation is not allowed so and here's some here are some so and here's some here are some examples so the first one is examples so the first one is you're given like this envelope with you're given like this envelope with this kind of like width and this kind of like width and width and height and the output is three width and height and the output is three because the uh because the uh that's the that's the three envelopes that's the that's the three envelopes you can you can fit into each other you can you can fit into each other basically three two you can fit in four basically three two you can fit in four and five because and five because because four is greater than two four because four is greater than two four i'm sorry i'm sorry 5 is greater than 2 and 4 is greater 5 is greater than 2 and 4 is greater than 3. than 3. so that's 2 and another one is 6 and 7 so that's 2 and another one is 6 and 7 right because 6 is greater than 5 right because 6 is greater than 5 and 7 is greater than 4. and 7 is greater than 4. so so if you guys watch it closely as so so if you guys watch it closely as you guys probably already find out right you guys probably already find out right so basically so basically this is like the two kind of like two this is like the two kind of like two strictly increasing strictly increasing sequence here right so first one is the sequence here right so first one is the width width and the second one is the height and the second one is the height i mean if you guys have have done the i mean if you guys have have done the problem called the longest problem called the longest increasing subsequences so this thing increasing subsequences so this thing this problem is this problem is it's just like a two two dimensional version of the of that the longest increasing sequence because both the height because both the height basically you have to satisfy that basically you have to satisfy that longest increasing subsequence in both longest increasing subsequence in both of the of the in both height and width in both height and width right so and i and actually right so and i and actually this problem is a little bit similar this problem is a little bit similar than the than last week's weekly contest than the than last week's weekly contest problem which is the i think it's called problem which is the i think it's called uh best team uh best team with no conflict something like that so with no conflict something like that so from for that problem it's similar from for that problem it's similar basically you have you're given like a basically you have you're given like a team with the with the agent score and team with the with the agent score and it asks you to find it asks you to find the the maximum score the maximum score the the maximum score the maximum score without conflict so basically just without conflict so basically just similar as this one similar as this one i mean so every time every time when you i mean so every time every time when you guys see guys see this kind of like so the longest this kind of like so the longest sequence longest sub increasing sequence uh longest increasing sequences with two conditions we need to satisfy right so this in this problem is a we have to satisfy both the height and and the width so every time with this problem you just we just need to sort one condition first we sorted we satisfy one conditions and then we can utilize that longest increasing subsequence logic to to get our the maximum value based on the other on the other instant okay so okay so so for the uh so for those who still uh so for the uh so for those who still uh don't know don't know the the the logic for the longest the the the logic for the longest increasing subsequence basically for increasing subsequence basically for that one the that one the the basic logic for that one is we have the basic logic for that one is we have a dp a dp we have dp array here right we have dp array here right so this dp array stands for the longest so this dp array stands for the longest increasing subsequence increasing subsequence this this number at with this number as this this number at with this number as an ending number an ending number okay and then so what do we do we simply okay and then so what do we do we simply do this right we do a we do a do this right we do a we do a max max of what max of the dp max max of what max of the dp i right so i right so max of dpi and the dp max of dpi and the dp j plot plus j plot plus one right if one right if if the number number i is greater than the number of j so that's the the lsi logic basically you know at each of the at each of the uh the ice locations we look through out numbers before i and then we we find out all the numbers we for for each numbers whose number is smoke smaller than the current i then we know okay so we have find the uh another validate of valid candidates that we can we can calculate our current dp right so it means that since this dpi my dpj is also strictly increasing since we have these like conditions for each of the dp so it means that we have dpi here right and then we have uh some numbers and then we have a db a dpj right because dp from from zero to dpj this is increasing and since dpi is sorry since number i is greater than number j so which means that from 0 to dpi plus and to dpj this is also strictly increasing that's why this thing works okay so that's the uh that's the basic lis logic and we can just simply utilize that utilize this method here okay i'll i'll give you guys this straightforward this straightforward solution first but and then i'll be discussing another one another another solution because for this problem if you're if you're using this like kind of like the na the native lsi solutions it will tle so which means we'll need a better solution for this okay but let me try to implement this one first okay so like i said since we have two conditions we need to satisfy here right so we will be sorting at first condition we'll basically we'll sort on the uh we can sort out any one it doesn't really matter envelopes we do a sort we simply do a envelopes we do a sort we simply do a sort sort basically this was sort by the first basically this was sort by the first condition right condition right and then we have an end level here okay and then we have an end level here okay envelope and then we're going to have a like a dp so so for we initialize all the values with dp with zero and with one because at each of the locations as you guys can see the this the envelope itself still counts at one so even though we can do a this russian dot twice but the total number is three that's why we start this thing with one or we can initialize everything with zero and then in the end we increase it we increase the final answer by one either way it's fine but in this case i'll just initialize with one so and then we have i in the range of of n here right so now since we have already sorted by the uh it means that the width is always it means that the width is always increasing it no it's not increasing it no it's not it's it's not inc it's always it's it's not inc it's always it's always non-decreasing so that's why it's always non-decreasing so that's why like i said like i said for j here right so the j the range is for j here right so the j the range is from from from zero to i here and we need to check from zero to i here and we need to check basically the envelopes that's basically the height right that's basically the height right the height is greater than the than the the height is greater than the than the the j's height then we can do about the j's height then we can do about there's like there's like a little there's a thing one more thing a little there's a thing one more thing you guys need to be careful here you guys need to be careful here because it says both the width and because it says both the width and height has to be strictly height has to be strictly greater so which means that even though greater so which means that even though we're sorting by the we're sorting by the by not by the the weight already but the by not by the the weight already but the weight could could be the same weight could could be the same right so for that case we we cannot right so for that case we we cannot we cannot consider it's it's a valid we cannot consider it's it's a valid valid candidates so which means that valid candidates so which means that basically basically we have to do this zero okay so it means that the first one is the height but still we need to check if the uh if the width is not it's not the same because we have already sorted sorted from sorted the width here but so here we're essentially only checking if the width let's basically i'm only checking if the basically i'm only checking if the current width is now the same as the current width is now the same as the previously weight previously weight then we know okay so we can we can use then we know okay so we can we can use this one this one to calculate our current j here right so to calculate our current j here right so it means that the dp i is equal to the it means that the dp i is equal to the maximum maximum of the dp i and then from dpj of the dp i and then from dpj plus one because so now we have find plus one because so now we have find another envelope so that's why we can do another envelope so that's why we can do another russian doll here another russian doll here right yeah and that's it so in the end right yeah and that's it so in the end we simply return what we simply return what we return the maximum dp yeah so why is that i mean this is because you know if we have like a bunch of numbers let's say for the uh for the li lis right zero one two zero one two 8 right and then 2 8 right and then 2 3 4 6 3 4 6 9 10. i mean basically the the longest the longest increasing subsequence could add any location it could end up here so that's the first that's the first increasing sequence and this is the second one which is which in this case the last one is our final answer but it's not it's not always a true always true right so the longest subsequence could end up at any location so that's why we have to do a maximum of dp yeah so this thing in large in terms of the logic whites i think it is correct if we run the code yeah certainly pass okay sorry yeah so okay sorry yeah so of course we need like this we seem to simply return zero right so we seem to simply return zero right so let me let me submit one more time yeah so this means tle yeah so let me check the details how many yeah so it's almost past everything but it's still tle here so why is that because for the traditional lis longest increasing subsequence solutions this is clearly a o n square solution and even though it didn't give you give and even though it didn't give you give us the range of the of the problem us the range of the of the problem but seems like so this on square but seems like so this on square solution will solution will fail then it only leaves out fail then it only leaves out no other choice but to find a better no other choice but to find a better solution solution which is the the unlock and solution okay explain these things here for you guys explain these things here for you guys see we can have this hmm see we can have this hmm okay i'll just try to explain it here so okay i'll just try to explain it here so let's assuming we have like a bunch of let's assuming we have like a bunch of numbers i'm only numbers i'm only trying to solve this uh is problem let's trying to solve this uh is problem let's say we have a 0 say we have a 0 8 4 10 8 4 10 2 2 [Music] [Music] 6 9 11. how about this longest increasing sequence problem longest increasing sequence problem what is another way to solve this so a what is another way to solve this so a better way is this better way is this basically we're maintaining like a dp basically we're maintaining like a dp here here but in this dp here we're only but in this dp here we're only maintaining maintaining the current the current longest the current the current longest subsequence subsequence we are we can get by by this position so we are we can get by by this position so what does it mean it means that what does it mean it means that in this dp here we're we're always in this dp here we're we're always maintaining like a maintaining like a increasing increasing number increasing increasing number so which means that you know for example so which means that you know for example we have a zero here we have a zero here at the beginning we have zero okay and at the beginning we have zero okay and at at eight here we do and every time since eight here we do and every time since we're maintaining like we're maintaining like always increasing always increasing always increasing always increasing numbers here we can do a binary search numbers here we can do a binary search we can do a binary search to find the we can do a binary search to find the proper insert location for the new proper insert location for the new numbers here numbers here okay so and based on this location okay so and based on this location we'll would decide if if we will replace we'll would decide if if we will replace update the value or we will append this update the value or we will append this value value so at the first one zero of course it's so at the first one zero of course it's zero zero at at number eight here we do a binary at at number eight here we do a binary search search right so we do a binary search and then right so we do a binary search and then what what values we get what what values we get we got like we got a we got one here we got like we got a we got one here so one is the same as the length of this so one is the same as the length of this dp here right so it means that dp here right so it means that okay so the eight is greater than all okay so the eight is greater than all the numbers the numbers in this dp here so so that we will in this dp here so so that we will basically will append we'll append this basically will append we'll append this number to the end number to the end of this dp here and now we we have of this dp here and now we we have four right so we have four here so four right so we have four here so what's the uh what's the uh what's the the what's the index if we do what's the the what's the index if we do a binary search of four a binary search of four it's one right and then basically we'll update 4 here so why is that because so why we can so why is that because so why we can update 4 because you know four is great update 4 because you know four is great it's smaller than eight right because it's smaller than eight right because because four is always smaller than because four is always smaller than eight because we're doing like the uh eight because we're doing like the uh the binary search so it's always the binary search so it's always it's always guaranteeing that it's always guaranteeing that the current the new numbers the new the current the new numbers the new numbers numbers that we are having here will be this that we are having here will be this was either equal or smaller than the was either equal or smaller than the previously previously numbers at the same location and then we numbers at the same location and then we can can we can re we can replace that so this is we can re we can replace that so this is a little bit like greedy a little bit like greedy idea behind the scene here because we idea behind the scene here because we have find have find another number right which is smaller another number right which is smaller than the previous one so that this one than the previous one so that this one may give us a better may give us a better a longer subsequence so that we have a longer subsequence so that we have four here four here and then the next one is 10 right so now and then the next one is 10 right so now the next one is 10 the next one is 10 so 10 is what 10 is okay so 10 is so 10 is what 10 is okay so 10 is another one so 10 is greater than another one so 10 is greater than that everything so that's why we we that everything so that's why we we append append we append these things to the end we append these things to the end okay and now we have two here so what's okay and now we have two here so what's the index of two the index of two it's it's also one here because the two it's it's also one here because the two will be inserted into one will be inserted into one so now what we do we update again right so now what we do we update again right so so we update one with two to ten we update one with two to ten and then what and then six and then what and then six right we have six here so six what's the right we have six here so six what's the index of six index of six is two right so which will be here is two right so which will be here and it will be updating that two to zero and it will be updating that two to zero six sorry 0 2 and 6 and then we have 9 here so 9 is greater than everything so we do a dp equals to 0 2 9 0 6 and 9 right and then the last one is eleven do the same thing six nine and eleven so basically so the present this approach in the end the length of dp will be our answer that's going to be that's going to be 5. so as you guys can see now this business solution the the time complexity will become n log n right because we look through everything n times but with each of the loop here we do a binary search which is a log and that's that's why this this func this solution is much faster and the key observation for this pro for this solution is the uh you know this this append is easier to understand but it's the it's the the most important part is this replace part basically you know every time when we have like a numbers we find the index here we will be replacing that number with the same with the same index so why we can do that because we are still maintaining like the in the increasing pattern here right because we do a binary search we find the the place for this slope for these new numbers and after replacing these numbers we know okay it still complies with this increasing pattern that's why we can we can we can okay so with this in mind okay so with this in mind let's try to use this this one for this let's try to use this this one for this problem right problem right okay cool so so for that you know let me try to come out the first one here i think we can come out here right we need we'll be needing those sort there so like i said you know we'll be maintaining like an empty dp first right and then we'll basically loop the width and height in the envelope the width and height in the envelope and envelopes right so we'll first find and envelopes right so we'll first find the index the index of the we'll do a binary search for the of the we'll do a binary search for the current number current number which is the which in our case which is the which in our case is the uh is the height right because is the uh is the height right because we're searching we're storing this we're searching we're storing this height in this dp okay and we're doing like the by the binary search uh sorry left sorry it's not right it should be left so why is that because the issue with doing a binary search left is because in case of the same numbers here right let's say we have another eight here we come after eight there's another eight we don't wanna append this eight because remember we have a condition right if the current index is smaller than the length then we do a replace otherwise if it's equal to the length we do a we do append and when there is a same eight here we want to get get index one not two because with the left it will give us 1 but if we do a right it will give us 2 which is which is not what we want right so here so the logic like i said so if the index is smaller than the length of the dp okay then we do what we replace we replace this dp index with the current h right elsewhat else we simply append dp append append the current h okay and then we return right so these things it looks pro this right so these things it looks pro this looks promising looks promising but does is this one correct with but does is this one correct with everything here everything here no so why is that we are replacing these numbers right we are replacing these numbers right since you know we have for the one 1d since you know we have for the one 1d like the regular like the regular lis after replacing here right lis after replacing here right we have we have all the numbers in dp we have we have all the numbers in dp still confirm uh i mean following following the the increasing rules here but but here even though right even though we have like this w here we have w but if we're only doing this h here we but if we're only doing this h here we have like we have this w we still need to consider here um you know what let's so the best example is just to submit and this will give us basically that's the example we have we basically that's the example we have we need here right so okay so if we sort if we sort by the by the width and then the height so what by the width and then the height so what we'll have we'll have one we'll have we'll have one one right so that's the and then we have one right so that's the and then we have two three and then we have two three and then we have four and five right and then we have four and five right and then we have four and six and then we have four and six and then we have we have six and seven six and seven we have six and seven six and seven okay so that's the sortings after okay so that's the sortings after that sorted the list and this is okay from one to one this is okay which means we will have like what let's see so in this case we'll have like dp equal to what since we remember we're storing this height in the dp here we'll have one three five okay so we have one three five and then what and then we have we have we have six right but can we use six probably not because we have this thing we have the we have this this i mean this this width we have this this i mean this this width we need to be we need to be to be taken care of because we cannot for this six here we cannot one three five we cannot add at six here because 5 and 6 they have the same same width simply using this numbers here simply using this numbers here so we have to find out another way i mean someone might may think that the uh maybe we can like introducing a width dth array here which will be storing the direct the the corresponding width for each of the height here and every time when we do this kind of index or either insert or update we check we check that that width will not work either this is because so what every time when use when we so what every time when use when we update update when we update this this height here when we update this this height here will be uh sorry when we get the index will be uh sorry when we get the index for this height here we'll be updating for this height here we'll be updating the dp with this height and we're the dp with this height and we're assuming assuming every time when we update this height every time when we update this height here here so the the both of the conditions will so the the both of the conditions will should still be should still be be maintained right be maintained right but if we're doing that if we're doing but if we're doing that if we're doing that even though we have a that even though we have a the weight here it's it will never so the weight here it's it will never so the width the width the the increasing pattern of the width the the increasing pattern of the width will will always be will will always be broken i mean you guys can try to do it i already tried so it won't work even though you're trying to tweak this width an update or where we checked if the width is smaller or greater and then you do append it will always broke it will always so then it only leaves us one com so then it only leaves us one com one option which is to change one option which is to change the sorting a little bit so as you guys the sorting a little bit so as you guys can see here so can see here so the issue happens right here when we do the issue happens right here when we do a four five and four six and the issue a four five and four six and the issue happens when we have happens when we have four and four have the same four and four have the same have the same width and then if we are have the same width and then if we are sorting this sorting this this height in the same increasing this height in the same increasing orders orders so we will process this four five first so we will process this four five first and then we'll process this and then we'll process this four six what does it mean it means that four six what does it mean it means that even though the four four are the same even though the four four are the same we're still considering this five and we're still considering this five and six are valid six are valid a valid increasing sequence so the a valid increasing sequence so the easiest way to fix this is that easiest way to fix this is that we simply reverse these two sortings we simply reverse these two sortings here so now we have one one two three and 4 and the 4 6 right so if we follow the below logic here so we have 1 3 and 6 okay and now we have a right so if we have if we have four and right so if we have if we have four and a five here and we do it we do a binary search instead of three here we'll get two which is which is here so which means that so we will do up update this time and the length is still three so now the problem is soft so what which that means is we simply do a a customized sorting here we do a key equals to lambda lambda what x and what is the key so the key is we stored by x0 ascending order and then we do a sort right so that's that's the sorting and right so that's that's the sorting and that's how we fix this problem here cool so this thing works and submit cool so this thing works and submit yeah as you guys can see this one is yeah as you guys can see this one is super super fast you know super super fast you know this is because the time complexity is this is because the time complexity is is now unlocked in here yeah and if you guys know how to solve this problem instead of doing a reverse sortings here if you guys can find a way of introducing some additional arrays to solve it i would love to know it no know that as well yep and other than that i think it is a great problem you know so the first one the first solution is the traditional dp solutions which is the n square solutions this one is pretty easy to understand right basically we try all the previously enveloped of course we need to sort first and then anyone that satisfies the conditions we we can use that as a candidate and then in the end we return we return the the maximum number and the second one here i mean in the interview i'm not sure if it will if the interviewer will ask you to improve your n unsquare solutions i think thirty percent of of the chance it it might happen so it's at least it's it's better to to know there's like another way of using this dp basically we maintain like the dp arrays here and then we're using a binary search to help us to find the the maximum length so this part i think it's not that hard to understand right basically the why this thing works is because first we're maintaining like a length right and every time when we find the smaller numbers we find the smallest numbers in the uh uh comparing with the previously previously numbers we update the numbers because we know that once we find the place for that right because basically we're we're replacing that number with this number because in later on we might find out like better a better different numbers based on this number right a greater number based on this number that's why okay yeah basically we are as if we are okay yeah basically we are as if we are finding a better finding a better candidate for this for this index candidate for this for this index previously we have an index uh at index previously we have an index uh at index eight here we have so at index one here eight here we have so at index one here we have eight we have eight so now we we have four here so now so now we we have four here so now basically the basically the you know the uh we have better you know the uh we have better candidates at four here so why is that candidates at four here so why is that because we have a because we have a we have eight zero eight four let's say we have eight zero eight four let's say we have we have five and six so we have zero and eight five and six so we have zero and eight we have four here so now we have four we have four here so now we have four because four is smaller than eight which because four is smaller than eight which means that means that between four and eight later on let's between four and eight later on let's say for you for example in this case say for you for example in this case right right we might find a better solutions by we might find a better solutions by using using 4 as this at this index yeah actually speaking of that you know yeah actually speaking of that you know we might can we we we might also be able we might can we we we might also be able to use the uh amount of amount of q to solve this problem you know something like this since we're getting the minimum the increasing sequence i mean every the increasing sequence i mean every time when we have a new time when we have a new numbers here right we pop anything numbers here right we pop anything that's that's that is smaller than the current one and that is smaller than the current one and in the end that's the answer in the end that's the answer right so let me try that you know this might also work let me comment out these things here let me comment out these things here so basically this is what i mean here so basically this is what i mean here while the dp is not empty right and dp minus one sorry or where the four is or either the h is either small or equal or either the h is either small or equal than than the dp minus one okay we do uh oh probably not sorry forget about that you know forget about that it won't work because for in this case we have a 10 and 2 here right but we don't want to pop this 10 out actually that that may also work sorry actually that that may also work sorry because we can update the answers because we can update the answers every time when we have a number here so every time when we have a number here so which means we have answer here it's which means we have answer here it's going to be 0. going to be 0. so we have a while loop here right while so we have a while loop here right while dp is dp is stat and then we do a dp stat and then we do a dp dot pop okay and then dot pop okay and then here i don't know if i'm here i don't know if i'm doing something useful here or not doing something useful here or not and let's have dp dot append and let's have dp dot append append h here right and then we append h here right and then we every time we do update we every time we do update we get a maximum of the answer dot the get a maximum of the answer dot the length of dp length of dp in the end we simply return the answer i'm hoping this will also work yeah let's see okay sorry forget about what i said about the monocule just forget about it so it won't work here all right guys so that's it so stick with the uh the dp and this binary search solution here and cool thank you so much for watching this video guys stay tuned | 2024-03-24 11:20:30 | 354 | LeetCode 354. Russian Doll Envelopes |
|
SC86z-BcmTQ | looking at problem 347 top K frequent elements elements just per usually the three steps just per usually the three steps implementing any problem are one implementing any problem are one understand it to visualize and then understand it to visualize and then three implement it given an integer three implement it given an integer array nums and integer K return the K array nums and integer K return the K most frequent elements you may return most frequent elements you may return the answer in any order the answer in any order you have an example we have one one one you have an example we have one one one two two and a three k is two so we want two two and a three k is two so we want the two most frequent elements and just the two most frequent elements and just with the cursory look we can see there's with the cursory look we can see there's three ones three ones so that's the first one and then there's so that's the first one and then there's two two so that's the second one and two two so that's the second one and that that should be your output that that should be your output example two is just a very basic example example two is just a very basic example we have exactly one number k equals one we have exactly one number k equals one we output one the constraints there's we output one the constraints there's between 1 and 105 numbers each number is between 1 and 105 numbers each number is between negative 104 and 104. and K is between negative 104 and 104. and K is in the range of between one and the in the range of between one and the number of unique elements in the array number of unique elements in the array and it is guaranteed that the answer is and it is guaranteed that the answer is unique unique and here we also have a follow-up your and here we also have a follow-up your algorithms time complexity must be algorithms time complexity must be better than o n log n where n is the better than o n log n where n is the array size array size so there's uh two ways two approaches to so there's uh two ways two approaches to solve this problem that I know the first solve this problem that I know the first one is using heaps the problem with one is using heaps the problem with heaps in for this particular problem is heaps in for this particular problem is that it it does have uh it is an o n log that it it does have uh it is an o n log n time n time so you know it is a good algorithm in so you know it is a good algorithm in general and you know if the problem was general and you know if the problem was just for finding the the most frequent just for finding the the most frequent element then it would uh element then it would uh it would be faster but because it's top it would be faster but because it's top K and you know the constraint is that K K and you know the constraint is that K is between one the number of unique is between one the number of unique elements in the array it is possible for elements in the array it is possible for it to just uh you know the end result to it to just uh you know the end result to just be a heaps or algorithm just be a heaps or algorithm uh where you just Traverse the entire uh where you just Traverse the entire area at which point it's n log n area at which point it's n log n so with that in mind let's do the so with that in mind let's do the approach that's actually uh that can approach that's actually uh that can actually happen in linear time actually happen in linear time and and so so let's take a look at the numbers so so let's take a look at the numbers here so we have these one one ones and here let's keep tabs uh since your frequency frequencies so we're iterating we see and let's see so one is starting off uh two is zero we have three numbers we're we're tracking uh number to frequency so we just iterate over each one one that's one it's another one of those guys those guys now for two we see one let me see a second and then three we see one so like this is just a do you need to do this like whatever approach you take you need to just you know count the frequency of each number and you know the question then becomes how can you um then in uh without sorting your numbers or your key value pairs in any way like still give out the K most frequent elements so that's where the that's where the magic happens and let's just uh let's first Implement what we've done so far of just getting our frequencies and then let's discuss how to just uh just return the K most freaking elements the map uh let's call this a frequency map just like we did a new map and then we iterate of our numbers just as we iterated earlier and let's see if uh brick map that has num like we've already looked at this number before otherwise otherwise we reset it to one oh and then sorry uh that guy to that and then this guy to just one okay so that's how much we've reviewed so far in in our examples and our visualization and now we have to think about uh this interesting JavaScript Quirk which revolves around how arrays are unbounded um wait let's create an array I already is you know just an empty I already is you know just an empty array array and and Let's uh let's take the the frequencies Let's uh let's take the the frequencies and make these the make the indexes of and make these the make the indexes of the frequencies the frequencies make the frequencies into indexes and make the frequencies into indexes and then the the values into these numbers then the the values into these numbers and so in example one three so that's and so in example one three so that's the frequency is equal to this one the frequency is equal to this one in the case here our frequency is two we in the case here our frequency is two we make this equal to two make this equal to two and then our frequency here one is equal and then our frequency here one is equal to the number three to the number three now look at how our array looks now now look at how our array looks now so we've actually like expanded the so we've actually like expanded the array like we didn't have any problems array like we didn't have any problems we said now it's actually its length is we said now it's actually its length is now four and it has this you know empty now four and it has this you know empty value value and and we can take this property of JavaScript we can take this property of JavaScript and what we're going to do is we're and what we're going to do is we're going to move all the frequencies going to move all the frequencies uh we're gonna we're gonna like do this uh we're gonna we're gonna like do this exact same process of filling up an exact same process of filling up an array with uh the frequency indexes array with uh the frequency indexes mapped to their number values mapped to their number values uh the one one more thing is like uh the one one more thing is like imagine imagine we also had we also had uh four and four uh four and four then we would actually see the number then we would actually see the number four is frequency is two four is frequency is two and we see that these two overlap so so and we see that these two overlap so so you know you know zero one two units value is two we don't zero one two units value is two we don't want to override it with four want to override it with four so we can use a different data structure so we can use a different data structure instead of just uh a single number we instead of just uh a single number we can do a set can do a set and just uh have sets for each of these and just uh have sets for each of these and that that will solve so I can just and that that will solve so I can just show you with the set example looks that show you with the set example looks that are are is that is that then we would say then we would say R so start from beginning R3 R so start from beginning R3 equals new set equals new set add one add one then we hit look at the next guy our 2 then we hit look at the next guy our 2 is equal to new set add is equal to new set add uh uh two two look at the next guy the frequency is look at the next guy the frequency is one R1 equals new set add three one R1 equals new set add three and then we look at the last guy so this and then we look at the last guy so this is R2 so this guy already has a value so is R2 so this guy already has a value so we can say R2 dot add we can say R2 dot add four four and oh shoot I didn't add to our oh you and oh shoot I didn't add to our oh you know it's okay like I I created a new know it's okay like I I created a new set but you can see I overwrote the the set but you can see I overwrote the the previous area but you can see how it previous area but you can see how it looks like so three then we have these looks like so three then we have these two two four and then one two two four and then one and at that point because they're and at that point because they're already sorted from largest to smallest already sorted from largest to smallest we can just go back until we've uh you we can just go back until we've uh you know K number of elements and just know K number of elements and just return those and we are done return those and we are done so let's Implement what we just so let's Implement what we just described described we are obviously other frequency maps and we want to create our in our and we want to say or let and we want to say or let you know key value of our if I set our if uh if if this already exists then we can our value dot add key so that's exactly what we did down here uh we just added four in that case otherwise set r equals new set key dot add oh sorry a news oh sorry a news oh no it's just new set dot add oh no it's just new set dot add key okay there we go key okay there we go and you can see what this looks like and you can see what this looks like it should look the same as what we it should look the same as what we already did and what example do we run and there you have it so you have this and there you have it so you have this three and then you know if I were to add three and then you know if I were to add the fours that we did in the second the fours that we did in the second example example oh uh oh uh I guess we can use that for this example I guess we can use that for this example but you can see that you have these sets but you can see that you have these sets so at this point we just need to iterate so at this point we just need to iterate over our sets until you know filling up over our sets until you know filling up our result our result and return our result and return our result so we need to iterate K number of times so we need to iterate K number of times and then we are out we're out of here and then we are out we're out of here for let I equal remember we had to start for let I equal remember we had to start from the right hand side because the for from the right hand side because the for the art to the right the larger number the art to the right the larger number of frequencies you are set our I think minus one I is greater or equals to zero I minus minus so we say so so remember that we have these empty items so we want to clear those guys out and there's no set r i just uh you know skip over that but now we actually do have a number so result dot push set r i and then we want to say if you know how have we already exhausted the K number of elements like how do I already have you know K elements in the array let's ask that question so that length greater equals to K you know we want to stop adding stuff to our area let's just call it quits let's see this guy runs to that path example cases okay and there you have it that's the okay and there you have it that's the first approach with the unbounded array first approach with the unbounded array approach approach now let's look at how we would solve now let's look at how we would solve this with a a heap like a like a heap this with a a heap like a like a heap strategy strategy so this is uh you know it won't perform so this is uh you know it won't perform as well but it's still good practice to as well but it's still good practice to know how to do heaps so as a reminder a know how to do heaps so as a reminder a heap is a heap is a is a data structure where it it's an is a data structure where it it's an array but it's in when we think about it array but it's in when we think about it and treat it like it's a binary tree and treat it like it's a binary tree an example you know again if you don't an example you know again if you don't remember so you know the array one two three four five six seven eight we represented as a so the first thing you need is a so the key element of a heap is a heapifying function and you know as a as a reminder like a a big summary of what we're going to do is we're just gonna add our heapifying function that that you know churns arrays into heaps as a reminder a heap is uh it could be their Max Heap or Min Heap uh this is an example of a mini heat because the root node is the smallest value Max Heap would be where the root node is the largest number we are going to do Max Heap because we're we're only really interested in we want to do a Max Heap where we where the the numbers with the highest frequencies are at the closest to the root or at the root of the tree and so yeah we're not concerned at all with Min heaps only Max heaps and we need a keepifying function and all you need to do a heapifying function you need the array and you need the index value and you need to know how to uh you know grab the no no what the left and right note of the tree is and you know so so I I won't describe this in all detail like if you're really interested like definitely check out our uh video on sorting algorithms using the Heap Sort algorithm so let me just uh assume you know that I'm just gonna write what we have to do I'm gonna try to not make this video too long times two plus one let's write equals left plus right that largest equals index we need uh to bound our Heap let Heap boundary equals uh so what will this be oh oh so so we do need to know like how many unique items there are if you want to use the heapsort approach so let's quickly grab that so unique nums equals a frequency map how will you get that so we have frequency map that keys are the unique frequency map that keys are the unique numbers numbers and then we say and then we say nums the length nums the length and the reason we need the heat boundary and the reason we need the heat boundary is that as we like in any good Heap Sort is that as we like in any good Heap Sort algorithm algorithm at a certain point like you're going to at a certain point like you're going to be you're going to have your numbers at be you're going to have your numbers at the perfect position like the largest the perfect position like the largest number will be at the rate of the array number will be at the rate of the array and you don't want to accidentally run and you don't want to accidentally run your keepifying function on that number your keepifying function on that number and you know reintroduce it into the and you know reintroduce it into the array so we need to set up like a array so we need to set up like a boundary where our algorithm no longer boundary where our algorithm no longer runs to keep those numbers safe and runs to keep those numbers safe and locked in locked in so if so if left is less than our boundary left is less than our boundary and and free map dot get free map dot get will this be that get uh our will this be that get uh our left left is greater than freak map.get our is greater than freak map.get our largest largest then that means that we actually have a then that means that we actually have a number that has higher frequency number that has higher frequency largest equals left largest equals left and do the exact same thing for the and do the exact same thing for the right side and then then you get Heap function would do if R just does not equal index then we need to do a swap let's define a swapping function temp this is just boilerplate stuff temp this is just boilerplate stuff are right equals our left are right equals our left oh it should be the other right around oh it should be the other right around and then our right equals temp and then our right equals temp and then I guess call that guy so we and then I guess call that guy so we pass our array and then large is an pass our array and then large is an index so we swap them and then we need index so we swap them and then we need to just to just uh check all the uh check all the the inner inner notes make sure that the inner inner notes make sure that they're nicely humified as well they're nicely humified as well because we did this change we need to because we did this change we need to compare against our you know the the compare against our you know the the value that we swapped out value that we swapped out so that's the hebify function and the so that's the hebify function and the only distinction here between here and only distinction here between here and the user algorithm is that we we want to the user algorithm is that we we want to just compare the frequencies we don't just compare the frequencies we don't want to get want to get the compare the actual numbers because the compare the actual numbers because the numbers themselves aren't relevant the numbers themselves aren't relevant and so so so at this point we're just and so so so at this point we're just simply just writing a heapsort algorithm simply just writing a heapsort algorithm it's just it's a two-step process the it's just it's a two-step process the first step is to run the Heap Sort first step is to run the Heap Sort algorithm from right to left and that algorithm from right to left and that what that will do is that at the end of what that will do is that at the end of doing that the largest number will 100 doing that the largest number will 100 be at the leftmost spot at you know be at the leftmost spot at you know index zero and then the second step is index zero and then the second step is we take that value we swap it with the we take that value we swap it with the rightmost number and then we move this rightmost number and then we move this heat boundary down one to lock it in and heat boundary down one to lock it in and protect it from ever being heapified protect it from ever being heapified again again so it'll so we're basically we'll so it'll so we're basically we'll basically be sorting the uh the array basically be sorting the uh the array and and then we'll grab the K elements and and then we'll grab the K elements the rightmost side of the array and then the rightmost side of the array and then call it quits call it quits for that I equals for that I equals uh unique so we should at this point we let me just log this to double check let me just log this to double check something so let's actually make this a full array so let's actually make this a full array like we're done with treating it like uh like we're done with treating it like uh like you know a different type of data like you know a different type of data structure let's just keep symbol with an structure let's just keep symbol with an area okay so for that I equals unique nums the length minus one so that'll be the rightmost number I is greater equals to zero minus minus array and our area will actually be unique nums so so that that will and you can see so so that that will and you can see that the rightmost number will be left plus one yeah okay yeah okay so yeah there's the the one is at the so yeah there's the the one is at the rightmost side rightmost side and two is there next so and two is there next so this is looking good this is looking good and now we need to and now we need to grab the leftmost number move it to the grab the leftmost number move it to the right and close down or bound right and close down or bound and then so it's that for let I equals and then so it's that for let I equals in terms of length minus one in terms of length minus one I is greater than equals to zero I minus I is greater than equals to zero I minus minus minus so we want to swap unique nums we want to swap the left and right and we want to close down our heat and we want to close down our heat boundary and then we want to because the numbers may have changed and like that that rightmost number is necessarily at the right Heap spot let's hipify that guy and then we can just return pick numbers of length minus k pick numbers of length minus k and let's see how that does and let's see how that does that example I think the other these that example I think the other these examples and there you have it we have implement this with a heap and we have implemented this with uh using an unbounded rectangle strategy so thank you and | 2024-03-24 11:10:08 | 347 | Visualize Leetcode 347: Top K Frequent Elements |
|
u4-ZzRTr1Ag | what's going on guys welcome back in this video we are going to be solving this video we are going to be solving leap code problem number one Numero Uno leap code problem number one Numero Uno and it's going to be the two sum problem and it's going to be the two sum problem so get excited guys let's go ahead and so get excited guys let's go ahead and jump straight into the code jump straight into the code [Music] so let's get started by checking out the prompt guys so they're going to give us an array of integers and a Target and they want us to return the indices of the two numbers such that they add up to the Target so really quickly it's pretty straightforward if we just look at this example in this array here the reason we get back zero and one is because two plus seven equals nine which is our Target and 2 is at index 0 7 is at index one in our array and they explain it down here and then you know down here we get back one and two because two plus four is six and two is at index one four is it index two so it's pretty straightforward so with that being said let's just go ahead and hop straight into the code so the first thing I notice guys is that the problem is asking us to return an integer array so what I'm going to do to start this off is create that array and we know it has to be an integer array I'll call it result and then down here at the bottom we're just going to return that result and we know that in order to solve this problem we just need to go through this numbers array that they give us and see if we can find values A and B such that a plus b equals our Target which we can call C or something like that so I'm just going to add that as a note here in my problem trying to find two numbers such that a plus b equals c okay so the easiest way to accomplish this would be to use nested for loops and what we could do is start let me just go ahead and get my array copy and paste it over here so we can take some notes with it let me just create a multi-line comment here as well and paste this in here cool so this is our array so I'm going to put seven at the end guys and put 15 right here just to illustrate this concept a little bit better so basically we would we would start one loop at two and then within that have another loop that goes and checks every number after two and we would just have some logic in there that says hey if any of those two numbers equal the target then we know we can return the indices of those and solve our problem so let's go ahead and just code this out so basically we would say 4i in 0 up to nums.count so this would start our Loop here at the first end of X the first index of the array then we would want to check every number after that within this iteration right and then we would go to 15 and check all the numbers after 15 then go to 11 check all the numbers after that so that's where the second for Loop comes in and here's the trick to this we would say 4 J in I plus 1 up to but less than nums.count so what this does is it's going to take a look at what I is at the time right so it starts at zero then it's going to start this second loop at one because 0 plus 1 is 1 and it's going to go to the end of the array and at each point we're just going to check and see if any if any of these guys plus 2 is equal to our Target so we would say if nums I plus nums J equals Target I comma J so you guys could also say I comma J so you guys could also say results equals I results equals I J which we can do for now and we can J which we can do for now and we can discuss why the other way is better in discuss why the other way is better in just a second let's just go ahead and just a second let's just go ahead and run this to see if it works so we notice that this does solve our problem right but this is not the most optimal solution for this problem so we're going to go over how to optimize this version of it and then create an entirely different algorithm to solve this program or this algorithm in a way more efficient fashion so to illustrate why this is not the most effective way with the Brute Force approach guys I'm just going to add a print statement here so I'm going to say print and let's just print out the result of num's eye we'll see that I get a bunch my program we'll see that I get a bunch my program continues to run even after I found the continues to run even after I found the correct solution so you guys will notice correct solution so you guys will notice that I get a bunch of print statements that I get a bunch of print statements here right but the correct answer here here right but the correct answer here is nine so all of these additional is nine so all of these additional Loops or iterations of my Loop that I Loops or iterations of my Loop that I did were completely unnecessary so I'm did were completely unnecessary so I'm getting the right answer but it's not getting the right answer but it's not the most efficient way of doing it so the most efficient way of doing it so basically what I want to do is as soon basically what I want to do is as soon as I find the two numbers that satisfy as I find the two numbers that satisfy this condition I just want to return this condition I just want to return those numbers so we're sorry the indices those numbers so we're sorry the indices of those numbers and this way as soon as of those numbers and this way as soon as I find my solution the execution of my I find my solution the execution of my program will stop right then and there program will stop right then and there so let me run this again and you'll so let me run this again and you'll notice that we get back a single print notice that we get back a single print statement and it's just going to be nine statement and it's just going to be nine so yep that's all we get back and you so yep that's all we get back and you guys notice that we didn't get back all guys notice that we didn't get back all of those other print statements because of those other print statements because our program stops as soon as it hits our program stops as soon as it hits this guy so to illustrate this a little this guy so to illustrate this a little bit better bit better I'll change this around where I put I'll change this around where I put seven at the end of my test case so you seven at the end of my test case so you guys could just go to the test case tab guys could just go to the test case tab right here and you could customize this right here and you could customize this to have whatever test case you want to have whatever test case you want you guys will see that we get back you you guys will see that we get back you know a couple more print statements but know a couple more print statements but it's still a more efficient solution so it's still a more efficient solution so at first we get back 17 then 13 then at first we get back 17 then 13 then none and then we stop because we found none and then we stop because we found our answer so that is a good way of our answer so that is a good way of optimizing The Brute Force approach but optimizing The Brute Force approach but the Brute Force approach in and of the Brute Force approach in and of itself is not the most optimal solution itself is not the most optimal solution for this problem it's in fact the worst for this problem it's in fact the worst way to solve this problem so if we were way to solve this problem so if we were to look at the Big O notation or runtime to look at the Big O notation or runtime complexity of this on this chart here we complexity of this on this chart here we would be in the O N squared time would be in the O N squared time complexity and that's because we have to complexity and that's because we have to use that nested for Loop and essentially use that nested for Loop and essentially visit every element in the array twice visit every element in the array twice basically so we are at O N squared so we basically so we are at O N squared so we notice that as my array gets larger my notice that as my array gets larger my time complexity significantly increases time complexity significantly increases which is very bad we can solve this which is very bad we can solve this problem in o n time which you can see is problem in o n time which you can see is way more effective than O N squared way more effective than O N squared right this goes parabolic parabolic in right this goes parabolic parabolic in terms of its time complexity and we can terms of its time complexity and we can see that it is terrible right so this see that it is terrible right so this guy is fair which is what we want for guy is fair which is what we want for this problem so let's talk about how we this problem so let's talk about how we can accomplish this well we're going to can accomplish this well we're going to be using something called a map or a be using something called a map or a dictionary and basically what we can do dictionary and basically what we can do is use it as a lookup tool to see if we is use it as a lookup tool to see if we can find the complement of this equation can find the complement of this equation right so imagine we are looking for a right so imagine we are looking for a number B such that a plus b equals c number B such that a plus b equals c well we could say that hey if I have B well we could say that hey if I have B which equals c minus a right this is which equals c minus a right this is what's known as the complement of B and what's known as the complement of B and we can store all of those values in a we can store all of those values in a map to look it up then we know that we map to look it up then we know that we have solved our problem so that's what have solved our problem so that's what we're going to be doing to solve this we're going to be doing to solve this more efficiently guys so let's go ahead more efficiently guys so let's go ahead and code it out and then I'll break it and code it out and then I'll break it down a little bit further because I know down a little bit further because I know that sounds a little bit confusing so that sounds a little bit confusing so let's go ahead and just delete all this let's go ahead and just delete all this code or you guys could comment it out if code or you guys could comment it out if you'd like but basically I'm going to you'd like but basically I'm going to create a map here and it's going to be create a map here and it's going to be an integer to integer dictionary so an integer to integer dictionary so basically we're going to have this key basically we're going to have this key value store and it's going to store an value store and it's going to store an integer as the key and have an integer as the key and have an Associated value as the key so we're Associated value as the key so we're going to go over how to populate this going to go over how to populate this dictionary in just a second dictionary in just a second so if you guys are uncomfortable or so if you guys are uncomfortable or unfamiliar with dictionaries I highly unfamiliar with dictionaries I highly recommend checking out a video recommend checking out a video instructional on maps and when if you're instructional on maps and when if you're watching this in the lead code killer watching this in the lead code killer course I will have a video posted on course I will have a video posted on this in the data structures intro this in the data structures intro section but if you guys aren't section but if you guys aren't comfortable with maps or how to use them comfortable with maps or how to use them I highly recommend checking that out so I highly recommend checking that out so anyway guys let's continue with the anyway guys let's continue with the solution to the problem we're still solution to the problem we're still going to need to run a for Loop here so going to need to run a for Loop here so we're going to say 4i in 0 up to nums we're going to say 4i in 0 up to nums dot count dot count and what we need to do is store the and what we need to do is store the complement here in a value so I'm going complement here in a value so I'm going to say let comp to say let comp equal Target minus equal Target minus nums I nums I so now that I have this complement value so now that I have this complement value right so I'm going to Simply do a lookup right so I'm going to Simply do a lookup in my dictionary and see if I can find in my dictionary and see if I can find that value in my dictionary and if I can that value in my dictionary and if I can return the associated value with it return the associated value with it which in this case will be the index of which in this case will be the index of that number so I'm going to say if let that number so I'm going to say if let index equals map index equals map comp comp return I return I in the index and if we can't find that in the index and if we can't find that then we just need to make sure that we then we just need to make sure that we actually populate this map with the actually populate this map with the correct value so we're just going to correct value so we're just going to store num's I and its Associated index store num's I and its Associated index so I'm going to say map so I'm going to say map nums I nums I default zero default zero equals I and you guys will notice that equals I and you guys will notice that this is going to solve our problem too this is going to solve our problem too we just need to add a return statement we just need to add a return statement down here so outside of my for Loop just down here so outside of my for Loop just go and say return some blank array so if go and say return some blank array so if we obviously can't find any two values we obviously can't find any two values that satisfy this condition we would that satisfy this condition we would just return a blank array so let's run just return a blank array so let's run this and see if it works so we guys know you guys notice that this works as well so what I want us to do to break this down guys and make it easier to understand is actually add some print statements here so we can see what's happening at every step of the problem so first thing let's comment out this return statement just so that we can see what's happening at every iteration of the problem and below this line here where we set up where we populate the map with values let's go ahead and say print comp is comp and then let's print the map as well and then let's just print out like a line with a bunch of dashes to get some separation here and let's run our code and talk about what's happening line by line so this is our input array guys remember we modified it slightly from what we got back in the example we just put seven at the end to make it more interesting but let's go ahead and just scroll down and take a look at all these print statements which is really going to help us make sense of this solution so we're just going to break this down step by step so basically we've created our map here and then we start looping through our nums array right and we store this complement in a value which is equal to Target minus nums I and if you guys remember the logic we're trying to find two numbers such that a plus b equals c so the complement of B would equal C minus a and on the flip side the complement of a would equal beam or C minus B so that's what we're storing here right in this complement value so here we see that the complement is seven first up because 2 is the first value in our array nine minus 2 is 7. so this piece of code that comes up next is very important guys so what this is doing is trying to look up the complement in our dictionary because we know that if the complement exists in the dictionary that we have solved our problem because we have seen that number before which is the number that we're looking for right we are currently looking at 2 the complement is seven so if 7 is in my dictionary I know I've seen it before and 2 plus 7 satisfies the conditions of my problem it equals nine so I'm trying to look that up and see if it's in there and it's not because there's nothing in our map so then we go down to line 12 where we actually populate our map with a value so we're saying hey in the future if we ever see seven again I just want to look up and see if two exists in the dictionary and give back this Index right here which is the location of two in the array which is what I need in this situation right I need to know if 2 is in the dictionary and if it is what index that it's at because that's what the problem's asking me to return the indices of the values that add up to my target so that's why we get back the complement is seven and then currently our map is 2 and 2 is at index 0. so then we move on to the next value right the complement is negative six because nine minus 15 in this case is negative six and then we try to find that in our dictionary and we obviously can't because um the complement of that doesn't exist in our map so it just stores 15 at the one index so we keep going same thing happens for negative two um or sorry when the complement is negative two and then this is what our map looks like 11 is at index 2 15 is at index one two is at index 0. and here on this last iteration is where we actually solve the problem right so let's break this down because this is the key to understanding the solution so we are looking at the complement here right what is the complement of seven such that some number plus seven equals nine well it's two right so in this case the complement is two and when we go to look that up in our dictionary in this case we have two in the dictionary so when we go to do that lookup it says oh hey dude 2 is there and that's exactly what you're trying to find because in relation to the number seven and the number nine two is the value that we need and we need the index that it is located at in the original array of nums so we find that value and then this gives us back the index of it right that's the value associated with two and then we stop there and we return I which is the current index that we're on in the array which is seven and we needed to look up and find two which is in our map and it's at index 0. so this would return three and zero and luckily for us guys we can return the numbers in any order so we could return it a zero one or one zero it doesn't matter so really quickly just to make sure this works with all text test cases guys go ahead and delete that and let's uncomment our return statement and let's just go ahead and hit submit and see what this gives us back so we notice that that does solve our problem and the numbers look really really good here right guys it's better than 91.72 percent of all Solutions in terms of runtime and beats 86.4 in terms of memory so that is going to wrap it up for this video guys that is lead code problem number one the twosome problem we went over how to solve it in a really good way and a really bad way and went over the differences between the two so hope you guys enjoyed this video we'll | 2024-03-18 09:35:54 | 1 | The CORRECT Way To Solve Two Sum | LeetCode #1 |
|
7dKiBCY-HmQ | hi everyone let's all today's daily challenge that is zigzag conversion so challenge that is zigzag conversion so in this question we are given a string in this question we are given a string and it is written in a zigzag pattern on and it is written in a zigzag pattern on a given number of rows like this right a given number of rows like this right and then what we are doing is we are and then what we are doing is we are taking the first row of it and then taking the first row of it and then after the first row we are appending the after the first row we are appending the second row and to that second row we are second row and to that second row we are appending this third row so we get a appending this third row so we get a string like this and that is what we string like this and that is what we have to return so we have to write a have to return so we have to write a function in which it will be taking a function in which it will be taking a string and then it will be creating such string and then it will be creating such a pattern a zigzag kind of a pattern out a pattern a zigzag kind of a pattern out of it and then we will consider all of of it and then we will consider all of its rows right and we have to Simply its rows right and we have to Simply return return a pattern that we will be obtaining a pattern that we will be obtaining after reading this pattern row by row so after reading this pattern row by row so let's understand uh what this exact let's understand uh what this exact pattern in this question means so in pattern in this question means so in this question the zigzag pattern that this question the zigzag pattern that they are considering is like this right they are considering is like this right so we will have something like this so we will have something like this so this is the zigzag pattern that they so this is the zigzag pattern that they are considering so let's uh try to are considering so let's uh try to understand it for n is equal to 3 what understand it for n is equal to 3 what this exact pattern is so when n is equal this exact pattern is so when n is equal to 3 we will be having 0 1 2 3 rows to 3 we will be having 0 1 2 3 rows right and within these three rows we right and within these three rows we have to form this exact pattern so how have to form this exact pattern so how will we forming this exact pattern so we will we forming this exact pattern so we will consider will consider p a y along this and then we have to p a y along this and then we have to fill this diagonal so we will fill P fill this diagonal so we will fill P here here right and then we will fill out a l i right and then we will fill out a l i then again we have the diagonal so we then again we have the diagonal so we will put s here and then we will will put s here and then we will consider h i consider h i and R and then we will have and R and then we will have um I here and N here and G here right so um I here and N here and G here right so this is the zigzag pattern that will be this is the zigzag pattern that will be forming okay now what we have to do we have to take we have to take its rows right so we then we have to take this then we have to take this a p l s i i and G and then we have to a p l s i i and G and then we have to consider the third row and we have to consider the third row and we have to append it append it to our resultant string so this is what to our resultant string so this is what we have to return right we have to return right so now um let's do it for n is equal to so now um let's do it for n is equal to 4 4 so that things will be more clear to you so that things will be more clear to you now we'll do it for n is equal to 4. now our n is 4 okay so how do we have to form this exact pattern you have to form this exact pattern so we have four rows here 0 1 2 and 3. so we have four rows here 0 1 2 and 3. so we'll Place p so we'll Place p a y and p here and then we will have a a y and p here and then we will have a L along the diagonal then we will have I s h and I and then we will have R and I here and n and G here right so this is the pattern that we will be forming and then what do we have to do we have to take row wise character so first we will have p i n then we will have a l s i g then we will have y a h r and then we will have p and Pi so this is the resultant string and that is what we have to return so I hope you uh you are clear with the zigzag pattern that we are considering in this question so let's see how we will solve it so uh let's see how will we get the first row if you try to evaluate that how will we get the first row so we have P right so how many characters do we have to skip to get to I right so it will be 1 2 3 4 5 and 6 right so the sixth character we have to take right then again one two three four five six six character we have taken from here how many steps do we have to take one two three four five and six so we will get n right so this is how we will get the first row right let's see for second row for second row what we'll be doing will for second row what we'll be doing will again be doing the same thing again be doing the same thing will come to a now and from a how many will come to a now and from a how many steps do we have to take steps do we have to take so if we take uh six steps where will we so if we take uh six steps where will we reach so one two three four reach so one two three four five and six right so at the sixth step five and six right so at the sixth step we have S right then after S one two we have S right then after S one two three four five and six we get G but three four five and six we get G but what about L and I they are also in this what about L and I they are also in this row right and we have to consider them row right and we have to consider them so how can we get lni so let's say from so how can we get lni so let's say from a how many steps do we have to take so a how many steps do we have to take so we have to take one two three and four we have to take one two three and four so at the fourth step we will be getting so at the fourth step we will be getting L right and similarly from S at the one L right and similarly from S at the one two three and fourth step we will be two three and fourth step we will be getting I getting I so what did we do so what did we do so first of all uh how will we get six so first of all uh how will we get six steps right so if I just do 4 minus 1 steps right so if I just do 4 minus 1 into 2 is it equal it is equal to 6 into 2 is it equal it is equal to 6 right right similarly for L and I if I subtract 6 similarly for L and I if I subtract 6 minus 2 what do I get 4 so we are minus 2 what do I get 4 so we are considering four steps for it right considering four steps for it right now let's move on to the third row for now let's move on to the third row for the third row we are at y here right so the third row we are at y here right so we are at y we are at y from y if I take six steps where will we from y if I take six steps where will we reach one two three four five and six we reach one two three four five and six we will come at H right and after that we will come at H right and after that we don't have anything here so we'll not be don't have anything here so we'll not be getting anything we'll be going out of getting anything we'll be going out of the bounds of the length of the string the bounds of the length of the string right so we will get y h how to get a right so we will get y h how to get a and r and r so from y it is at a distance of 1 and so from y it is at a distance of 1 and 2. and from h r is at a distance of one 2. and from h r is at a distance of one and two so what are we doing now we are and two so what are we doing now we are doing 6 minus 4 that is 2. doing 6 minus 4 that is 2. right we're also doing this right we're also doing this along with the six steps for each and along with the six steps for each and every Row for each and every character every Row for each and every character along with the six steps we are also along with the six steps we are also taking taking the numbers at 4 sorry the num the numbers at 4 sorry the num characters at a fourth and second steps characters at a fourth and second steps right we are also considering these right we are also considering these so uh can we generalize it so if I do so uh can we generalize it so if I do six six minus 2 into that particular row that is minus 2 into that particular row that is 1 here 1 here so I will get 4 for the first row so I will get 4 for the first row similarly if I do for the second row similarly if I do for the second row what will I get what will I get I will get 2 here right because for the I will get 2 here right because for the second row I is equal to 2. so I hope second row I is equal to 2. so I hope the pattern is clear to you now right so the pattern is clear to you now right so what we'll be doing we will be taking what we'll be doing we will be taking the number of rows minus 1 into 2. the number of rows minus 1 into 2. these many steps and then we will be these many steps and then we will be skipping it so for first and the last skipping it so for first and the last row you can see that we can simply get row you can see that we can simply get the whole row by taking six steps at a the whole row by taking six steps at a time right so P then six steps I then time right so P then six steps I then after six steps we get n so our first after six steps we get n so our first row is complete similarly for the last row is complete similarly for the last row what do we have to do because we row what do we have to do because we don't have any diagonal characters here don't have any diagonal characters here right we don't have any diagonal right we don't have any diagonal characters so we can simply do six steps characters so we can simply do six steps for the first and the last two only for for the first and the last two only for the middle rows we also have to consider the middle rows we also have to consider characters at these steps also right so characters at these steps also right so I hope the um logic of the problem is I hope the um logic of the problem is clear to you and the pattern is also clear to you and the pattern is also clear to you select quickly code it out clear to you select quickly code it out so what do we have to do first of all also there will be a base case and that base case is that if the number of rows given to us is one in that case we simply have to return this string because in that case we will not be able to form any zigzag pattern so if num rows is 1 right then we have to Simply return this string s now what if this uh number is not one then we have to Traverse in these rows right as we saw we'll be going from uh this row this row this row and this row right for four all the four rows we will I is equal to 0 I less than num rules I is equal to 0 I less than num rules right the number of rows and I plus plus right the number of rows and I plus plus now let's also make the string in which now let's also make the string in which we'll be appending everything uh let's we'll be appending everything uh let's call it result call it result right and let's initialize it to null right and let's initialize it to null and also we have to consider the number and also we have to consider the number of jumps that we will be doing so the of jumps that we will be doing so the number of jumps number of jumps right or the number of steps that we right or the number of steps that we will be skipping are will be skipping are numb Rose numb Rose minus 1 into 2 right so these are the minus 1 into 2 right so these are the number of jumps number of jumps so after this so after this so for each and every row what do we so for each and every row what do we have to do we have to take these many have to do we have to take these many jumps so let's also jumps so let's also create a loop for that so we'll be going create a loop for that so we'll be going from J is equal to I that particular from J is equal to I that particular index index to J less than to J less than the size of the string the size of the string and then what we'll be doing will be and then what we'll be doing will be taking jumps number taking jumps number of steps right of steps right and that is what we'll be including in and that is what we'll be including in our resultant string so we will add our resultant string so we will add jumps here now jumps here now we have to add we have to add the characters at this particular jump the characters at this particular jump right so it will be inside of J only right so it will be inside of J only right so we will take s of J here but we right so we will take s of J here but we also saw that also saw that for first and the last row it is okay for first and the last row it is okay right but for the middle rows right as right but for the middle rows right as we saw for the middle rows we also have we saw for the middle rows we also have to consider the characters at to consider the characters at then jumps minus 2 into that particular then jumps minus 2 into that particular row number we also have to consider row number we also have to consider these diagonal elements right so for these diagonal elements right so for these diagonal elements this is what we these diagonal elements this is what we will be doing so let's see will be doing so let's see so first we will check if so first we will check if we are in Middle rows we are in Middle rows right if I is greater than 0 and less right if I is greater than 0 and less than num rows minus than num rows minus rows minus 1 rows minus 1 right and also right and also and also this particular index that we and also this particular index that we are considering that is 6 minus 2 into I are considering that is 6 minus 2 into I if it it is also in Bound that is it is if it it is also in Bound that is it is less than less than it is less than the number of jumps it is less than the number of jumps sorry the number of the size of the sorry the number of the size of the string right so J plus jumps minus string right so J plus jumps minus um it will be 2 into that particular row um it will be 2 into that particular row that we are at if it is less than that we are at if it is less than the size of the string only 10 what do the size of the string only 10 what do we have to do we have to add this we have to do we have to add this particular index also in our resultant particular index also in our resultant string right so that will be this string right so that will be this particular index only particular index only 2 into I right so what this will do is 2 into I right so what this will do is for for this row will be consider from a for for this row will be consider from a we also have to consider the fourth step we also have to consider the fourth step right one two three four so we also have right one two three four so we also have to consider n to consider n so along with a after this it will so along with a after this it will append at the fourth step and append at the fourth step and then it will append then it will append the next character which is at sixth the next character which is at sixth step and then again from here it will go step and then again from here it will go here and it will append this I which is here and it will append this I which is at the fourth step and then it will also at the fourth step and then it will also append the G that is at the sixth step append the G that is at the sixth step so this is how it will be working and so this is how it will be working and after this Loop we will simply return after this Loop we will simply return the string the string so let's run it right so it's accepted let's quickly submit it so that's how um you have to solve this | 2024-03-18 11:36:17 | 6 | 6. Zigzag Conversion | LeetCode Feb challenge | C++ |
|
h4Dq1UntKdk | anthony what he did what he did or didn't do in the country in game to Busquets they know a game of I'm fine he said and it's not up to them valdez valdez the same as always the water although there is show credit suisse first world brown defense information there is fastball 36 modified five the one being the three are spam one in like like web slices attack web slices attack which was the five in the usa five 2 shot laude 3 ace ace then of lacy croce ice ice in private lamy wave white and you don't realize that I'm going from israel and you don't realize that I'm going from israel wing black hawk ride soul wing black hawk ride soul among the issues that luckily I am among the issues that luckily I am I returned both types of interest from here I returned both types of interest from here with cruelty monster example of this with cruelty monster example of this one of one of one of multi of 56 like one I say sexy la de child of by jane lynch by jane lynch like one schuchat like agents trick like one tourists who go out in ray charles ford web show included committed 6 committed 6 committed 6 one2one was committed in the fis west of one2one was committed in the fis west of the west indies walsh security and the west indies walsh security and venice is going to be venice is going to be yang wei I go to a place tour and as one in retail best seller one in retail best seller one jaguars these tests we are going to discard jaguars these tests we are going to discard Alfonsín highlighted the Alfonsín highlighted the Kristaps sales late now the in Guayas to list that this one in Guayas to list that this one in the 'pheasán' bar click | 2024-03-22 16:29:30 | 863 | All Nodes Distance K in Binary Tree -- Leetcode #863 |
|
skMofPdLHjY | hello everyone welcome to learn overflow in this video we will look into today's in this video we will look into today's lecture problem that is the convert lecture problem that is the convert sorted array to binary search tree sorted array to binary search tree so this is an easy level problem and we so this is an easy level problem and we will understand how we can uh solve this will understand how we can uh solve this problem or how can think of solving this problem or how can think of solving this problem so before starting this video problem so before starting this video make sure to subscribe to this channel make sure to subscribe to this channel for regular record videos like this also for regular record videos like this also every details about this question will every details about this question will be there in the description make sure to be there in the description make sure to check that out as well check that out as well [Music] [Music] so let's start this uh the question says so let's start this uh the question says that we are given an integer arrayed that we are given an integer arrayed nums and the nums is the array that we nums and the nums is the array that we are given over here five and it says are given over here five and it says that while the elements are sorted in that while the elements are sorted in ascending order so the elements are ascending order so the elements are already sorted that we need to remember already sorted that we need to remember the elements are already sorted so the the elements are already sorted so the array numbers given to us is a sorted array numbers given to us is a sorted array file uh in ascending order and we array file uh in ascending order and we need to convert it to a height balanced need to convert it to a height balanced binary search tree so it should be a binary search tree so it should be a height balanced binary substitute and height balanced binary substitute and what does the height balance ionic what does the height balance ionic surgery means surgery means uh that it explains over here that the uh that it explains over here that the highest balance binary tree is a binary highest balance binary tree is a binary tree which uh tree which uh in which the depth of the two sub trees in which the depth of the two sub trees of every node never differs more than of every node never differs more than one okay so it basically means like one okay so it basically means like there's a tree say there are two sides there's a tree say there are two sides of a tree the depth that is the height of a tree the depth that is the height of each of the subtree never defers more of each of the subtree never defers more than one like uh than one like uh that never was the first one so uh that never was the first one so uh that's the whole thing okay so once we that's the whole thing okay so once we so the best thing is like how many like so the best thing is like how many like the number of elements or uh the total the number of elements or uh the total height in this height in this length is more or less equal to the length is more or less equal to the height on this uh the other side so for height on this uh the other side so for each of the loops like each of the loops like it may not be equal as well like it can it may not be equal as well like it can have a difference of one but it have a difference of one but it shouldn't be more than one like it shouldn't be more than one like it should be like a huge difference in should be like a huge difference in height as well so it it cannot be like height as well so it it cannot be like uh it's only going on the right it's uh it's only going on the right it's currently going on the right so this currently going on the right so this cannot be a possible height balance the cannot be a possible height balance the binary search okay so binary search okay so once we are trying to find a solution once we are trying to find a solution like like this like where the spinach has to is in this like where the spinach has to is in height balance then height balance then how we can actually uh go ahead finding how we can actually uh go ahead finding a solution in this case okay we need to a solution in this case okay we need to see we need to see and i'm going to see see we need to see and i'm going to see what the question gives us and we need what the question gives us and we need to see how we can actually think uh to see how we can actually think uh all the stuff given to us in the all the stuff given to us in the question the first thing given to us in question the first thing given to us in the question is the elements are the question is the elements are inserted so once the elements are inserted so once the elements are already inserted then already inserted then can you think that if you have can you think that if you have say you have a say you have a scale or a ruler in your hand fine so if scale or a ruler in your hand fine so if you need to balance the ruler you need you need to balance the ruler you need to uh like you need to say need to to uh like you need to say need to balance a ruler that so that on your balance a ruler that so that on your finger or on any object okay so how finger or on any object okay so how would you do you start with middle would you do you start with middle element isn't it like what do you element isn't it like what do you whatever reach center of mass if the whatever reach center of mass if the ruler will balance from that position ruler will balance from that position fine fine so so if that is the concept we use in physics if that is the concept we use in physics now the similar kind of concept we can now the similar kind of concept we can use uh in uh constructing the binary use uh in uh constructing the binary search tree because we need to do that search tree because we need to do that it's a balance this should be height it's a balance this should be height balanced okay so the first thing you balanced okay so the first thing you need to do in height balance is you need to do in height balance is you should the what whatever be the middle should the what whatever be the middle element that should be element that should be the uh root okay so the uh root okay so like say say there are five errors given like say say there are five errors given to us in the to us in the nums array in that nums array in that the middle limit zero becomes the root the middle limit zero becomes the root in any of the cases fine so that's the in any of the cases fine so that's the idea in this now uh further you see if idea in this now uh further you see if faded element 0 becomes root then there faded element 0 becomes root then there are two elements on the right there are are two elements on the right there are two elements of the left so you can two elements of the left so you can start with the start with the thought in mind that it's going to be thought in mind that it's going to be balanced more or less okay you are balanced more or less okay you are balancing the tree because the number of balancing the tree because the number of elements elements at least are same in both the side for at least are same in both the side for the the first root okay the the first root okay next we need to go ahead and check for next we need to go ahead and check for the next next roots fine the next next roots fine further we find that there are five and further we find that there are five and nine so you can start by taking like the nine so you can start by taking like the five as the next root and five as the next root and then uh keep nine so that's more or less then uh keep nine so that's more or less like the like the other solution uh given to us fine uh other solution uh given to us fine uh what i mean is like after taking 0 it's what i mean is like after taking 0 it's like the 5 you can take the 5 as the like the 5 you can take the 5 as the root and then try to balance the 9 or root and then try to balance the 9 or you can take 9 as the next root or and you can take 9 as the next root or and you can try to balance the 5 when it's you can try to balance the 5 when it's left ok left ok so that's the idea now uh you may say so that's the idea now uh you may say like what happened uh like it's uh how like what happened uh like it's uh how is it balanced look uh form nine the is it balanced look uh form nine the other side is none fine uh that's the other side is none fine uh that's the that's what we know so we say it's like that's what we know so we say it's like it should be the difference should not it should be the difference should not be more than one but the difference is be more than one but the difference is what the other side is zero there here what the other side is zero there here is one element so the difference is in is one element so the difference is in this one so this one so we know that this is we know that this is like height balance because the like height balance because the difference is one it shouldn't be more difference is one it shouldn't be more than one okay the next case is on the than one okay the next case is on the left hand side that is minus three and left hand side that is minus three and two minus two so you can go ahead with two minus two so you can go ahead with something like something like simply taking minus three as uh simply taking minus three as uh uh your root over here or you can so uh your root over here or you can so mine you can take minus just root and mine you can take minus just root and then then take 10 on its left and like minus 10 is take 10 on its left and like minus 10 is left on the right it should be it's not left on the right it should be it's not fine so you can take like that or on the fine so you can take like that or on the reverse case what you can take you can reverse case what you can take you can go ahead with go ahead with taking minus 10 as the root or taking minus 10 as the root or and minus you on its right so this may and minus you on its right so this may happen okay so happen okay so so so the question is like an explanation the question is like an explanation tells us like the both the solution can tells us like the both the solution can be an accepted solution so that they be an accepted solution so that they will accept both the solutions fine so will accept both the solutions fine so there won't be any problem uh related to there won't be any problem uh related to that how can you think of uh finding a that how can you think of uh finding a solution like this okay the thought solution like this okay the thought is pretty simple considering the uh what is pretty simple considering the uh what i initially gave examples at the uh i initially gave examples at the uh center of mass of an center of mass of an of our object okay the center of gravity of our object okay the center of gravity what do we say uh how we go ahead with what do we say uh how we go ahead with that the idea was uh just find the total that the idea was uh just find the total number of elements okay and find the number of elements okay and find the middle element at each position so if i middle element at each position so if i even find the middle element make this even find the middle element make this your root and then your root and then go ahead with uh the all the elements on go ahead with uh the all the elements on this left are these lip subtree all the this left are these lip subtree all the elements on his right are his right sub elements on his right are his right sub tree so that's the idea okay and the tree so that's the idea okay and the next case uh next case uh when you are in the left subtree so what when you are in the left subtree so what is the middle element middle element is the middle element middle element will be 0 plus 1 will be 0 plus 1 that's 1 by 2 is like once the middle that's 1 by 2 is like once the middle element comes out big three okay so so element comes out big three okay so so minus three it doesn't matter it because minus three it doesn't matter it because you did minus three or the minus two you did minus three or the minus two because both the because both the weights are accepted solution fine so weights are accepted solution fine so now we find that it's minus three ah if now we find that it's minus three ah if you take the middle element this comes you take the middle element this comes out to be minus 3 fine out to be minus 3 fine now take the minus 3 and take minus 10 now take the minus 3 and take minus 10 and this leftward element and another is and this leftward element and another is right towards the element so that's the right towards the element so that's the whole idea okay that's the idea just on whole idea okay that's the idea just on each of the pieces on or each of the each of the pieces on or each of the subtree just take the middle element uh subtree just take the middle element uh who is your whatever element on its left who is your whatever element on its left eyes left subject whatever this right is eyes left subject whatever this right is slight subtree so that's the whole idea slight subtree so that's the whole idea you need to follow to you need to follow to come a solution to this so we'll follow come a solution to this so we'll follow the same thing and write a code uh or the same thing and write a code uh or based on that okay based on that okay we'll exactly do the same thing and we'll exactly do the same thing and write a code so that would be our idea write a code so that would be our idea so let's go ahead and write our code and so let's go ahead and write our code and then understand how we exactly try to then understand how we exactly try to follow what we uh wanted to do in this follow what we uh wanted to do in this question okay let's go ahead with that see here the particular solution we came across is actually is again a zero millisecond solution is faster than 100 percent java solutions okay let's understand what a solution you came across over here the solution is uh exactly the tribe we were discussing till now the idea was um we took another like helper function within the same name but the different parameters so it's like a function overloading is going on so what it took we took the nums at it we took a start and the end it was just the uh index uh to point what's the current starter what's the current okay so if the start is greater than n written null so what this condition is whenever we need to add a null uh value to any of the roots okay any other subtree so that's the uh this will help us in that fine now further what we did we took up meat i said we will take a mate and meat is basically uh finding the middle uh like the middle element from the starting okay so that's the how we are calculating the meat and then for what you are doing we are just doing like we are creating a new tree node like a current node and that node is basically uh tree node uh is visible we are creating a new tree node and that's the value we are giving it as uh tree nums dot nums meat the mid value whatever the meat uh pointing and so we just gave it a numspeed so which uh construction we are using uh is in the like commenter section you can see the constructors are given so ah there there is a construction like this uh this one so like tree node in val if we just send a val so this will initialize uh the current value value of the tree node as like the file or whatever valve we are passing it through next we just went ahead with that root left that's the root we created and the root equator so we just went ahead with the root letter and root right so root left is again calling the same uh like the same function with uh with a different parameter parameter like the nums uh array being sent as it is and the start being the starting till uh the we're on the left side so it will be like starting uh till mid mid was initially zero uh like this uh this element was initially made so what we did on the left we said start till uh mid minus one because mean is that just the pointer we had so we start to meet minus one and on the right what we are going with uh mid plus one till end okay so that's the whole idea that's the whole idea we just break break it in that format and we found that this is the ultimate return uh we're determining this rule so once in any case say on the left or on the right we don't uh find a expected solution or we don't find any particular value that's uh lies this so we end up with that as a null path okay so that's the whole idea that's how the question like we are trying to solve this question and you folks already saw that the question works pretty well as a zero millisecond solution right so that's the more or less the idea behind this question i hope i can make you understand how you can go ahead and solve a question like this fine and you should try this question and definitely if you face any problem understanding this question make sure to comment it down i'll be more than happy to help you out in the comments as well fine so uh i like this video for making me understand that you actually uh you find this video helpful for you as well uh commented uh you know if you face any uh doubts or if you just want to uh convey any other approach that you have in mind i'll i'll be happy to read that and ex like communicate with you as well in the comments so that's more or less about this video guys thank you all for watching this video make sure to subscribe to this channel for regular echo videos like this i hope to see you soon in my next video as well thank you | 2024-03-21 10:30:41 | 108 | Convert Sorted Array to Binary Search Tree | Algorithm Explained | LeetCode 108 | Learn Overflow |
|
zM9N_x_v_24 | hello guys welcome to study algorithms and today we would be looking at finding and today we would be looking at finding the diameter of a binary tree first we the diameter of a binary tree first we would be understanding what is the would be understanding what is the diameter of a binary tree and look at diameter of a binary tree and look at some sample test cases next we would some sample test cases next we would discussed a brute force solution and the discussed a brute force solution and the problems you may face next we will try problems you may face next we will try to intuitively think of the problem and to intuitively think of the problem and come up with an efficient solution come up with an efficient solution followed by a dry run of the code so let followed by a dry run of the code so let us dive into the problem to understand us dive into the problem to understand this problem first you need to this problem first you need to understand what do you mean by the understand what do you mean by the diameter of a binary tree the diameter diameter of a binary tree the diameter of a binary tree is simply stated as the of a binary tree is simply stated as the longest possible path that you can find longest possible path that you can find between any two nodes in a binary tree between any two nodes in a binary tree so to demonstrate it let me just take up so to demonstrate it let me just take up three examples you have tree number one three examples you have tree number one tree number two and three number three tree number two and three number three entry number one the longest possible entry number one the longest possible path between two nodes that you can find path between two nodes that you can find would be this entry number two the would be this entry number two the longest possible paths that you can find longest possible paths that you can find would look something like this would look something like this so for tree number one our distance is 2 so for tree number one our distance is 2 and tree number 2 our distance is 7 and tree number 2 our distance is 7 but please note that it is not necessary but please note that it is not necessary that the longest path would include the that the longest path would include the root nodes a good example of this can be root nodes a good example of this can be seen entry number 3 entry number 3 the seen entry number 3 entry number 3 the longest path would be something like and longest path would be something like and this has a length of 5 so this is how this has a length of 5 so this is how you define the diameter of a binary tree you define the diameter of a binary tree so as for the problem statement you are so as for the problem statement you are given a binary tree and you are required given a binary tree and you are required to tell me the length of the diameter to tell me the length of the diameter let us see how we can go about solving let us see how we can go about solving this to get started let's just try to this to get started let's just try to have a small tree as an example a good have a small tree as an example a good way to solve any problem is to come up way to solve any problem is to come up with a solution first and then try to with a solution first and then try to optimize it so given this problem what optimize it so given this problem what solution can you think of the first solution can you think of the first solution that comes to my mind is what solution that comes to my mind is what if I just find the distance between each if I just find the distance between each of the node of the binary tree let's say of the node of the binary tree let's say 1 2 1 3 1 4 and 1 5 now 1 2 1 3 1 4 and 1 5 now each of these notes would have some each of these notes would have some distance for node one to have a distance distance for node one to have a distance of one one three have a difference of of one one three have a difference of two one four have a difference of two two one four have a difference of two and one five have a difference of one and one five have a difference of one similarly if I go ahead and compute the similarly if I go ahead and compute the distance of each of the nodes with distance of each of the nodes with respect to every other node how would it respect to every other node how would it look like now these are all the possible look like now these are all the possible distances between each of the two nodes distances between each of the two nodes in that minor tree and if you look at it in that minor tree and if you look at it the maximum possible distance that we the maximum possible distance that we found is three and hence this would be found is three and hence this would be the diameter of the binary tree the the diameter of the binary tree the problem with this solution is very problem with this solution is very obvious we only have five nodes in the obvious we only have five nodes in the tree and we have ten different distances tree and we have ten different distances to calculate what would happen if the to calculate what would happen if the tree size is let's say a thousand nodes tree size is let's say a thousand nodes or if a tree sizes a tenth of the nodes or if a tree sizes a tenth of the nodes the number of these distances would just the number of these distances would just explode and calculating all of them explode and calculating all of them would result into unnecessary would result into unnecessary calculations and a lot of time wastage calculations and a lot of time wastage so definitely there should be some so definitely there should be some better way to solve this problem let us better way to solve this problem let us try to have a look at it let us try to try to have a look at it let us try to look at the original examples that we look at the original examples that we had in the problem if you think about had in the problem if you think about this problem intuitively how long or how this problem intuitively how long or how deep a tree is it can be determined if deep a tree is it can be determined if you know how deep its left subtree and you know how deep its left subtree and how deep its right subtree are going so how deep its right subtree are going so if we can calculate the depth at each if we can calculate the depth at each node in the tree then maybe we can come node in the tree then maybe we can come up with some kind of a solution so let up with some kind of a solution so let me just try to calculate the depth at me just try to calculate the depth at each level of each node in the binary each level of each node in the binary tree I would start off with all of the tree I would start off with all of the leaf nodes so no - we have the depth of leaf nodes so no - we have the depth of one node fix has a depth of one node one node fix has a depth of one node zero has a depth of one and no nine have zero has a depth of one and no nine have a depth of one now moving on to the a depth of one now moving on to the parent nodes node seven has a depth of parent nodes node seven has a depth of two nodes five have a depth of two and two nodes five have a depth of two and here's the tricky part when you come to here's the tricky part when you come to node 4 you need to just know the maximum node 4 you need to just know the maximum depth so the left subtree has a depth of depth so the left subtree has a depth of 1 and the right 1 and the right three has a depth of two since we are three has a depth of two since we are interested in calculating the longest interested in calculating the longest path we would be looking at the maximum path we would be looking at the maximum depth so in this case the maximum depth depth so in this case the maximum depth at number four is three going over to at number four is three going over to the right the maximum depth at node the right the maximum depth at node number eight is again three because it number eight is again three because it has no right subtree going up to node has no right subtree going up to node number three it has no left subtree so number three it has no left subtree so it's maximum depth is four and going to it's maximum depth is four and going to the root the maximum depth is five to the root the maximum depth is five to verify our result we can easily see that verify our result we can easily see that for node number one this is our maximum for node number one this is our maximum depth for node number four this is our depth for node number four this is our maximum depth and hence we can easily maximum depth and hence we can easily conclude that these numbers are conclude that these numbers are representing the maximum depth at each representing the maximum depth at each of the levels of the binary tree now of the levels of the binary tree now given this scenario we can come up with given this scenario we can come up with the total depth for each of the nodes in the total depth for each of the nodes in the binary tree and this depth would be the binary tree and this depth would be given something like depth of left tree given something like depth of left tree plus right tree so if we are able to plus right tree so if we are able to calculate the total depth at each of the calculate the total depth at each of the nodes in the tree and we keep a track of nodes in the tree and we keep a track of what is the maximum depth that we could what is the maximum depth that we could found by combining the left subtree and found by combining the left subtree and the right subtree that should give you the right subtree that should give you the diameter theoretically so let us the diameter theoretically so let us just try to calculate it for each of the just try to calculate it for each of the node we are adding up the Left depth and node we are adding up the Left depth and the right depth in hence you see we got the right depth in hence you see we got the maximum depth at each of the node in the maximum depth at each of the node in the binary tree if you see the maximum the binary tree if you see the maximum depth that we found was at known number depth that we found was at known number one and its value was seven which comes one and its value was seven which comes out to be the diameter of your binary out to be the diameter of your binary tree and hence this is your answer let tree and hence this is your answer let us see how we can go about implementing us see how we can go about implementing this algorithm this problem also has a this algorithm this problem also has a recursive solution where we treat each recursive solution where we treat each of the left subtree and the right of the left subtree and the right subtree as a problem in itself and then subtree as a problem in itself and then recurse on the way up to the stack but recurse on the way up to the stack but recursion gives you a lot of problems recursion gives you a lot of problems while debugging and hence we would be while debugging and hence we would be looking at an iterative approach for the looking at an iterative approach for the iterative approach we initialize a stack iterative approach we initialize a stack and a node depth map this known depth and a node depth map this known depth map would be storing the known and the map would be storing the known and the maximum depth of each of those nodes we maximum depth of each of those nodes we start off start off with the root node and that if one to with the root node and that if one to perform a post order traversal we push perform a post order traversal we push elements into the stack until we reach a elements into the stack until we reach a leaf node because the root node needs to leaf node because the root node needs to be processed at the last so while be processed at the last so while hydrating through this code we would hydrating through this code we would wishing one into the stack then four and wishing one into the stack then four and then do now to does not have any child then do now to does not have any child nodes and hence we can process it for nodes and hence we can process it for processing what we do is we calculate processing what we do is we calculate the left depth and the right depth in the left depth and the right depth in this case both of them are zero and this case both of them are zero and hence the maximum depth available at hence the maximum depth available at node number 2 is just 1 and hence we node number 2 is just 1 and hence we update this value as 1 if you just try update this value as 1 if you just try to look back a couple of seconds ago we to look back a couple of seconds ago we had updated this value to 1 moving had updated this value to 1 moving forward forward we pop out two from the stack and hence we pop out two from the stack and hence we reach node number 4 but for still has we reach node number 4 but for still has some child nodes so we would be some child nodes so we would be processing 5 and then 6 6 would be processing 5 and then 6 6 would be treated in the same way as node number 2 treated in the same way as node number 2 and hence we are updating our map as 6 and hence we are updating our map as 6 and 1 while we are updating our map you and 1 while we are updating our map you see that we are also trying to update see that we are also trying to update the diameter of the tree that we find the diameter of the tree that we find now this is the maximum value we can now this is the maximum value we can find for the left nip and the right find for the left nip and the right depth so up till now our maximum value depth so up till now our maximum value is 1 and 0 and hence we update our is 1 and 0 and hence we update our diameter to be 1 going forward we pop diameter to be 1 going forward we pop out 6 and then will we are looking at out 6 and then will we are looking at node number 5 for node number 5 we see node number 5 for node number 5 we see that left depth is equal to 1 and hence that left depth is equal to 1 and hence while putting into the map we would be while putting into the map we would be updating its value so this would update updating its value so this would update something like this and if you remember something like this and if you remember we had put the value 2 in here going we had put the value 2 in here going forward we've opted for from the stack forward we've opted for from the stack now 4 has both left depth and the right now 4 has both left depth and the right depth the left half of 4 is 1 and the depth the left half of 4 is 1 and the right depth of 4 is 2 and hence when we right depth of 4 is 2 and hence when we updated into the map we would be putting updated into the map we would be putting like 4 and 3 now we are again updating like 4 and 3 now we are again updating the value of diameter and that would be the value of diameter and that would be the value that we have found so far and the value that we have found so far and the new value that you're finding at the new value that you're finding at node number 4 this would be 1 plus 2 and node number 4 this would be 1 plus 2 and hence our value updates to 3 hence our value updates to 3 moving on we go on to the right sub-tree moving on we go on to the right sub-tree so then we push three into the stack so then we push three into the stack since it has neighbors we push it it has since it has neighbors we push it it has neighbors we push seven and then again neighbors we push seven and then again we reach zero zero is again the same as we reach zero zero is again the same as number six and no number two so we would number six and no number two so we would just pop it from the stack and update just pop it from the stack and update our map same happens with number nine our map same happens with number nine now coming on to number seven we are now coming on to number seven we are looking at the left subtree and the looking at the left subtree and the right subtree so this valley would right subtree so this valley would update to two going over to number eight update to two going over to number eight this value updates us three and then this value updates us three and then going over to number three this value going over to number three this value updates us four and now we've reached updates us four and now we've reached the main node and that is number one so the main node and that is number one so when you reach at number one let us just when you reach at number one let us just try to look at the left depth so the try to look at the left depth so the left depth at node number one is three left depth at node number one is three the right depth at node number 1 is 4 as the right depth at node number 1 is 4 as you can see over here and here and we you can see over here and here and we need to update the diameter that will be need to update the diameter that will be the maximum value of the value that we the maximum value of the value that we have up till now that was 4 and the new have up till now that was 4 and the new value left and right so that would look value left and right so that would look something like max of 4 comma 3 plus 4 something like max of 4 comma 3 plus 4 which turns out to be 7 and hence this which turns out to be 7 and hence this is your answer the time complexity of is your answer the time complexity of this algorithm is order of n and we this algorithm is order of n and we occupy order of n extra space more occupy order of n extra space more details on the recursive solution can be details on the recursive solution can be found in the problem description found in the problem description mentioned in the link below both the mentioned in the link below both the solutions work in order of n time it's solutions work in order of n time it's just that the iterative approach it's just that the iterative approach it's easier to visualize please feel free to easier to visualize please feel free to reach out to me in case of any doubts reach out to me in case of any doubts and leave your feedback in the comments and leave your feedback in the comments below thank you | 2024-03-20 10:39:36 | 543 | Diameter of Binary Tree (LeetCode 543) | Full Solution with Examples | Study Algorithms |
|
vssbwPkarPQ | hey what's up guys it's Nick white here I do tack encoding stuff on twitch and I do tack encoding stuff on twitch and YouTube and check the description for YouTube and check the description for everything about me I do all the problem everything about me I do all the problem ly code problems and they're all on my ly code problems and they're all on my youtube channel so just check those out youtube channel so just check those out same intro as every other video this same intro as every other video this one's called flattened binary free to a one's called flattened binary free to a linked list and we don't really flatten linked list and we don't really flatten it to a linked list at all I don't even it to a linked list at all I don't even really know why it's called that it says really know why it's called that it says given a binary tree flatten it to a given a binary tree flatten it to a linked list in place so for example linked list in place so for example given the following tree so we have a given the following tree so we have a tree we would turn it into this so tree we would turn it into this so basically as we can see here we're basically as we can see here we're basically kind of just turning it into a basically kind of just turning it into a tree it is kind of a list type thing but tree it is kind of a list type thing but it's it's you know I could see how they it's it's you know I could see how they could say linked lists cuz none of these could say linked lists cuz none of these have a left child so basically now it's have a left child so basically now it's just only nodes with a bright child and just only nodes with a bright child and if you wanted to think about it it would if you wanted to think about it it would be like a node just dot next in the be like a node just dot next in the right dot right would now be dot next or right dot right would now be dot next or whatever if you wanted to think about it whatever if you wanted to think about it like that but yeah we're basically like that but yeah we're basically taking these and turning it into taking these and turning it into position wise kind of an in we're taking position wise kind of an in we're taking the position of the nodes and turning it the position of the nodes and turning it into a position wise ordered kind of into a position wise ordered kind of path here of all right children right so path here of all right children right so basically the right children will be in basically the right children will be in all the right children of the nodes will all the right children of the nodes will be kind of an order of the previous tree be kind of an order of the previous tree position wise right so as you'll notice position wise right so as you'll notice all of the you'll basically be taking all of the you'll basically be taking the left children and be setting them to the left children and be setting them to the right children of from root down so the right children of from root down so yeah you can see just position wise like yeah you can see just position wise like 1 2 3 4 so it's kind of leftmost to 1 2 3 4 so it's kind of leftmost to rightmost is how we're kind of gonna be rightmost is how we're kind of gonna be traversing this tree and setting the traversing this tree and setting the right notes right so to do this all we right notes right so to do this all we have to do is if root equals no it's have to do is if root equals no it's pretty easy honestly so return a lot pretty easy honestly so return a lot easier I've seen harder easier problems easier I've seen harder easier problems and trees than this so then we'll have and trees than this so then we'll have our stack like all the other problems so our stack like all the other problems so we have a stack of tree nodes we'll call we have a stack of tree nodes we'll call it stack stack add the root to it just it stack stack add the root to it just like the other ones while the stacks not like the other ones while the stacks not empty so while the stack is an empty pop the current node tree node current stack pop and then what we do is since it's a stack we're going to traverse we're gonna add the right node to the stack first because we actually want the left node first so we're gonna add the right node to the stack first so what we do is if current node right this will make sense in a second right it's not equal to null stack top push current node dot right and then same thing for the left now left is afterwards dot left is not equal to null stack push current node dot left right so you push the right then you push flush and then all you have to do down here is if you do the because I'll explain that in a second - because I'll explain that in a second - then you do current node dot right is then you do current node dot right is equal to stack top peek and you're gonna equal to stack top peek and you're gonna set yeah we'll go through an example set yeah we'll go through an example here and then you set every node no here and then you set every node no matter what they're left to null because matter what they're left to null because you can see every now it's left is no so you can see every now it's left is no so let's go over an example here so the let's go over an example here so the first node we're gonna put on is one first node we're gonna put on is one right for the root you would check you'd right for the root you would check you'd see the left node is 2 and the right see the left node is 2 and the right node is 5 so you push the right node node is 5 so you push the right node onto the stack which is 5 and then you onto the stack which is 5 and then you push 2 onto the stack for the left node push 2 onto the stack for the left node then you just do this check down here if then you just do this check down here if the stack is not empty which it's not it the stack is not empty which it's not it has five and then it has two we pull two has five and then it has two we pull two off because that's the peak and we said off because that's the peak and we said well we don't pull two off we just get well we don't pull two off we just get it we get two because that's the peak so it we get two because that's the peak so the stack peak is two and we set one dot the stack peak is two and we set one dot right to two and you can see one dot right to two and you can see one dot right is to here and you do that over right is to here and you do that over and over again and eventually it sets and over again and eventually it sets all the proper right notes and it sets all the proper right notes and it sets every left node to null and it does that every left node to null and it does that because and you have to do this check because and you have to do this check down here this the second is stack is down here this the second is stack is not empty check down here because let's not empty check down here because let's say it was just a room note so all we say it was just a room note so all we have is room have is room we popped the root note off the stack so we popped the root note off the stack so it's just one you add nothing because it's just one you add nothing because the left and right are null so these the left and right are null so these never get executed and then you would never get executed and then you would have to do this check because you don't have to do this check because you don't want to set right there's nothing in the want to set right there's nothing in the stack to set the right to so that's why stack to set the right to so that's why we just do the second stack we just do we just do the second stack we just do the second check here because we are the second check here because we are popping off the stack so we we're popping off the stack so we we're technically decreasing the size of the technically decreasing the size of the stack so we do have to make sure that stack so we do have to make sure that the stack has something in it it's the stack has something in it it's pretty self-explanatory it would set pretty self-explanatory it would set although it takes all the left notes although it takes all the left notes kind of puts them in the stack and sets kind of puts them in the stack and sets all the right nodes to the first left all the right nodes to the first left the leftmost nodes and then as we go the the leftmost nodes and then as we go the right notes get set to other right notes right notes get set to other right notes so it's kind of a left-to-right type of so it's kind of a left-to-right type of deal here and hopefully I explained that deal here and hopefully I explained that pretty well let me know in the comments pretty well let me know in the comments if I need to do better it's pretty kind if I need to do better it's pretty kind of self-explanatory I don't think it's of self-explanatory I don't think it's that hard of one if you really just that hard of one if you really just think about it and go through a couple think about it and go through a couple solutions in your head that's pretty solutions in your head that's pretty much it so thank you guys for watching much it so thank you guys for watching check out some other solutions and I'll check out some other solutions and I'll see you guys later | 2024-03-21 10:49:07 | 114 | LeetCode Flatten Binary Tree to Linked List Explained - Java |
|
RQmjgvWbMd8 | hello and welcome to python programming practice in this python programming practice in this episode episode we are going to be covering lead code we are going to be covering lead code number 69 number 69 called square root x called square root x given a non-negative integer x given a non-negative integer x compute and return the square root of x compute and return the square root of x since the return type is an integer the since the return type is an integer the decimal digits are truncated decimal digits are truncated and only the integer parts are returned and only the integer parts are returned so so basically i guess that means we find the basically i guess that means we find the square root but square root but we want to return like rounded down to we want to return like rounded down to the nearest integer like the floor the nearest integer like the floor function function of the square root of the square root example i don't know that we even need example i don't know that we even need examples we kind of know what the square examples we kind of know what the square root is root is if x is 4 the square root is 2. if x is if x is 4 the square root is 2. if x is 8 8 the output is actually 2 as well because the output is actually 2 as well because the square root of 8 is somewhere the square root of 8 is somewhere between two and three and if we round between two and three and if we round that down that down to uh the nearest integer well it's to uh the nearest integer well it's showing us here the square root of eight showing us here the square root of eight is two point eight is two point eight whatever but if we round that down then whatever but if we round that down then it's going to be two as well it's going to be two as well our constraints are the numbers going to our constraints are the numbers going to be between 0 be between 0 and 2 to the 31 minus 1 so we are going and 2 to the 31 minus 1 so we are going to have to be able to handle fairly to have to be able to handle fairly large numbers here large numbers here now this is seems like a now this is seems like a very simple problem because it's just very simple problem because it's just asking us to do an asking us to do an operation that is just math that python operation that is just math that python can just naturally do with either can just naturally do with either basic imports or just exponentiations so basic imports or just exponentiations so it seems like they should have really it seems like they should have really maybe put more instructions as to kind maybe put more instructions as to kind of how you're supposed to approach this of how you're supposed to approach this problem because problem because there's a few easy ways we could do this there's a few easy ways we could do this without really doing anything without really doing anything interesting like for one we could say interesting like for one we could say an import solution all you'd have to do an import solution all you'd have to do is import math to gain access to the is import math to gain access to the square root function square root function then return math dot square root then return math dot square root of x that should be a easy working of x that should be a easy working solution solution but of course we need to also do int of but of course we need to also do int of that that since the problem called for rounding to since the problem called for rounding to the nearest integer that should the nearest integer that should strip off the decimals and just return strip off the decimals and just return the int portion of it the int portion of it so that should be a working solution so so that should be a working solution so let's go ahead and submit that one just let's go ahead and submit that one just to to get a start on this problem so let's get a start on this problem so let's just pull over and see the result of just pull over and see the result of what that is what that is we can see just even with that basic we can see just even with that basic submission i'm assuming lots of other submission i'm assuming lots of other people did that people did that the run time was 32 milliseconds faster the run time was 32 milliseconds faster than than 81 of other python 3 submissions now 81 of other python 3 submissions now in reality i don't see why you would in reality i don't see why you would ever ever do anything more than this if you want do anything more than this if you want to do square root in python you should to do square root in python you should just just use the square root function but i guess use the square root function but i guess there is probably other ways to solve there is probably other ways to solve this this now one other very simple way to do this now one other very simple way to do this without even importing math without even importing math is use exponentiation so we could is use exponentiation so we could say exponent say exponent solution so the square root of a number solution so the square root of a number is the same as that number raised to the is the same as that number raised to the one-half power one-half power so all we'd have to do is return int of x to the one-half and this should also get us the same answer as what we just did so let's submit that and it's probably going to result in the exact same everything but who knows so for some reason that run was a little bit quicker than the math one i guess because we didn't have to import the math module first or something but so 28 millisecond runtime faster than 92 percent of other python 3 submissions now again these two solutions are probably the easiest and best way to do this but clearly if you want to make this problem more interesting than just importing something or doing basic exponentiation you'd actually have to go out and figure out how to find square roots mathematically and that's something that most people probably have no idea how to do so i didn't know how to go about manually calculating square roots because i'm not sure that's something i ever learned i went to wikipedia and looked up some different ways so we can look at wikipedia here and there's a whole bunch of different methods for finding square roots i found this thing called the babylonian method which is supposed to be one of the first algorithms used for doing this which is basically an iterative approximation of a square root basically what it does is starts with some estimate of what the square root is and then iteratively gets closer and closer to the right answer we don't need to go too big into the details the most important part of it is this here it basically says that the method can be represented by this algorithm so we start with some estimate x0 that's supposed to be somewhat close to the square root of s or whatever number you're working with it actually doesn't have to be close to it it just means that if it the closer your initial estimate is to the square root the faster it will converge but it doesn't actually have to be that close we can just use whatever initial estimate we want to and then we just keep updating this estimate based on this formula so the next estimate which is x n plus one we start with x of zero n plus one of zero would be one but then we go to the second estimate third estimate and so on so the next estimate after whatever initial one we have is equal to one half times that current estimate plus s divided by the current estimate where this value s is the number that we're finding the square root of and then mathematically this method will converge on the square root as you go through more and more iterations that's what this is saying here it's saying the square root of our number is actually equal to this value xn in the limit as n goes to infinity so basically as we're doing more iterations and we keep doing this update this number will get closer and closer to the square root of our target until enough iterations and it'll basically be effectively the same thing so i thought for an exercise it could be interesting to try to code up this algorithm as a solution to the square root problem even though you would never actually want to do this if you're having to calculate square roots in python so let's go ahead and try this so it's going to be called the and we don't want to have to deal with and we don't want to have to deal with cases cases where the target is too small because where the target is too small because when x is one and x is zero things get when x is one and x is zero things get a little weird so if x is a little weird so if x is less than or equal to one let's just less than or equal to one let's just return x return x because that deals with those corner because that deals with those corner cases where cases where the square root of 1 is 1 and the square the square root of 1 is 1 and the square root of 0 is 0. root of 0 is 0. so let's get rid of that and then so let's get rid of that and then [Music] [Music] else we just want to implement else we just want to implement that function that we just looked at so that function that we just looked at so let's come up with some initial let's come up with some initial estimate x n estimate x n um it could really be anything let's um it could really be anything let's just set it to just set it to say half of the target that we're given say half of the target that we're given so so the integer target we're given is called the integer target we're given is called x in the x in the little algorithm we looked at was called little algorithm we looked at was called s but it could be whatever we want s but it could be whatever we want and we now also want to keep track of and we now also want to keep track of how big the number is changing how big the number is changing so basically we want to keep running the so basically we want to keep running the update update until the change that we're seeing from until the change that we're seeing from one iteration to the next is small one iteration to the next is small enough that we want to enough that we want to exit we don't know exactly what small exit we don't know exactly what small enough should be enough should be in this case but anything that's quite a in this case but anything that's quite a bit smaller than one we're probably bit smaller than one we're probably then in the range where we're going to then in the range where we're going to be close enough to an answer be close enough to an answer to round it to the nearest integer and to round it to the nearest integer and get the right thing get the right thing so let's set the change so let's set the change equal to just one initially and but equal to just one initially and but we're going to keep iterating until the we're going to keep iterating until the change is change is smaller than that so while the change smaller than that so while the change we're seeing we're seeing is say greater than some value that's is say greater than some value that's kind of small kind of small maybe 0.01 or something like that that maybe 0.01 or something like that that should put us pretty close to what the should put us pretty close to what the real square root is then we will do real square root is then we will do the algorithm updates that we saw so we the algorithm updates that we saw so we need to calculate what the next need to calculate what the next the next n is going to be and that was the next n is going to be and that was equal to equal to one-half so 0.5 one-half so 0.5 times times times times what the current value was what the current value was so x n plus so x n plus the actual number we're looking for the actual number we're looking for x and the algorithm we looked at was x and the algorithm we looked at was called s but it's called x for us called s but it's called x for us divided by the current number so this is divided by the current number so this is what the next estimate is going to be what the next estimate is going to be the change is now going to be equal to the change is now going to be equal to the old estimate the old estimate minus the new one so minus the minus the new one so minus the next one that's the change and next one that's the change and in theory the change here could actually in theory the change here could actually end up being negative it's end up being negative it's if it's being adjusted the right way for if it's being adjusted the right way for that to happen that to happen so we actually want to take the absolute so we actually want to take the absolute value of this value of this to make sure that it's just the to make sure that it's just the magnitude of the change and we don't get magnitude of the change and we don't get a negative a negative value here and then value here and then we just need to do the update so after we just need to do the update so after that we'll update that we'll update our x n to equal the next n our x n to equal the next n and this while loop now will just keep and this while loop now will just keep running and running and running running and running and running and finding a better approximation of and finding a better approximation of the square root the square root until the change scene from one until the change scene from one iteration to the next is iteration to the next is less than 0.01 that should end up being less than 0.01 that should end up being a pretty close approximation to the a pretty close approximation to the square root square root so at that point we can just return so so at that point we can just return so we will return we will return we need the integer again so we'll we need the integer again so we'll return the int return the int of our xn that we are of our xn that we are finding the approximation for so this finding the approximation for so this should should essentially be a working implementation essentially be a working implementation of that of that of this function here that was shown in of this function here that was shown in wikipedia wikipedia so that should also get us the square so that should also get us the square root we'll root we'll we'll see how good these babylonians we'll see how good these babylonians were with their were with their algorithm efficiency i guess so let's uh algorithm efficiency i guess so let's uh hit submit on that one hit submit on that one as long as we didn't make any errors in as long as we didn't make any errors in the code the code now again we didn't come up with a very now again we didn't come up with a very smart kind of smart kind of initial seed for our estimate of the initial seed for our estimate of the square root square root if we could come up with maybe a smarter if we could come up with maybe a smarter way of doing that this might be a little way of doing that this might be a little more efficient but more efficient but regardless it should eventually find regardless it should eventually find something that works let's pull over and something that works let's pull over and we got we got a working result it was 36 milliseconds a working result it was 36 milliseconds so so the runtime was maybe a little bit the runtime was maybe a little bit slower than some of the slower than some of the python built-in ones we used but it's python built-in ones we used but it's still relatively fast giving that it was still relatively fast giving that it was faster than 60 faster than 60 of submissions and i'm guessing most of submissions and i'm guessing most people that submitted this one probably people that submitted this one probably just did one of these just did one of these more simple ones and if we didn't want more simple ones and if we didn't want to be to be so exact in our approximation we could so exact in our approximation we could probably get something faster like probably get something faster like here we're trying to find where the here we're trying to find where the change is less than a very small amount change is less than a very small amount well well if we maybe made this little bigger if we maybe made this little bigger maybe the approximation wouldn't be maybe the approximation wouldn't be quite so good and it quite so good and it it might actually fail the greater but it might actually fail the greater but if we make that 0.1 if we make that 0.1 we won't have to run as many iterations we won't have to run as many iterations let's let's submit that and see let's let's submit that and see how fast it is so how fast it is so i guess that didn't make too big of a i guess that didn't make too big of a change but it was slightly faster change but it was slightly faster than the one where we had a few more than the one where we had a few more iterations so iterations so you could probably play around with this you could probably play around with this with the seed value and how many with the seed value and how many iterations and iterations and maybe get something that's about as good maybe get something that's about as good as these built-ins as these built-ins so this is a case where the easiest so this is a case where the easiest solutions are probably solutions are probably what you should be using in practice what you should be using in practice there's no reason to there's no reason to reinvent the wheel and try to find a new reinvent the wheel and try to find a new way to implement square root when it can way to implement square root when it can be done so easily in the base language be done so easily in the base language but for the purposes of having a but for the purposes of having a somewhat more interesting coding problem somewhat more interesting coding problem i thought it'd be interesting to i thought it'd be interesting to actually try to implement actually try to implement an algorithm that finds a square root an algorithm that finds a square root mathematically instead of just mathematically instead of just using something baked into the language using something baked into the language so thanks for watching so thanks for watching and keep coding | 2024-03-20 11:17:37 | 69 | Python Programming Practice: LeetCode #69 Sqrt(x) |
|
SwGhraPO7-w | hello everyone so in this video let us talk about a easy problem from lead code talk about a easy problem from lead code the problem name is fair candy swaps the problem name is fair candy swaps okay so Alice and Bobs have different okay so Alice and Bobs have different total number of candies you are given to total number of candies you are given to integer array Alice size and Bob size integer array Alice size and Bob size where Alice size I is the number of where Alice size I is the number of candy of the ith box of candy of the ith box of the candidate Alice hold whereas Bob the candidate Alice hold whereas Bob size J is the number of candies of the J size J is the number of candies of the J box of the candidate Bob has okay so box of the candidate Bob has okay so I'll just take you the next input as I'll just take you the next input as well that Alice size as you can assume well that Alice size as you can assume that these are different candy boxes that these are different candy boxes okay one candy box is of size one okay one candy box is of size one another candy boxes of size one so Alice another candy boxes of size one so Alice has two candy boxes of size one has two candy boxes of size one similarly Bob has two candy boxes of similarly Bob has two candy boxes of size two got it so plus they have these size two got it so plus they have these type of candy boxes since they both are type of candy boxes since they both are friends they like to exchange one candy friends they like to exchange one candy box okay one candy box will transfer the box okay one candy box will transfer the box to Alice and Alice will translate to box to Alice and Alice will translate to Bob now they want to do that such that Bob now they want to do that such that they have the both has a total amount of they have the both has a total amount of same candy okay so the total sum of the same candy okay so the total sum of the candy boxes the value of these candy candy boxes the value of these candy boxes whatever you can say will become boxes whatever you can say will become equal after that one exchange okay now I equal after that one exchange okay now I just have to tell that what is the value just have to tell that what is the value that should be given by Alice and what that should be given by Alice and what is the value addition by given by Bob so is the value addition by given by Bob so that eventually they have the same that eventually they have the same number of candies and it is guaranteed number of candies and it is guaranteed at least one cycle the first thing which comes to my mind is okay uh they have different candidates but eventually they will reach two same candles same condition means a middle of whatever candidates they have so let's say one has more candies one will have less candy and they will come to the middle so what you can what is the middle value you can directly get out at what value they will eventually reach when they are equal candles so what you can actually do is just sum all the value of candies Alice says and Bob have divided by two you will get what is the amount of candy both should be having in the end of The Exchange so that they both have same number kind I hope you get the point so what we'll do is we first find out the sum of all the elements of Alice and Bob and divided by two so that we we got to know what is the final lead of Alice and Bob after doing this machine now they have to do an exchange now how they should be doing an exchange the first thing is what we can do is that let us there will be only one exchange that is given to you so let us try to iterate over Alice voxel of candies and one by one we'll check that whether if Alice give the first blocks if Alice give the first box what is the candy that Bob should give so that they both will become equal okay we have the final final point at which we should reach the final state that we should reach we have the current state if Alice gives the ith box we will iterate over every box of I because they will do bearing out only one box so what we'll do is we'll enter over every box of LSi and let's say that Alice give the ith box if Alice give the ith box Alice has a total sum it gives the ith boxer to subtract from this but eventually they want to reach a final state in which they have equal amount so this is the final needed so this total final needed State minus the amount of Andy as like candy Alice gives from the total sum will gives you what is the amount of candy it should receive to reach this final state hope you get the point so Alice has given something and it will also receive something so how much Alice should be receiving to reach the final state after giving the is capital now if Alice give this candy to Bob or Bob will also give you something now Bob should be giving that much of candy so that Alice should reach this final state so I I knew that this final state is other I have stored in this at this variable so I just checked that whether this other type of candy is present in Bob's candy collection or the different candy boxes we have so we what we can do is to make it more quicker we can just make a map out of all the candies present with Bob and we can just check in the map or you can also make a set not met like I said multi set because they can multiple same candies as well but if a candy is present with Bob that Alice wants then uh Bob can give that candy to Alice and Alice is giving one candy to Bob and eventually because we decided that this is the final State and this is the final State Alice will reach So eventually Bob will also reach the final State because uh the candies are same only like they are a fixed collection of category so what we'll want to is that if Alice is giving the is candy it should be receiving this other amount of candy from Bob so that Alice will reach the final needed State and for that can it be received by Bob you have to actually check that whether that can be that amount of candy pop should have so we will check then in the map that whether the amount of candy pop have if it has that particular candy then we got the answer that Alice will give this eye candy Bob will get to this or this other candy and both of them are fine so we just make and like because you have to return what amount of candy Alice and Alex should give and Bob should give so we just return an array of the candy that is Alice should be giving and the Box should be giving and that's it so it will always occur this state so this will be returned always and this is a zero comma zero I'm just in like just to make this function more clean that's why it is written but this condition will never hit because it's a uh the condition is like for every case it will always sit and then uh we have just make an unordered map we just checked it whether I put the candy special job for a particular candy given by Alice okay that's our logic so coming down Your Dragon City we have done an O of n to find out the sum this o of n make another another map then we have done the fall Loops of n so it is all together o of n only for doing this whole operation if you are using a map it will be o of n log n but that's not much of a deal because it would probably that time home safety as well so that's overall logic and the good part for this particular problem if you still have any doubts you can mention not in the comment box of this particular problem thank you for watching video till the end I will see you in the next Monday | 2024-03-22 17:40:01 | 888 | 888. Fair Candy Swap | LEETCODE EASY |
|
WH_FUQgMvuY | hey hey everybody this is larry this is day 28 of the january lego daily day 28 of the january lego daily challenge hit the like button hit the challenge hit the like button hit the subscribe button join me on discord let subscribe button join me on discord let me know what you think about this me know what you think about this problem which is design ad and search problem which is design ad and search word status structure word status structure restrained restrained design design hopefully i've been doing all right it's hopefully i've been doing all right it's still very cold here in new york and still very cold here in new york and i've been just feeling a little bit i've been just feeling a little bit unwell uh hopefully not of the you know unwell uh hopefully not of the you know thing that's going around i mean i've thing that's going around i mean i've just been having poor sleeping habits to just been having poor sleeping habits to be honest but uh okay let's see be honest but uh okay let's see uh okay matches if we did it uh okay matches if we did it i'd would add was it can be matched i'd would add was it can be matched later search okay oh it may contain dots later search okay oh it may contain dots okay length is 500 uh okay huh kind of these things are always a little bit tricky because hmm this i guess it's not clear hmm this i guess it's not clear um i'm trying to also see where how many words there are but i guess the implicit part is that there can be you know 50 000 words or whatever but of course this is also like one of those type of this is also like one of those type of problems that i feel like is problems that i feel like is um kind of guests to input a little bit um kind of guests to input a little bit what i mean by that is that what i mean by that is that you know it could be they could have you know it could be they could have really hard test cases and really hard test cases and and you know almost no solution would and you know almost no solution would pass or it could have you know silly um pass or it could have you know silly um silly cases but silly cases but yeah i don't know yeah i mean let's do it naively and then yeah i mean let's do it naively and then we'll see if that's fast enough because we'll see if that's fast enough because that's going to be that's going to be [Music] [Music] if they really want it to if they really want it to they can make it very sloppy but yeah i always do struggle a little bit because you can pre-process it but it's because you can pre-process it but it's always like always like like i said like that also depends on on like i said like that also depends on on a bunch of things a bunch of things um because like the word length being um because like the word length being 500 means that it prevents you from 500 means that it prevents you from doing a lot of the pre-calculation stuff doing a lot of the pre-calculation stuff with respect to like you know brute with respect to like you know brute forcing um wild card on order sub sub forcing um wild card on order sub sub uh subsequence is it yeah so it's a uh subsequence is it yeah so it's a little bit awkward but okay let's uh let's just do it naively and then we'll um um [Music] um if if uh someone like i mean you could write this in a for loop but yeah so if x is equal to y or x is equal to 2 for x y in sip of word talk uh the other way target word if all of this then we return true now this is basically as naive as it now this is basically as naive as it gets we might have to think about gets we might have to think about optimization i mean i didn't really you optimization i mean i didn't really you know know but i guess we'll see but i guess we'll see oh this actually may be wrong because oh this actually may be wrong because if target and word has different lengths if target and word has different lengths um then this may actually give you a um then this may actually give you a true even though it's worse true even though it's worse [Music] so so target length is equal to length of target length is equal to length of target target and then if and then if target let's target let's talk the length as you go to length of talk the length as you go to length of the word and all this stuff um and you can kind of actually test this i should have tested for demonstration um for for [Music] [Music] let's say let's say [Music] [Music] this should give you force but if we this should give you force but if we didn't have this then if i didn't have this then if i it might give you true for example if i it might give you true for example if i took this away i think this would maybe took this away i think this would maybe give me true give me true um um yeah so so i'm glad we fixed that but yeah so so i'm glad we fixed that but now we'll see if it's fast enough now we'll see if it's fast enough um we could also do something like do a um we could also do something like do a look up by the length so that we can look up by the length so that we can save this save this uh and maybe even the first character or uh and maybe even the first character or something like that but ah i did it okay something like that but ah i did it okay last time i wonder how i did it last last time i wonder how i did it last time time we'll see if this is fast enough also like i feel like they've been adding a lot of test cases for the last couple of years so given if i did the same code it might not be fastened up and this is too slow apparently um well well how many test cases are we uh well how many test cases are we uh well there's only 13 test cases and we've not there's only 13 test cases and we've not do do um uh but i also saw like a lot of two uh but i also saw like a lot of two characters in one character so i guess characters in one character so i guess what we can do is just have like a what we can do is just have like a lookup table right lookup table right so so yeah [Music] right and then we can let's copy and paste this i'm still a little bit tired to be honest uh ooh uh ooh whoops now my keyboard my keyboard is fine but i've been put i think i've moved my keyboard to a weird place and then my fingering's a little bit off uh two point okay that seems fast enough but we'll see if that's actually fast enough um yeah that's a little bit silly though it's like i said right everything depends on the exact input this is such a weird optimization uh or maybe not weird just i don't know what i did last well well i was actually thinking about doing with i was actually thinking about doing with a try but i didn't a try but i didn't i wasn't sure that it would be fast i wasn't sure that it would be fast enough enough um because um because the period can branch off multiple the period can branch off multiple places right so places right so i guess in the past i just yellowed a i guess in the past i just yellowed a little bit differently but little bit differently but because we have a word and then if it's because we have a word and then if it's equal to word then we look at every edge equal to word then we look at every edge right so i feel like in theory again right so i feel like in theory again like i guess that's why i didn't do it like i guess that's why i didn't do it this time uh even the last time i was this time uh even the last time i was happy with the yolo but the problem is happy with the yolo but the problem is that that [Music] yeah the problem is that technically i i want to say technically you can branch out like in many ways and it becomes almost looking at every word but that said looking everywhere was basically what i was doing before so because you can think about it as a tree where you know there are multiple branches and all the branches you go you know you're going to get um yeah this is brute force on like almost a deaf researcher like if you have a wild card then look at every leaf or not every leaf every children to see if one of them is good um i don't know i don't know how i feel about how to do it i think this one is one of those classic problems that is a little bit reading reading um reading the mind of the problem setter and those are always a little bit tricky because they just want you to implement in a specific way and the number of test cases and the not even just the number of test cases because that is something that i complain about as well but beyond that the um [Music] the the like the distribution of inputs or something like this right um like i i think the the uh this case like this case uh apparently filtering out by length saves a lot of time but even if they're all the same length let's say we we moved order one period to two periods then he is essentially we would check a lot more words right so then like maybe that's enough to make it time limited i don't know but that's kind of things that's like a little bit about or at least in lead code a lot about just guessing what the the writer is intending so those are always a little bit yucky um in terms of complexity this this is really like this is naive right to be honest it's naive with a very minor optimization so there really is um [Music] i mean i don't know it is not a very good optimization there's not really good complexity so i don't know all right um let me know what you think about this farm let me know what you think about my solutions either this one or the one that i did previously um that's all i really have i don't uh this is a very yucky problem i don't really i'm not a fan of it uh at least in terms of you know there's two there's two too many ways you could have done this and like i said it's just about guessing the input uh just like the texture of the input say so yeah anyway that's all i have stay good stay healthy to good mental health i'll see | 2024-03-22 10:29:31 | 211 | 211. Design Add and Search Words Data Structure - Day 28/31 Leetcode January Challenge |
|
Td7JK43D3ho | hello my friends this is Alexander barmin and this is my YouTube show lead barmin and this is my YouTube show lead code with me where we solve coding code with me where we solve coding challenges from lead code challenges from lead code recently I conducted my first live recently I conducted my first live stream and hope you enjoyed it and if stream and hope you enjoyed it and if you have topics for the next streams to you have topics for the next streams to for me to cover please don't forget to for me to cover please don't forget to write a comment for this video and write a comment for this video and they'll definitely arrange a next stream they'll definitely arrange a next stream and if you still want to play powerblade and if you still want to play powerblade game for NES also please write a comment game for NES also please write a comment they will have it so let's get started they will have it so let's get started and go ahead okay let's start the Korean and go ahead okay let's start the Korean challenge so we're given an integer challenge so we're given an integer and we need to return and not the and we need to return and not the integer with its digit reversed so for integer with its digit reversed so for example if you're given one two three we example if you're given one two three we should return two three one so there are multiple ways to solve and git and this most simplest option is to convert this integer to the string one two three and next read the string in a reverse order simple yep relatively simple but maybe not so efficient because we have number to string and next we need to convert our string three to one back to the number little one which is not really good let's try to because we we know it's a slit code we know it's lit court and Lead code ordinary asked to think about our challenges from the mouth point of view so let's think so we have number which is equal to one two three and what we need to do we need to take the last one number from it it's free in this scenario right right so what does it mean we need to divide our number by 10. and take a rest so roughly speaking well we need to divide and by 10 and take a rest so in this case the rest is free and what is left is 12. right again next step we have 12 we again divided by 10 we take two and one left again 1 divided by ten it is 1 and 0 left okay fine uh other than that we need to find a way of building numbers in a reversed order okay let's start thinking about it let's assume that by default we have zero and we will start adding these rests zero plus three is equal to three okay next time what we need to do we need to say three is not the first number and not the first number in our in is not the first digit in our number it should be moved one position to the left what does it mean we need to multiply it by 10 and plus the second rest so roughly speaking it means it's 30 plus 2 which is 32. next step okay I have 32 If I multiply it by 10 and add 1 because 1 is the rest here what I will have I will have 320 plus one which is three two one okay so I managed to reverse my number and I managed to do it by doing F2 operations first of all dividing by 10 and second multiplying by ten and the last one bit is in case if number was negative I need to persist the sign if it was negative it should be negative it's positive it should be positive okay that's it traffic speaking let's write it down long result is equal to zero I start with long because the conditions the task says that it's uh in case if it is outside the integer uh range I need to return zero so I need to know is it outside or not and um uh in order to do that I want to continue and write something like this integer max value if it's more than max value of result is less than integer mean value it is zero that's it just because I'm sad that I need to return zero because integer my might overflow and next I need to convert my result back to integers so this means that in case if number is more the is outside of the integer range which I should return zero and in case of my in my value is inside the integer range I need to return this integer so easy okay other than that I need to persist a sign so Boolean negative because positive it's fine uh this is the sign in case if number is negative this condition will be related to true in case if it's positive it will be evaluated through uh false and other than that I need to return my sign back if negative my result is Multiplied to minus one or it's better to write it like this results multiply to minus one because it's more readable and X is math ABS X so uh I take an absolute value just because it's easier so I edit all the conditions and right now I may start implementing the logic I just described first step is to divide by zero next step is multiply by zero and add a rest so while my number X is more than zero what I wanna do is I will take my result and multiply it by 10 as I said here I'm multiplying my result by 10 and other than that I need to add a rest after division by 10. so this is what I do and Next Step so because this is not an assignment it is just a computation what else I need to do I need to say okay X is everything which left on the left hand side after dividing by 10. so this first line says that I multiply what I had before roughly speaking 0 multiplied by 10 again it's a valid condition and plus a rest of the division it's free next time I take what I already have in my result multiply it by 10 and add a result of division by 10. okay and also I need to decrease value of the X of the X so just by dividing it by 10. okay I'll work okay I'll work and final submit while it beats 97 and 75 percent of all users who wrote it in Java I suppose this is exactly what they expected that's it for today hope you enjoyed the video and if so please don't forget to give me a like write a comment and subscribe to my channel [Music] | 2024-03-18 11:53:41 | 7 | [LEET] Code with me #7 (Reverse Integer) |
|
o8emK4ehhq0 | hey guys it's iran with another coding interview question and this one is interview question and this one is called called minimum cost to higher k workers this minimum cost to higher k workers this one is really popular with google one is really popular with google probably on account of it being really probably on account of it being really difficult it's also labeled as a lit difficult it's also labeled as a lit code hard code hard and i do agree with that label so that's and i do agree with that label so that's exactly why i wanted to make this video exactly why i wanted to make this video i really hope it will help you guys and i really hope it will help you guys and if it does please let me know in the if it does please let me know in the comment section because i would love to comment section because i would love to know know okay so let's get straight into the okay so let's get straight into the problem description there are n workers problem description there are n workers the ice worker has a quality measurement the ice worker has a quality measurement and a minimum wage expectation and a minimum wage expectation i'm just going to change the name of the i'm just going to change the name of the array because array because i want it to be called expected wage now i want it to be called expected wage now we want to hire we want to hire exactly k workers to form a paid group exactly k workers to form a paid group when hiring a group of k workers we must when hiring a group of k workers we must pay them according to the following pay them according to the following rules rules so the first rule is that every worker so the first rule is that every worker in the paid group should be paid in the in the paid group should be paid in the ratio ratio of their quality compared to other of their quality compared to other workers in the group workers in the group and in other words it means that the and in other words it means that the ratio between the offers that we make to ratio between the offers that we make to any two workers has to be exactly equal any two workers has to be exactly equal to the ratio between their qualities so to the ratio between their qualities so in other words the first rule in other words the first rule says exactly that now the second rule is says exactly that now the second rule is that every worker in the paid group that every worker in the paid group must be paid at least their minimum wage must be paid at least their minimum wage expectation expectation so again in other words the the offer so again in other words the the offer that we make them that we make them has to be larger or equal to the has to be larger or equal to the expected wage of the worker now we want expected wage of the worker now we want to return the least amount of money to return the least amount of money needed to form a paid group satisfying needed to form a paid group satisfying the above conditions the above conditions okay so we want to return the minimum okay so we want to return the minimum cost that it will take us cost that it will take us to hire k workers considering these to hire k workers considering these rules so the first important thing to rules so the first important thing to notice here is notice here is that because we're trying to pay the that because we're trying to pay the least amount of money there is always least amount of money there is always going to be at least one worker in the going to be at least one worker in the group group that is paid exactly what he asked for that is paid exactly what he asked for otherwise we pay everyone more than they otherwise we pay everyone more than they wanted which is a missed opportunity wanted which is a missed opportunity right right we could be paying everyone a little we could be paying everyone a little less and still satisfy the conditions so less and still satisfy the conditions so again there's always going to be at again there's always going to be at least one worker in the group that is least one worker in the group that is paid his expected wage paid his expected wage we'll call that worker the captain so we'll call that worker the captain so the second important insight here the second important insight here is that once we decide who the captain is that once we decide who the captain is once we decide uh what to pay is once we decide uh what to pay one worker we know exactly what we need one worker we know exactly what we need to pay all of the others and i'll show to pay all of the others and i'll show you exactly what i mean you exactly what i mean so uh we decided that we're going to pay so uh we decided that we're going to pay the captain his expected wage right the captain his expected wage right now we have this a second rule that now we have this a second rule that states that the states that the um ratio between offers to any two um ratio between offers to any two workers workers including that of the captain is equal including that of the captain is equal to the to the ratio of their qualities so if we ratio of their qualities so if we substitute substitute this uh term with this one we get to this uh term with this one we get to this equation here now i want to isolate this equation here now i want to isolate this term so i'm going to multiply both this term so i'm going to multiply both sides with the captain's expected wage sides with the captain's expected wage and then i get to this equation here so and then i get to this equation here so basically what this means basically what this means is that once we decide who the captain is that once we decide who the captain is we will know the value of these two is we will know the value of these two terms terms and then we will know exactly what we and then we will know exactly what we need to offer each of the other workers need to offer each of the other workers the amount that we'll need to offer to the amount that we'll need to offer to worker i worker i is equal to the quality of worker i is equal to the quality of worker i multiplied by the captain's ratio now multiplied by the captain's ratio now let's see an example let's see an example so we have three workers in this example so we have three workers in this example we're going to call them we're going to call them jay tom and ben each worker has a jay tom and ben each worker has a quality measurement and an expected wage quality measurement and an expected wage and we want to find the minimum cost to and we want to find the minimum cost to hire two workers so the way we approach hire two workers so the way we approach this this is we give each worker a chance to be is we give each worker a chance to be captain then for each captain we captain then for each captain we calculate how much we're going to have calculate how much we're going to have to pay each of the other workers to pay each of the other workers then we pick the two workers that cost then we pick the two workers that cost the least amount of money the least amount of money and that's going to be the cost for this and that's going to be the cost for this captain and then captain and then at the end we will pick the group that at the end we will pick the group that cost the least out of all of the cost the least out of all of the captains now let's see how this works captains now let's see how this works so if jay is the captain we're going to so if jay is the captain we're going to pay his minimum wage expectation which pay his minimum wage expectation which is 80. is 80. and then the captain's ratio is going to and then the captain's ratio is going to be 80 divided by 10 because 10 is j's be 80 divided by 10 because 10 is j's quality quality so 8 and then we're going to offer tom so 8 and then we're going to offer tom 5 which is this quality 5 which is this quality multiplied by 8 which is the captain's multiplied by 8 which is the captain's ratio ratio so 40. then we're going to offer ben so 40. then we're going to offer ben 15 times 8 which is 120 15 times 8 which is 120 and then we're going to pick the two and then we're going to pick the two workers in this group workers in this group that cost the least which are uh jay and that cost the least which are uh jay and tom so the minimum cost with jb and the tom so the minimum cost with jb and the captain captain is 120. now if tom is the captain we're is 120. now if tom is the captain we're going to pay his expected wage going to pay his expected wage so uh 35 and then the captain's ratio is so uh 35 and then the captain's ratio is going to be going to be uh 35 divided by 5 which is 7. uh 35 divided by 5 which is 7. so j is going to be offered 10 so j is going to be offered 10 multiplied by 7 which is multiplied by 7 which is 70. now notice we're not allowed to 70. now notice we're not allowed to offer 70 to j because his minimum offer 70 to j because his minimum expectation is 80. expectation is 80. uh so if tom is the captain we are not uh so if tom is the captain we are not allowed to hire jay allowed to hire jay ben will be offered 15 times 7 which is ben will be offered 15 times 7 which is 105. 105. it's above his expectation so it's good it's above his expectation so it's good so if tom is the captain so if tom is the captain the cost of the group is going to be 35 the cost of the group is going to be 35 plus plus 105 which is 140. and lastly if ben is 105 which is 140. and lastly if ben is the captain we're going to pay his the captain we're going to pay his minimum expectation minimum expectation the captain's ratio is going to be 30 the captain's ratio is going to be 30 divided by divided by 15 which is 2. then we're going to offer 15 which is 2. then we're going to offer j j 10 times 2 which is 20. that's below his 10 times 2 which is 20. that's below his expectation so we cannot hire j expectation so we cannot hire j we're going to offer tom 5 times 2 which we're going to offer tom 5 times 2 which is 10 is 10 and this is again below his expectations and this is again below his expectations so we cannot hire tom so we cannot hire tom and that means that ben cannot be and that means that ben cannot be captain because there are no groups of captain because there are no groups of two workers two workers that satisfy the conditions and now we that satisfy the conditions and now we choose the minimum cost between the choose the minimum cost between the captains which is 120 captains which is 120 and this is the value that we want to and this is the value that we want to return okay so let's start with the code return okay so let's start with the code we'll start with the nav way and go from we'll start with the nav way and go from there there so i'm just going to start by getting so i'm just going to start by getting the number of workers then we're going to need a variable for the main cost i'm going to initialize it to the maximum possible value a double can have in c plus plus it would look like this now we're going to give each worker a chance to be captain and we want to calculate the captain's and we want to calculate the captain's ratio it's going to be ratio it's going to be the captain's expected wage divided by the captain's expected wage divided by his his quality next we're going to calculate quality next we're going to calculate how much we're going to offer how much we're going to offer each other worker we're going to offer the quality of the worker multiplied by the captain's ratio then the offer is accepted only if it is larger or equal to the expected wage of the worker so we're going to need an extra vector here that will hold all of the accepted offers so i'm going to call it accepted offers and now if the offer is larger or equal to the expected wage we want to add the offer to the accepted offers array now at this point if the size of the accepted offers array is less than k it means that this worker cannot be captain because he cannot form a group of um k workers that satisfy the conditions this is the exact situation that we had with ben being the captain in the example okay so we just want to move on to the next captain the next thing we want to do is we want to find the sum of the k smallest elements in accepted offers array finding the k smallest okay largest elements in an array is actually a very common problem with a very common solution and the solution is to use a heap for k smallest we want to use a max heap now this is not the main topic of this video so i'm going to do this very briefly if you want to get more information about this algorithm uh you can just search for uh k smallest elements and you will get like a million results so uh for now let's just write the code for this so we're going to define a max heap in c plus bus it's called the we're also going to need a variable for we're also going to need a variable for the sum of the heap the sum of the heap initialized to zero and then we're going initialized to zero and then we're going to build the heap to build the heap out of the k first elements in the out of the k first elements in the accepted offers array next we want to iterate over the other next we want to iterate over the other elements in the accepted offers array so elements in the accepted offers array so start at k start at k all the way to the end and if the heap all the way to the end and if the heap is not is not empty and if the empty and if the current offer is smaller than the current offer is smaller than the maximum element in the heap then we want to replace the maximum so the cost for the minimum group that so the cost for the minimum group that this captain can form this captain can form is actually exactly the uh sum of the is actually exactly the uh sum of the heap heap and then we want to keep track of the and then we want to keep track of the minimum cost out of all of the captains minimum cost out of all of the captains now we want to return the main cost now we want to return the main cost so let's try this it's pretty inconsistent with the capital age here okay so the code works for the example but it's not going to be accepted because of the runtime let's think about how to improve this so i want to focus on this line here an offer to worker x is only accepted if it is larger or equal to the expected wage of the worker the offer is equal to the quality of the worker multiplied by the ratio of the captain if we divide both parts by the quality of the worker we get to this expression here which means that the only offers that are going to be accepted are the ones to worker that have ratio that is smaller or equal to the captain's ratio so if we sort the workers by their ratio we will know in advance which workers are going to accept our offer all the workers that are on the left of the captain in the sorted array will accept the offer and all the workers that are on the right of the captain will not accept it so we could just avoid making them in the first place and save time so let's get back to the code and see how it works okay so the first thing that we want to add to this code is an array of workers that is sorted by the ratio each pair will contain the ratio and the quality of the worker and the size of this array is going to array and now we're going to sort this array so it's sorted by the ratio so now we don't need to give each worker a chance to be captain because we know that workers at index below k minus one will not be able to form a paid group because they don't have uh k workers that have uh smaller ratios right so we can start this loop from k minus one now we already know the captain's ratio because we calculated it here right so you can just take it from the workers array like this and we only want to look at workers on the left of the captain because these are the workers that are going to accept the offer so we can stop this loop here and then we can also remove this condition because we know that that all of them are going to accept the offer and we want to also um take the quality from the workers array and uh not from the quality array because we want it to be sorted so uh it's here now we don't need this line right because we know for a fact that the accepted offers array is going to be uh larger than k so we can remove it and the rest of the code stays exactly the okay so let's try to submit this okay so let's try to submit this okay so as you can see this is still okay so as you can see this is still taking too much time taking too much time so let's look at what we can do next so so let's look at what we can do next so basically what happens in this section basically what happens in this section is that for each iteration i the captain is that for each iteration i the captain is worker i is worker i and we want to find the k smallest and we want to find the k smallest elements in this array elements in this array we want to find the k smallest offers to we want to find the k smallest offers to workers that are on the left of the workers that are on the left of the captain captain so that's why it goes from zero to i so that's why it goes from zero to i then in iteration i plus one then in iteration i plus one the captain is worker i plus one and we the captain is worker i plus one and we want to find the k smallest elements in want to find the k smallest elements in this array that goes from this array that goes from zero to i plus one now this feels like a zero to i plus one now this feels like a lot of duplicate computations right lot of duplicate computations right it would be great if we can somehow it would be great if we can somehow reuse the results from previous reuse the results from previous iterations iterations and not start from scratch for each and not start from scratch for each captain right the problem is that captain right the problem is that these offers are not the same for each these offers are not the same for each captain captain because they depend on the captain's because they depend on the captain's ratio ratio so the trick here would be to just so the trick here would be to just remove the captain's ratio out of the remove the captain's ratio out of the equation equation like that and now this array is exactly like that and now this array is exactly like this array like this array plus this one extra element right plus this one extra element right because it's just an array of the because it's just an array of the qualities qualities which don't depend on anything so by the which don't depend on anything so by the time we reach iteration i plus 1 time we reach iteration i plus 1 we already know the k smallest we already know the k smallest quantities in this array and all we have quantities in this array and all we have to do is decide how this last element to do is decide how this last element fits in fits in and this is pretty easy so let's do that and this is pretty easy so let's do that in code okay so because we now try to in code okay so because we now try to find the k smallest qualities and not find the k smallest qualities and not the case smallest offers the case smallest offers we can just remove the part that we can just remove the part that calculates the uh offers right calculates the uh offers right we can also take the part that we can also take the part that initializes the heap and put it outside initializes the heap and put it outside so it's only done so it's only done once and again because we are talking once and again because we are talking about about qualities this is not a double it's an qualities this is not a double it's an int int this also and this is not for the this also and this is not for the accepted offers we want to accepted offers we want to put here the qualities and the qualities put here the qualities and the qualities are so now we have the sum of decay first qualities so let's also compute the cost for the first group and we don't need this here we can just okay so now we also have to start here okay so now we also have to start here from k and not k minus one from k and not k minus one and now we also don't need this loop and now we also don't need this loop here right because for each captain all here right because for each captain all we have to do is figure out how the we have to do is figure out how the captain's quality fits in which is the captain's quality fits in which is the last element in the array so we don't last element in the array so we don't need the loop we can just take need the loop we can just take this part and do it once this part and do it once and of course instead of this term we and of course instead of this term we need to put in the captain's quality so now the sum of the heap is not the sum of the offers it's the sum of the qualities so we need to multiply it by the captain's ratio okay so let's try to submit this okay so let's try to submit this now this should be k minus one okay so this is a success we passed all the test cases and with pretty good time so let's say a few words about the complexity this loop will take of and worse time and then sorting the loop would be o of n log n building this heap is o of k and then this loop would take uh o of n log k because we have uh n iterations and uh with each iteration we do a push to a heap of size k which takes low k so that's how we get to n log k so the total time complexity would be n log n because this is the most uh time consuming part right so uh the time complexity of this algorithm is o of n log n okay so that is it for this video i hope it helped you guys if you liked it please give it a thumbs up and i will see you next time thanks for | 2024-03-22 16:22:48 | 857 | Google Coding Interview Question and Answer - Min Cost To Hire K Workers [LeetCode 857] |
|
OcOe66L1EKg | hello and welcome everyone let's continue edition prasad lists by solving continue edition prasad lists by solving climbing stairs climbing stairs while climbing is stick is and it takes while climbing is stick is and it takes n number of stairs n number of stairs steps to reach the top we can take steps to reach the top we can take either one or two steps and how many either one or two steps and how many distinct twists can we claim to the top distinct twists can we claim to the top we can see from the first example that we can see from the first example that we have two staircases and we want to we have two staircases and we want to get to the top so drawing a picture we get to the top so drawing a picture we can see that this is one staircase this can see that this is one staircase this is two stickies and this is you is two stickies and this is you in one huge step you can get to the top in one huge step you can get to the top this is one way or you could start this is one way or you could start slowly and get to the top in which case slowly and get to the top in which case this is going to be two ways and we also this is going to be two ways and we also have um have um let's try the second example where we let's try the second example where we have three have three the staircase is at three the staircase is at three and and once again this is you you could start once again this is you you could start slow and climb to the top this is one slow and climb to the top this is one or or could start slow then take a big chunk could start slow then take a big chunk of step and this is going to be one of step and this is going to be one or rather one or rather one or you could take a big chunk and decide or you could take a big chunk and decide to go slow and then this is three but imagine that our staircase we're giving five right we're giving five five staircases rather this is one two three four and five this could get really complex and confusing in that you could start here this is one you could start one go two three and this get really confusing this just tells you that we can try something like a decision tree should we try that maybe um so this is you here and you want to get to the top of the staircase right the top of the staircase is basically when there is no more stickies for you to get to but we know that you can take either one or two stairs at a time or two stairs at a time basically so you either taking one basically so you either taking one staircase in which case you would have staircase in which case you would have two more stickies to conquer or you two more stickies to conquer or you could taste two stickies in which case could taste two stickies in which case you would have just one more staircase you would have just one more staircase to climb to climb again we can see that again we can see that you can take you can take for each step that you've taken now you for each step that you've taken now you can either take one more step in which can either take one more step in which case you would have one step to conquer case you would have one step to conquer or you could take two state cases in or you could take two state cases in which case now you have zero steps to which case now you have zero steps to conquer now this basically means that conquer now this basically means that okay cool yeah at the top okay cool yeah at the top you're at the top here because you have you're at the top here because you have no more stickers to conquer now let's no more stickers to conquer now let's continue with this side where you want continue with this side where you want to take one staircase to take one staircase and this is zero you have nothing else and this is zero you have nothing else to conquer you've gotten to the top to conquer you've gotten to the top ray you're at the top ray you're at the top or you could take two staircases in or you could take two staircases in which case one minus two is going to be which case one minus two is going to be minus one and this doesn't work right minus one and this doesn't work right this is invalid that means when at this this is invalid that means when at this from this point you can take two from this point you can take two stickies stickies because it will lead to it's really to because it will lead to it's really to you falling off of the staircase there you falling off of the staircase there is nothing else you can take minus one is nothing else you can take minus one now we can go back to this final one now we can go back to this final one and whereby take one staircase and whereby take one staircase and you arrive at the top again because and you arrive at the top again because there is nothing else this is zero or there is nothing else this is zero or you take two stickers in which case we you take two stickers in which case we have what we previously had here in have what we previously had here in which you fall so now we can see that we which you fall so now we can see that we have three staircases using a decision have three staircases using a decision tree now why am i using a decision tree tree now why am i using a decision tree i am using a decision tree because it is i am using a decision tree because it is easier to picture a decision tree for easier to picture a decision tree for large cases we can't count the staircase large cases we can't count the staircase for having five but we can use a for having five but we can use a decision tree to picture what we want decision tree to picture what we want now as for to now as for to make it a little bit neater make it a little bit neater the left arrow or the left side the left arrow or the left side basically we're taking off we're taking basically we're taking off we're taking one step one step and the right is going to signify that and the right is going to signify that we're taking um we're taking um two steps also rather than getting to two steps also rather than getting to the zero keys can we make it better we the zero keys can we make it better we see that when we are three we would kind see that when we are three we would kind of see when we get to zero case image of see when we get to zero case image because when we get to zero there is no because when we get to zero there is no more staircase to conquer and we are more staircase to conquer and we are good but if we go beyond zero then we good but if we go beyond zero then we can't take that step and we know that can't take that step and we know that that's wrong that's wrong now rather than getting to zero is there now rather than getting to zero is there any best case that we can get to and yes any best case that we can get to and yes there is we know that if there is only there is we know that if there is only one staircase if you are giving just one one staircase if you are giving just one staircase and you are asked to get the staircase and you are asked to get the top of the staircase you can take just top of the staircase you can take just one step you can't take two because one step you can't take two because there is just one staircase if you take there is just one staircase if you take two they are definitely going to fall two they are definitely going to fall off because there is nothing for you to off because there is nothing for you to land onto so one is a base case because land onto so one is a base case because one stairs one stairs gives us one step gives us one step two is also a base case because if you two is also a base case because if you are giving two staircases it is clear are giving two staircases it is clear that you can take just two steps at a that you can take just two steps at a time or just two steps to get to the top time or just two steps to get to the top either you go slow you take one or you either you go slow you take one or you take a big chunk and take two so we know take a big chunk and take two so we know that these two that these two are base cases whereby are base cases whereby um um you take one stairs to get to the top once in one move or there are two steps and it takes you two ways to get to the top now continuing our decision tree let's move on don't forget that left and our right signifies that so just to make this to start this over so just to make this to start this over and give ourselves more space we have and give ourselves more space we have five five left means that we're taking left means that we're taking one step one step right means that we're taking two step right means that we're taking two step our best cases are one and two cool so now we can take one step here in which case would have four left to conquer or we take two in which case we would have three now we could take for each decision now we could take one again in which case we have three to conquer we could take two in which case we have two steps to conquer but our base case tells us that when we have two staircases left then there is only two minimum so at this point we've got it to an answer because we know that there are two steps to take from this place so we're kind of like good here now let's continue with this one we take one stairs one step rather and we are left with two or we take two and we are left with one in these instances we are also good because we've got into a base case whereby two is going to give us two movement and one is going to give us one this is a dynamic programming problem and to better understand this you need to understand things like recursion and memorization because you'll be using that in this problem though there's a way to solve it iterately iteratively rather but this is just a good intuitive way this comes more intuitively to me picturing it then i i'll rather solve this where i can picture the decision tree and then solve it iteratively so i feel like recursion is a good base knowledge to know to solve a dynamic problem knowledge now this three is already repeated here and we know that having this repetition this is going to be a question it's not good for our call stack basically because now we have to go down this decision tree when we've practically already gone down there and this is where we need the memoization technique whereby we have already stored decision tree that we visited earlier so for instance we visited this decision we can store it somewhere and then when we get to another decision we can just check our storage at a storage have we seen this this sub problem before and then our decision tree is like oh yes you have and then we're like okay what's the results rather than going down all this path this is what the memorization technique is for to store sub problems so we don't have to go repeat um problems i've already solved and that's bad for efficiency but for the sake of this joint we're going to go down this path whereby we take one step we have two we take another step and we have one you take one step we have to take one two steps and we have one and we know that our base cases is going to give us two and one if we sum this up together we should have two plus one plus two plus two plus one two four six eight so we have eight ways eight distinct twist to get to the top now this is the first way of solving this problem whereby we use our decision tree to traverse where this is this approach is called bottom it's called top down rather we're going from the largest number and we are going down to our base cases this is precaution and memorization this takes um two of end time complexity this is because for every decision we have two decisions to take and it's just going exponentially right our decision keeps growing exponentially but we can shorten this by using the minimization and then we reduce the um the time complexity to o of n we can go from 12 n o of n using the memorization basically won't be taking two decisions because it's possible that we visited each and then we're just storing this minimization num um yeah our memorization but if there is a way whereby we don't even have to use the memorization technique we don't have to go down the two path can we try that and yes we can actually try that part and this is the iterative top down approach whereby once again we're also going to be considering our base case and what's our being solved in one way you can climb being solved in one way you can climb one staircase in one way or we have two one staircase in one way or we have two staircases and we can climb this in two ways now we have one and we have two in our decision should we know that in our decision should we know that if you take one or you take two then if you take one or you take two then basically you are taking two or one step basically you are taking two or one step but we've already have we already but we've already have we already computed this we already know how many computed this we already know how many steps we are taking steps we are taking in one way or two ways def so we don't in one way or two ways def so we don't have to compute this again or go down have to compute this again or go down this path because we already have this this path because we already have this stored so what can we do instead is that stored so what can we do instead is that we just sum up what we have for taking we just sum up what we have for taking one for taking one staircase and for one for taking one staircase and for taking two stickers and then we have taking two stickers and then we have three i hope this isn't confusing i hope it isn't confusing at all because it might take a bit to wrap your head around just let's go over it again so we know that our base case is one and two in one for one staircase rather you can take one step and for two different staircases we can take two steps now for three different staircases you can take either one or two staircases now instead of computing all this all over again we can just visit what we already computed we already previously stored and just sum it up together because now these are the ways that we can get to it and we just have three basically we're climbing up of each other climbing up of each other if we have four four ways of or first decay while giving us first decades rather we know that it is always going to be the sum of three staircases and two staircases which we've computed before so we don't need to compute all over again basically we can just get the sum of the last previous computation now this is going to give us our six no no sorry this is going to give us five and we know that for the fifth staircase computing this is going to give us eight which is what we got previously so this is the iterative approach and since we're just getting the last two computation we're doing this in linear time and extra space though because we are storing or saving the last previous value but there is a way to not store the previous value whereby just using variables to store them i'm going to show it in the code but i'm not going to be coding that because i don't think it's very intuitive but i'm going to provide it in the code solution linked in the description box but for the purpose of this um problem we're going to be solving using the recursive approach and using the all right let's solve the problem all right let's solve the problem so so to solve recursively since we have a to solve recursively since we have a function i'll be calling itself we need function i'll be calling itself we need to define that function and we need to to define that function and we need to define our base case if n is equal to define our base case if n is equal to basically if our staircase is 1 then we basically if our staircase is 1 then we want to return one but if our staircase want to return one but if our staircase if we have two then we know that if we have two then we know that we want to return to these are base our we want to return to these are base our base cases basically then we want to base cases basically then we want to return um return um want to call this function on itself want to call this function on itself and you want to and you want to take one staircase take one staircase plus plus another chunk another chunk of two staircases then we can return this function this okay yeah this run but if we submit it okay yeah this run but if we submit it we should get a time limit exceeded we should get a time limit exceeded error error like we have here and this is the case whereby if you recall when we're talking about memoization basically this is going to take a while because we are recomputing what we already computed how do i stop this okay time limit exceeded so basically we are recomputing what we already computed since we are taking we have this decision tree it's growing exponentially and this is really bad because our call stack is just calling itself over and over again this will use the memorization technique to store it now we're going to have a global memo variable and we're going to say that if n exists in memo then basically just return the um value basically if we've already computed this number before then we do not need to compute it again we don't need to compute it again just give us back this number there is a imbued function in python lru cache but i'm using this hash table because i think that some languages don't have el rio cash and might be easier for them to understand what's going on using this hash table basically instead of our results our results in this hash table in this hash table and we will be returning this so and we will be returning this so basically what we are doing is basically what we are doing is this is a this is a if we are giving five number of if we are giving five number of staircases and we go down we take one staircases and we go down we take one stairs this is going to give us four or stairs this is going to give us four or we take two steps which is going to give we take two steps which is going to give us us three three now we are storing each of this value now we are storing each of this value for four and four three in a hash table for four and four three in a hash table so that if we go down four paths so that if we go down four paths eventually when we take one step from eventually when we take one step from four we're going to visit these three four we're going to visit these three again rather than solving for three all again rather than solving for three all over again we already have this saved in over again we already have this saved in our hash table this is what we are doing our hash table this is what we are doing here and it's just to um solve for here and it's just to um solve for efficiency to make our code more efficiency to make our code more efficient this is why we are doing this efficient this is why we are doing this and if we submit this now we should see and if we submit this now we should see that this runs that this runs and we no longer get this time limit and we no longer get this time limit exceeded error now let's this is the exceeded error now let's this is the bottom up bottom up rather top down to like i mixed up you rather top down to like i mixed up you know this is the top down recursive know this is the top down recursive approach we're going from top to down approach we're going from top to down like while breaking it down like while breaking it down basically now if we want to solve for basically now if we want to solve for this iteratively we can kind of like this iteratively we can kind of like have an array have an array where we have the base cases now why do where we have the base cases now why do we have an array of the base cases you we have an array of the base cases you can you can store this using a variable can you can store this using a variable but you know that but you know that we are kind of like pretending that our we are kind of like pretending that our array is one indexed year whereby array is one indexed year whereby you are taking one staircase and you you are taking one staircase and you have have you are doing this in just one step or you are doing this in just one step or you are taking two steps you are taking two steps you are taking two steps or you're you are taking two steps or you're giving two staircases and you take two giving two staircases and you take two steps for it we are not considering what steps for it we are not considering what if you are giving zero because basically if you are giving zero because basically that'll mean that there is nothing to that'll mean that there is nothing to climb there is no stickers to climb climb there is no stickers to climb staircase is non-existent so in this um staircase is non-existent so in this um our area we're only considering you are our area we're only considering you are taking one step you are taking to step taking one step you are taking to step and ignoring the zero index but i will and ignoring the zero index but i will come in and do soon come in and do soon now since we already have the base cases now since we already have the base cases of one stickers and two staircases we of one stickers and two staircases we can iterate over our number we already have for two so we don't need to include two we're starting from two and up to the end staircase and we're going to be appending to the value of the last two decisions the value of the last two decisions basically if this was three basically if this was three if this was three there basically saying if this was three there basically saying that sum the last that sum the last the the value at the index before value at the index before and the value at index two steps before and the value at index two steps before because we can only take one step and because we can only take one step and two steps at a time and we are pending two steps at a time and we are pending it to discount and for it to discount and for this this array keeps growing to accommodate the array keeps growing to accommodate the number of staircases that were given and number of staircases that were given and eventually we are going to return eventually we are going to return the this should be square brackets because we are accessing we're going to return if this was three if this had grown it was finished compass and this is three basically we want to return zero one two we're still going to assume that the index is zero one two i want to return the index at this point this is what our answer is going to be this is basically i was going to be growing for three it's going to sum up the last two for four is going to sum up three plus five which is um five three plus two which is five four five is going to sum up five plus three which is eight and basically this is the visualization of what we are doing on line five and line six now we can just run this code and see that it and once we're sure this works we can go and once we're sure this works we can go ahead and submit it all right this is a very good way to practice this is similar to the fibonacci number this problem and is a very good um way to practice dynamic programming to warm us up for more complex dynamic programming problems because the manufacturing problems can get really complex but i really really hope that you understood it i tried earlier to explain it as much as i could if you had not come across dynamic programming problems before but yeah let me know what you think in the comment section below thank you for watching this video see | 2024-03-20 11:23:19 | 70 | Leetcode 70 - Climbing Stairs | Recursive & Iterative approach |
|
1d4Tb2uJFt4 | And hero Ram Ram is being seen after a long time, today we are the ones to see [music] Ok Varna, I will explain, there is no problem, see how much Ram becomes, what are you trying to say, the question is ok, the question has been raised what are you trying to say, the question is ok, the question has been raised brother. as if you are seeing that the lines as if you are seeing that the lines cannot be represented in the matrix Music] So this is a matter of keeping things in mind and keeping an eye on things then it will come into it, what do you guys want to say? what do you guys want to say? what do you guys want to say? Hope, I understood that where there is this cylinder, there is a van where this cylinder is, the mines van is fine and it is not complete, only one raw is left, okay, so what to do now, what is the issue, what is the issue, Aapke bol de rakhi hogi ball de rakhi Aapke bol de rakhi hogi ball de rakhi Aapke bol de rakhi hogi ball de rakhi hogi like yeh de bol de rakhi it is ok it falls till the bottom if it is following the path ok then you have to return it to the place where it has fallen i.e. Its van is, Its van is, Its van is, if I show you, it is not being returned anywhere, it is not it is not being returned anywhere, it is not returning anywhere, this ball which is returning anywhere, this ball which is not being returned, if you look at its post, it not being returned, if you look at its post, it ends here, there ends here, there is an issue here, so you have to understand that it is an issue here, so you have to understand that it means problem. means problem. means problem. small thing which you have to understand, a small concept, if it is not coming, there is no problem from within you, it is not coming, no problem, see, there is a pattern that if it is And there is And there is And there is this one on the adjacent one too, this one on the adjacent one too, so I am writing that it will go to row plus so I am writing that it will go to row plus van column plus van, right zero zero and here van is from both sides, so I Well, there is a condition there, meaning if yours is from this one and this one, then it will definitely reach here and if you have this one and this one, then I am from, definitely it will reach here, it came out here It is right here, It is right here, It is right here, in this sector, in this sector, and when will the ball not reach down? In this case, and when will the ball not reach down? In this case, if you have this one on the left, this one on the if you have this one on the left, this one on the right, this one, or you have right, this one, or you have this one on the left and this one on the left, then the ball will never go. this one on the left and this one on the left, then the ball will never go. this one on the left and this one on the left, then the ball will never go. n't, it's a simple thing, okay, so I hope you have just understood, no, I will go back once and listen to what I have said, okay, now all this has been discussed, now how to code in this. So you will understand more and how to do it, if you see a little constant, what is done in it is M grade length and your M means daily, it is starting from one and the columns continue till 100, so this one we call global Or we can create a vector Or we can create a vector Or we can create a vector office of this size and we can office of this size and we can pass reference to it. pass reference to it. Creating global global variables is Creating global global variables is harmful for health, it is harmful for interviews. harmful for health, it is harmful for interviews. So what we will do is first So what we will do is first enlarge the screen a little. enlarge the screen a little. enlarge the screen a little. will do it with difference, so what do we have, let's first check the inter row, row, okay, if you do it like this from here, then you will okay, if you do it like this from here, then you will also get the column, you have got the also get the column, you have got the column bill, now what should we do ] from infinity, from infinity, ok ok and I have written the spelling of vector very beautifully, ok, now what will we do with all this, now ok, now what will we do with all this, now basically we are DP, ok. basically we are DP, ok. basically we are DP, ok. and that is, we will call the type and it will be done So in these less give the So in these less give the column high plus ok column high plus ok [Music] Yes, we will have to start, so we will start, so we will start from 0, meaning the first start from 0, meaning the first box will come and start from that. box will come and start from that. box will come and start from that. column is running with you, then let's column is running with you, then let's mix it for the daily, zero earned is ok, if that ball reaches the bottom, then we will if that ball reaches the bottom, then we will give its index. give its index. give its index. on which column is the induction started from zero, otherwise if we give it in mines, then we will give the vector of brick to make the solution and not write inter row, give If you are doing this If you are doing this If you are doing this then let's write vector vector in portion DP then let's write vector vector in portion DP Apart from this I don't think there is any Apart from this I don't think there is any need for need for anything, everything is fine, when our scene will end we we we into the bound, so let's write a boolean function and the current column and the current column is the current N current standard row and column and what is the current N current standard row and column and what can we return if row is greater give equals can we return if row is greater give equals zero and zero and zero and than N and if the column is smaller than M then Before checking if this is valid, it is Before checking if this is valid, it is giving us the correct value, which means which condition is to be checked. means which condition is to be checked. We all understand okay if row of column de great and the column on which I music] what are we doing okay if this is the scene what are we doing okay if this is the scene then what to do now then what to do now we would have checked the DP in Simply DP, [Music] Apart from this, if the condition comes, we will do the routine, we will not able to solve it, I am a little behind in the line. not able to solve it, I am a little behind in the line. not able to solve it, I am a little behind in the line. look a bit dirty but okay, now in a similar manner, we have to reduce it to N - 1, we do it by copy paste because I am a pro copy [Music] [Music] Column minus one will be Column minus one will be grade off. Let's also check this -1. Okay, grade off. Let's also check this -1. Okay, I I want [Music] -1 case. In this, there will be row plus one and plus one. [ [Music] So that's Interesting question, here is the code, its ok and if you Interesting question, here is the code, its ok and if you Interesting question, here is the code, its ok and if you enjoy this video then enjoy this video then remember, nothing else is required, ok Radhe remember, nothing else is required, ok Radhe Radhe | 2024-03-20 15:04:49 | 1,706 | Leetcode 1706. Where Will the Ball Fall C++ Solution |
|
Af4G5l4RFLg | here we go let's start the timer and read the question read the question okay restore IP addresses zero to 255 inclusive cannot have leading zeros so it cannot be zero mm-hmm okay a string containing only digits return all possible valid IP addresses not allowed to reorder or remove not allowed to reorder or remove we can only insert dots we can only insert dots and three dots we can insert three dots and three dots we can insert three dots okay okay we have an input that's only digits okay we have an input that's only digits and we want to insert three dots to make and we want to insert three dots to make valid valid IP addresses valid valid IP addresses and we want to return all of those valid and we want to return all of those valid addresses okay if so hmm we could do we could do so the length would at most be three so the length would at most be three times four times four since each integer can be since each integer can be at most 255 so if length it's so in example one so in example one length is 11 which means it will have to length is 11 which means it will have to be be three digit three digit three digit and three digit three digit three digit and two digits so how would we I mean we need to think about how we will solve it just like using our eyes and brains just like looking at how we would solve it first so if we have this I know that I need to use at most one that's only two digits the rest has to be three digits so we can start with 255 or 25 and those are the only two options if you start with 25 we see a five which is bigger than 255 so that's instantly invalid because it will need to be like this so that option is over so we need to have 255. and then we do this we try with two digits same case wouldn't work it has to be three digits okay now we do this we try two digits that works we try three digits that works okay so example one we have a clue of how to solve it but now let's look at the next one okay only four digits in total which means there's only one option we just have to add a dot between each digit okay what about when we have a six digits in input string input string um so six stitches and our options would be like one one we could do or one one or one one two two yeah I guess that's yeah I guess that's the only two possible so first we try with just one digit so first we try with just one digit oh so we try with one oh so we try with one and we see and we see okay we tried one okay we tried one I will try one again then we have two two or one three two two works one three does not work because there's um there's the leading zero okay okay now we try it with two one one [Music] [Music] two two or two one two which does not work because of the leading zero so two two and then we go two three and then we go two three okay three one one one that's the only okay three one one one that's the only option so we have option so we have 101 dots 0.2.3 101 dots 0.2.3 okay this is starting to feel like this is starting to feel like a pretty difficult question how would we solve this how would we solve this okay what if let's okay what if let's make up another example um let's see I mean we can do the I mean we can do the one provided here so what could we have for 10 digits so what could we have for 10 digits we could have we could have one three three [Music] we could have okay let's two two three three um hmm it has to be it has to be one three three and two two three three hmm when we had 11 digits what are when we had 11 digits what are the options two three three three that was the only option okay so of course we had 12 digits it has to be what about nine digits two three three hmm are there so if we had one you cannot have one here okay could we do anything with two eight seven this will be the same thing or no actually no because it's it will be different this will be different at the addresses which means even though we have only which means even though we have only this this combination combination we will need to do we will need to do all the permutations as well all the permutations as well so so so when we have one through three we not so when we have one through three we not only have to try for one three three we only have to try for one three three we also have to try four three one three also have to try four three one three three three one three and three three three three one three and three three three one three one so all permutations of that same so all permutations of that same combination combination okay getting very okay getting very troublesome troublesome all right so so here we have just the all right so so here we have just the possible combinations possible combinations and for each combination we have to try and for each combination we have to try out all the out all the permutations okay let's permutations okay let's let's finish this eight digits let's finish this eight digits we could do one one we could do one one three three one two um if you have one three only have one three two two it's the same there or one three one three this is still the same so this same okay okay that's all the options that's all the options what about seven digits what about seven digits you can have one one two three you can have one one two three what about one two what about one two two um okay six digits one one okay six digits one one equal to one on one three one one two two what about one two something one two one two that'll be the same okay and that's the only option four digits then it has to be one okay so these are so these are ignore that um so these are the possible combinations when we have this amount of digits in the input and for each combination except for these which are just same for each part so for all the other ones we could do um and while we are checking we need to make sure it's between 0 and 255 and we want to store them to return and we want to store them to return okay how would we be able to do this valid well we do not want to separate into all well we do not want to separate into all these different cases because that's these different cases because that's gonna be gonna be some some not quite a good solution what if we just we are given a string and then we always try with one one one first until it doesn't work then one one one two one one one two and one one one three and then we try one one two one one two two one one two three that seems pretty Lucian um [Music] okay so if we have okay so if we have I mean if we are gonna try [Music] two one one one three so this is gonna be so we have one two three three options and we have four and we have four that's gonna be that's gonna be 81. that doesn't feel very efficient oh gosh it's already been 20 minutes and that's haven't even found a solution okay I mean this seems like the only approach that I can think of right now even though it's tedious um is looks like it should work okay well I can think of something else right now so let's see if we can translate that into code so we have a string and we want to try when we see it's not working we just when we see it's not working we just move on to the next and then move on to the next and then try this try this and then we move on to the next well I really don't want to have four well I really don't want to have four four loops but what would be the other way if you're gonna do one two three and then one two three one two three one all right I cannot think of something else right let's just use okay I don't think this is the solution we I don't think this is the solution we are looking for okay okay [Music] Okay so does it say anything about length okay does it say anything about length okay smaller than 20 um substring zero and using zero and using this many and we wanna I mean we can do tripods we could do I mean we can do tripods we could do convert to int convert to int but is the input okay how is the input only digits okay so it will not this start index and things yeah that's what start index and things yeah that's what remember okay we started zero remember okay we started zero and like this and like this same as that and and [Music] [Music] if I mean it's Gotta Be A if it's outside of the strange we can if it's outside of the strange we can just Skip and continue to the next round if a one if you want if a one it has a leading zero it's in 30 to try parse it's in 30 to try parse okay let's see if that works otherwise okay let's see if that works otherwise we're gonna do in 32 try parts so that's gonna start at so that's gonna start at oh so I won if I one is one and I do it should be the same check here right it should be the same check here right h okay this is repetitive which means we need to ref which means we should be able to where does this start or you will just go to the end but or you will just go to the end but that should be the same thing there so put this result in the list which is what would this result be first part S1 Dot is to dot S4 hmm hmm hmm yeah we are forgetting a lot of yeah we are forgetting a lot of conditions here okay hmm hmm okay okay and if hmm oh yeah okay yeah so if we're here and there's still a lot left that it's not successful if if it's not the same okay so that's working oh okay very promising almost passed all test cases let's see why would we have this okay okay because the zeros actually was parsed to hmm is it because when we pass zero zero a zero one three is yes okay so the special case when we have two so the special case when we have two zeros zeros that does not work that does not work we cannot have two zeros there definitely need to refactor this because there's a lot of it it's really repetitive at the moment we can definitely put that into a function and then we just call the function but let's just click make sure it works first other ones so if we have zero zero as if okay seems seems like it didn't work um three this hmm okay one last okay one last okay I'll have a couple of zeros a few okay I'll have a couple of zeros a few triple zeros triple zeros hmm hmm oh I mean I could add that in as well oh I mean I could add that in as well but it's but it's also also ugly at this point but at least we know ugly at this point but at least we know that's the last step okay so this should work I'm really looking forward to refactoring this yes not at all the optimal solution okay well so this run time is ready now that reliable so this is like efficient enough I guess even though this is doing like the this is like Brute Force solution okay let's try to riff oh wait let's do timers with analysis and then try to refactor we are doing four we are doing four four loops four loops as mentioned here as mentioned here for each Loop we have only one two three for each Loop we have only one two three just three loops well essentially this is not that bad because this is a constant is actually not gonna scale with input n in any way so no matter what the input is we are always gonna do hmm hmm so each for Loop will run three times so each for Loop will run three times and we have it's gonna run 81 times if and we have it's gonna run 81 times if it doesn't it doesn't right into this continue so it's skipped right into this continue so it's skipped somewhere somewhere if it does go all the way then so I guess we could actually count this so I guess we could actually count this as constant time as constant time and inside we are doing just constant and inside we are doing just constant type of work type of work so I guess this so I guess this even though this algorithm is just brute even though this algorithm is just brute force and stupid it's still constant force and stupid it's still constant time time and does not rely or depend on and the and does not rely or depend on and the size of the the input size of the the input what about space we are doing what about space we are doing we are not using any data structure we we are not using any data structure we are just adding results to to the list are just adding results to to the list so this is all this constant all right so this is all this constant all right I guess we have constant time and space I guess we have constant time and space okay okay now let me see if I can refactor this so we have functions calling okay okay and and bummer that I wasn't able to use this bummer that I wasn't able to use this somehow because somehow because this seems like it could save a lot of this seems like it could save a lot of work but work but but this would mean that we need to but this would mean that we need to separate each cases all the input length separate each cases all the input length separate into all different cases and separate into all different cases and that wouldn't be recursive that wouldn't be recursive like this like this isn't this is not recursive but that isn't this is not recursive but that that will have to be all different cases that will have to be all different cases whereas this just handles all cases in whereas this just handles all cases in one one rhythm hmm all right maybe we have a much better Solutions we're gonna okay let's see if we can refactor this okay let's see if we can refactor this into a function do we need to return anything do we need to return anything [Music] [Music] um yeah I guess I guess we could return the list of string okay what do we call this function it is gonna go on to the next bar let's call it go on to the next bar let's call it check valid check valid so far so far I only need to put in I only need to put in put string I mean we are like if we look at the I mean we are like if we look at the last for Loop we are using all the I one last for Loop we are using all the I one two three two three for for so they need to be in so they need to be in in the input parameters okay now I'm not super sure if this is okay okay I need to go eat dinner I need to go eat dinner okay dinner after this motivation okay okay dinner after this motivation okay we have Inked I one two three four what we have Inked I one two three four what else do we need else do we need we need I mean we probably want this result I mean we probably want this result list with us foreign if if [Music] and length part so we want to obvious [Music] what if we do what if we do okay let's okay let's see what if we do see what if we do Boolean Boolean else um if check valid if check valid is is start would be three length will be I4 and the result string if that returns false otherwise we add the results okay I want if I want if track valid and one more let's continue and let's continue and one more zero one one I two one I two two three two three okay nope oh okay a list an eye a list an eye list oh okay okay s watch hmm what if we do if that's false this this if that's true well I still need to get hmm hmm Square me I still have all the i1 i204 I just don't want to do the substring thing again there's there's a better way but it's substrained I won well this is the stupid way to do this [Music] foreign actually we are not even doing anything actually we are not even doing anything with this oh wait if itself if it's if it's true we are actually coming true we are actually coming okay okay hmm hmm I believe I missed that hmm something is wrong something is wrong let's check oh actually could incorporate this as well okay if s length or or it's not a start no that would be it's not a start no that would be length start also return false okay let's say we have zero zero zero zero have S01 [Music] S01 that's not false that's not false substrings started to your left one we substrings started to your left one we have a zero have a zero that's not true that's not true Parts is what is one so why isn't this okay so this should um um next I want I want to see how many is the steps it's foreign okay oh hmm didn't do oh why is it that it isn't even um so so it's something wrong here it's something wrong here okay so that has returned okay so that has returned false false so you want to continue in each step so you want to continue in each step okay so why did that return false okay so why did that return false let's see zero zero zero zero zero one so nothing's wrong there age zero so this is where I returned false so weird that it didn't have this so weird that it didn't have this problem before before we pull this out into a method before we pull this out into a method itself itself it was the same code so why didn't the it was the same code so why didn't the react before react before okay okay okay okay okay if well well yeah you're trying to edit too fast and yeah you're trying to edit too fast and you make a mistakes which only cost you you make a mistakes which only cost you all right so at least we got that all right so at least we got that fixed fixed we can remove these we can remove these console Red Line yeah I'm trying to stop using visual studio to debug this is well you won't be able to use the visual studio to debug during an interview or during your online assessment so now I'm forcing myself to use console Redline and whatever I can in the code itself instead of debugging stepping in Visual Studio which I usually do let's kind of store the results we have let's kind of store the results we have four four check valid if it's not valid then we check valid if it's not valid then we continue if it's valid we go to the next continue if it's valid we go to the next step step for Loop check valid for Loop check for Loop check valid for Loop check valid valid for Loop for Loop so we so we and we could incorporate this one and we could incorporate this one somewhere here but I think it's fine to leave there otherwise we need to add an extra line here anyways and it will be like extra check for all the other check valid so I think this is fine and then we check valid if it's valid then we add it to the result right I was saying that this is not um it is working though I mean then we will need to store all I mean then we will need to store all these these substrains and we want to store those substrains and we want to store those substrings then I mean we could add extra lines to store there so we don't have these but okay it'll be the same thing and we are checking the length it's enough and we take out the substring and check if it's double zero triple zero and then we convert that to integer to do a final track if it's in the correct range and if it has a leading zero otherwise we okay okay hmm hmm usually I'm gonna start looking at other usually I'm gonna start looking at other Solutions but Solutions but it's already been over an hour so it's already been over an hour so I don't want to make this video super I don't want to make this video super long so we're just gonna look really long so we're just gonna look really quickly quickly and I will spend more time on it after I and I will spend more time on it after I eat eat string and backtracking so this is supposed to be one of those backtracking algorithms which I did not do I will need to work on it later to see I will need to work on it later to see if I can come up with the backtracking if I can come up with the backtracking algorithm I think algorithm I think okay who can be this goat oh it's always okay who can be this goat oh it's always so much fun so much fun looking at all the other Solutions oh look at that oh my God that does look very impressive that does look very impressive okay okay four four four four wait a second okay so instead of checking it inside each Loop like I've done we're just gonna try out all the different kinds of ABCD combinations and then you just take out the corresponding substring and convert to integer and then check if they are all valid this is indeed much smarter oh oh okay huh [Music] oh we do indeed have a recursive okay okay now check out the top three okay I'm gonna stop recording now but I'm gonna come back and now that I've seen the idea behind the first solution I'm gonna yeah rewrite my solution to use that idea so usually I will just like look through quickly and get the idea then I will code that myself instead of copying their code or just looking at their code and somehow doing it in another language so it's always good to try to code the better idea all by myself much better way to learn okay blah blah blah that's enough it's already too long yeah it took me unfortunately a lot of time to solve this okay I'm gonna go have dinner now it's okay I'm gonna go have dinner now it's 8pm | 2024-03-20 13:20:42 | 93 | LeetCode 93. Restore IP Addresses - LIVE coding & thought process |
|
fISIuAFRM2s | 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 island perimeter so this is an easy island perimeter so this is an easy problem but i would say it's more of a problem but i would say it's more of a medium problem medium problem in terms of difficulty it's similar to a in terms of difficulty it's similar to a different graph different graph problem called number of islands and you problem called number of islands and you may have solved that problem before this may have solved that problem before this problem is pretty similar so we're given problem is pretty similar so we're given a grid a grid and in this grid we actually only have and in this grid we actually only have one one island so you can see this is like the island so you can see this is like the water and this brown water and this brown piece is the island so we're guaranteed piece is the island so we're guaranteed to have exactly to have exactly one island and the only thing we need to one island and the only thing we need to do do is for this island we need to find is for this island we need to find the perimeter not the area right the perimeter not the area right counting the area would just be counting counting the area would just be counting the number of cells the number of cells but we want the perimeter so for example but we want the perimeter so for example this this cell has a perimeter of three right this cell has a perimeter of three right this top top or this left part this top and this or this left part this top and this right part right part so let me just redraw it so and this so let me just redraw it so and this center cell it doesn't actually have a center cell it doesn't actually have a perimeter right because it's not perimeter right because it's not connected to any water so this connected to any water so this cell we can't really count the perimeter cell we can't really count the perimeter but take a look at this cell it has a but take a look at this cell it has a perimeter of three the top perimeter of three the top the left and the bottom even though the the left and the bottom even though the left part left part is connected to the edge of the the edge is connected to the edge of the the edge of the entire of the entire uh water it still counts as a perimeter uh water it still counts as a perimeter so this perimeter is three so this perimeter is three and so what you can basically tell right and so what you can basically tell right taking a look at this perimeter we're taking a look at this perimeter we're really just counting the really just counting the parts that are connected to parts that are connected to water right watch connected to water or water right watch connected to water or connected to the entire boundary right connected to the entire boundary right like like this part is connected to the boundary this part is connected to the boundary so that counts as a perimeter so that counts as a perimeter and this part has a perimeter of two and this part has a perimeter of two right the left and the right right the left and the right then you move down this part has a then you move down this part has a perimeter of two as well the bottom and perimeter of two as well the bottom and the right this part has a perimeter of the right this part has a perimeter of three and when you add all of that three and when you add all of that together together we get a sum of 16 so that's what our we get a sum of 16 so that's what our output is going to be we just want to output is going to be we just want to compute that perimeter and then return compute that perimeter and then return it it now if you've solved pretty much any now if you've solved pretty much any other graph problem before you can tell other graph problem before you can tell that this problem is going to require a that this problem is going to require a graph algorithm graph algorithm you can do it with depth first search or you can do it with depth first search or breadth first search breadth first search i'm going to choose to do depth first i'm going to choose to do depth first search because it's usually more search because it's usually more simple and so that's what i'm going to simple and so that's what i'm going to do so we're going to do the depth first do so we're going to do the depth first search algorithm right so search algorithm right so you probably saw that coming if you've you probably saw that coming if you've solved the graph problem before so what solved the graph problem before so what are we going to do are we going to do well we can basically start at any of well we can basically start at any of the cells right let's just start at this the cells right let's just start at this cell for convenience right cell for convenience right what we need to do is we need to visit what we need to do is we need to visit every every single land portion of single land portion of this graph right but that's not enough this graph right but that's not enough we need to somehow find the perimeter of we need to somehow find the perimeter of it how are we going to do that it how are we going to do that well let's just look at it so starting well let's just look at it so starting here here let's go in all four directions right let's go in all four directions right let's go let's go above to the right to the bottom above to the right to the bottom and to the left and see which one of and to the left and see which one of these these neighbors happens to be land as well so neighbors happens to be land as well so first let's go first let's go up here this is clearly land right so up here this is clearly land right so this is one of the other cells of our this is one of the other cells of our island island so from here let's also go in four so from here let's also go in four directions let's go to the right let's directions let's go to the right let's go go above let's go to the left and let's go above let's go to the left and let's go down here to the bottom right but we down here to the bottom right but we know we already know we already visited this bottom cell right that's visited this bottom cell right that's where we came from where we came from so we don't need to visit it again how so we don't need to visit it again how am i going to keep track of that well am i going to keep track of that well i'm going to create a i'm going to create a set you could do an array and i'm going set you could do an array and i'm going to call it to call it visit right it's going to be a set and visit right it's going to be a set and inside of that set inside of that set i'm going to keep track of every single i'm going to keep track of every single position that we visited right so position that we visited right so the coordinates of this could be i and j the coordinates of this could be i and j right so for every position like this right so for every position like this position i'm going to take the position i'm going to take the coordinates coordinates and put it into our set so and put it into our set so so i'm going to do something like this so i'm going to do something like this right visit i'm going to add to it right visit i'm going to add to it the i and j the coordinates of all cells the i and j the coordinates of all cells that we visited before that's going to that we visited before that's going to help us help us when i actually write the code but from when i actually write the code but from here you can tell here you can tell that we only need to go in three that we only need to go in three directions now from this cell right directions now from this cell right so so when we go above what are we going so so when we go above what are we going to find we're going to find that this is to find we're going to find that this is out of bounds we can't go there so out of bounds we can't go there so therefore there's no land over here therefore there's no land over here right right so since there's no land over here so since there's no land over here doesn't that mean that this is doesn't that mean that this is technically a technically a boundary doesn't that technically mean boundary doesn't that technically mean that this is going to be part of the that this is going to be part of the perimeter right perimeter right because if there was another cell here because if there was another cell here that happened to be land that happened to be land then we could not count this as the then we could not count this as the perimeter right but since there's perimeter right but since there's nothing here there's no water there's no nothing here there's no water there's no land there's nothing this counts as a land there's nothing this counts as a perimeter perimeter so when i make a recursive call up here so when i make a recursive call up here in our debt first search function in our debt first search function what i'm going to do is i'm going to what i'm going to do is i'm going to return 1. return 1. i'm going to return 1 because that's i'm going to return 1 because that's going to be that 1 is going to be added going to be that 1 is going to be added to our total perimeter so to our total perimeter so let's keep track of our perimeter so let's keep track of our perimeter so let's add one to it right now our let's add one to it right now our perimeter is going to be one perimeter is going to be one we just counted this portion now let's we just counted this portion now let's make a recursive debt first search call make a recursive debt first search call to the right to the right now i find that this is water if it was now i find that this is water if it was actually land actually land i would not be able to count this as a i would not be able to count this as a perimeter but there's nothing here this perimeter but there's nothing here this is water is water so i'm going to count this as the so i'm going to count this as the perimeter again so i'm going to add one perimeter again so i'm going to add one to our perimeter to our perimeter and the exact same thing clearly is and the exact same thing clearly is going to happen when we go to the left going to happen when we go to the left right right so since there's nothing here i'm going so since there's nothing here i'm going to return a 1 to return a 1 add that to our perimeter so now you may add that to our perimeter so now you may have noticed have noticed basically what we're going to be doing basically what we're going to be doing is a depth first search is a depth first search visiting every single cell in our visiting every single cell in our island and once we get to the base case island and once we get to the base case right the base cases when we get out of right the base cases when we get out of bounds bounds we reach water or we literally reach the we reach water or we literally reach the edge of our edge of our grid then the base case is basically grid then the base case is basically going to be return going to be return one right basically we can add that as one right basically we can add that as part of our perimeter and then part of our perimeter and then once we've visited every single part of once we've visited every single part of our island our island we're gonna take that sum for the we're gonna take that sum for the perimeter and then return it right perimeter and then return it right that's all we really need to do that's all we really need to do so just to show you a little bit of so just to show you a little bit of what's gonna happen next is okay so we what's gonna happen next is okay so we visited that part visited that part now let's go over to the right over here now let's go over to the right over here right so in this position now we're right so in this position now we're going to do debt for search again now we going to do debt for search again now we can't go back there because we've can't go back there because we've already visited we can go down already visited we can go down right and up right and each of those is right and up right and each of those is going to be the base going to be the base case so we're going to return 1 plus 2 case so we're going to return 1 plus 2 plus plus 3 right so let's just add a 3. when we 3 right so let's just add a 3. when we go go left the exact same thing is going to left the exact same thing is going to happen right from here happen right from here you know in any of the three directions you know in any of the three directions we're allowed to move in we're allowed to move in we're gonna reach the base case we're we're gonna reach the base case we're gonna end up returning one for each of gonna end up returning one for each of them them so we can add three to our perimeter so we can add three to our perimeter again now when we go again now when we go down here right we have down here right we have three directions to move we can't go three directions to move we can't go back up because that's where we came back up because that's where we came from we can go from we can go left which is the base case right so add left which is the base case right so add one there there's nothing over here one there there's nothing over here we go right that's another base case we we go right that's another base case we add one and we can go add one and we can go down right down is going to continue our down right down is going to continue our debt first search so really debt first search so really from this cell we're gonna be adding two from this cell we're gonna be adding two so let's add two to our perimeter so let's add two to our perimeter and now we have three directions to move and now we have three directions to move in we can't go back up that's where we in we can't go back up that's where we came from we can go to the right came from we can go to the right we can go down and we can go left if we we can go down and we can go left if we go go right we're gonna reach the base case right we're gonna reach the base case add one to our perimeter if we go down add one to our perimeter if we go down we're also going to reach the base case we're also going to reach the base case add one to our perimeter so in total add one to our perimeter so in total we're going to add two we're going to add two and then we can move left which is going and then we can move left which is going to be the last to be the last cell that we need to visit in our island cell that we need to visit in our island now from here we have three directions now from here we have three directions to move in to move in up left and down right all up left and down right all three of those is going to reach the three of those is going to reach the base case because there's no more base case because there's no more island left for us to reach so one plus island left for us to reach so one plus two plus three is going to be added to two plus three is going to be added to our perimeter you add all of these up our perimeter you add all of these up three three plus six plus four three three plus six plus four plus three that's going to be 16. that's plus three that's going to be 16. that's quick math for you quick math for you and so this is going to be the perimeter and so this is going to be the perimeter we visited every single cell we visited every single cell in our island depth for search we had a in our island depth for search we had a very simple base case very simple base case now let me show you what that's going to now let me show you what that's going to look like in the code look like in the code so as i mentioned we are going to need so as i mentioned we are going to need one data structure i'm going to use a one data structure i'm going to use a set but you could use a 2d array set but you could use a 2d array this is just going to tell us which this is just going to tell us which cells of our island we already visited cells of our island we already visited so we don't end up visiting a cell so we don't end up visiting a cell twice now i'm also going to create a twice now i'm also going to create a depth for search function depth for search function i'm going to put this function inside of i'm going to put this function inside of another function so it's going to be another function so it's going to be easy we don't have to pass in every easy we don't have to pass in every single single parameter to every single function call parameter to every single function call we don't have to pass and visit into the we don't have to pass and visit into the function function the only parameters we pass in are the the only parameters we pass in are the coordinates of the cell that we're coordinates of the cell that we're visiting visiting so remember the main base case we have so remember the main base case we have to worry about to worry about is if we're out of bounds right so if i is if we're out of bounds right so if i was was greater than or equal to the length of greater than or equal to the length of the grid basically the number of rows the grid basically the number of rows or if j was greater than or equal to the or if j was greater than or equal to the number of number of columns so if either of these are true columns so if either of these are true then we're out of bounds then we're out of bounds there's a few more cases we have to there's a few more cases we have to check so if check so if i is less than zero we're out of bounds i is less than zero we're out of bounds or or if j is less than zero that means we're if j is less than zero that means we're also out of bounds of the grid and the also out of bounds of the grid and the last thing we have to check last thing we have to check is if the position we reached is inbound is if the position we reached is inbound so we check so we check i and j and so if this position happens i and j and so if this position happens to be equal to to be equal to zero that means we reached water so in zero that means we reached water so in this grid this grid zero represents water one represents zero represents water one represents land so if any of this is true that land so if any of this is true that means we reached out of bounds or we means we reached out of bounds or we reached water which is the base case reached water which is the base case right right so and we know in the base case we can so and we know in the base case we can return one because that means we reached return one because that means we reached the perimeter of our island right the perimeter of our island right and there's actually one other base case and there's actually one other base case so if the so if the position that we reach is in visit that position that we reach is in visit that means we're visiting means we're visiting a part of our island that we already a part of our island that we already visited before so that's visited before so that's the base case where we end up returning the base case where we end up returning zero because we can't zero because we can't you know add to our perimeter if we're you know add to our perimeter if we're visiting a visiting a island cell that we already visited island cell that we already visited before but before but if neither of these base cases is true if neither of these base cases is true that means we got to that means we got to a grid cell and we can start adding to a grid cell and we can start adding to the perimeter so the perimeter so basically we're going to go in all four basically we're going to go in all four directions right so the first direction directions right so the first direction is going to be i is the same and j is is going to be i is the same and j is added one right we're moving to the added one right we're moving to the right i think with that uh call and right i think with that uh call and we're going to we're going to basically call our depth first search basically call our depth first search four times one for each direction adding four times one for each direction adding to our perimeter each time so this to our perimeter each time so this direction is gonna be i plus one j stays direction is gonna be i plus one j stays the same the same and a couple more directions we also and a couple more directions we also need to subtract so need to subtract so this is i think gonna be the direction this is i think gonna be the direction to the left j to the left j subtracted by one and i subtracted by subtracted by one and i subtracted by one j stays the same so these are all one j stays the same so these are all four directions we've four directions we've totaled our perimeter now right with totaled our perimeter now right with well at least recursively right we see well at least recursively right we see depth for search we're making a depth for search we're making a recursive call and then all we need to recursive call and then all we need to do is return do is return that perimeter but actually one last that perimeter but actually one last thing i forgot is we need to make sure thing i forgot is we need to make sure to to add uh i and j to our visit add uh i and j to our visit set so visit set dot add set so visit set dot add i and j so that we don't end up visiting i and j so that we don't end up visiting i and j multiple times when we're making i and j multiple times when we're making this recursive call right we you see this recursive call right we you see we're making recursive calls we're making recursive calls we don't want to visit i and j multiple we don't want to visit i and j multiple times times so now that we've finished our debt for so now that we've finished our debt for search function the only thing left for search function the only thing left for us to do us to do is call that depth first search function is call that depth first search function right so on right so on i and j but the thing about our island i and j but the thing about our island is is part of it could be water and part of it part of it could be water and part of it could be land we need to find at least could be land we need to find at least one cell in our island that is land and one cell in our island that is land and we're guaranteed to have a cell like we're guaranteed to have a cell like that so we just need to find that so we just need to find it so we technically need to iterate it so we technically need to iterate over the entire over the entire uh or the entire grid potentially so uh or the entire grid potentially so let's do that so i and j basically we're let's do that so i and j basically we're iterating over the entire 2d grid iterating over the entire 2d grid and if we get to a position so if grid and if we get to a position so if grid of i and j is one or non-zero of i and j is one or non-zero right then we're going to call debt for right then we're going to call debt for search and we can return search and we can return the result of the debt first search and the result of the debt first search and you can see you can see that when we run this function it does that when we run this function it does work work and it's relatively efficient because and it's relatively efficient because this is a linear time algorithm this is a linear time algorithm linear meaning you see that we're only linear meaning you see that we're only going to visit going to visit each cell in our grid once and what's each cell in our grid once and what's the size of the grid it's going to be the size of the grid it's going to be n times m right because n is going to be n times m right because n is going to be the number of rows the number of rows m is going to be the number of columns m is going to be the number of columns this is going to be the size this is going to be the size of the grid we're only visiting each of the grid we're only visiting each position in the grid once or even twice position in the grid once or even twice but that's still going to be linear so but that's still going to be linear so the time complexity is going to be the time complexity is going to be big o of n times m big o of n times m so this is the time complexity this is a so this is the time complexity this is a linear function linear function but the memor the memory complexity is but the memor the memory complexity is also going to be the same also going to be the same n times m because you see we have a n times m because you see we have a visit set visit set right so potentially we might add every right so potentially we might add every single single position in the grid to our visit set position in the grid to our visit set that takes up extra memory so our memory that takes up extra memory so our memory and time complexity is going to be and time complexity is going to be this big o n times m so i hope that this this big o n times m so i hope that this was helpful was helpful if it was please like and subscribe it if it was please like and subscribe it supports the channel a lot and i'll supports the channel a lot and i'll hopefully see you pretty soon hopefully see you pretty soon you | 2024-03-18 10:47:12 | 463 | Island Perimeter - Graph - Leetcode 463 |
|
eVi4gDimCoo | hey guys what's up this is steve today let's go through another legal problem let's go through another legal problem 981 981 time based a key value stall let's take time based a key value stall let's take a look at the problem description first a look at the problem description first create a time-based keyword installed create a time-based keyword installed class time map class time map that supports two operations number one that supports two operations number one is set is set which takes three parameters key value which takes three parameters key value and timestamp and timestamp so this is kind of a mutation or so this is kind of a mutation or addition to a regular hash map which addition to a regular hash map which takes an takes an additional parameter which is timestamp additional parameter which is timestamp usually a hashmap or just a regular usually a hashmap or just a regular commonly seen map just takes two commonly seen map just takes two parameters one is key the at least value parameters one is key the at least value this one is just a this one is just a mutation third no number two mutation third no number two number two operation is get so gap number two operation is get so gap instead of just a regular instead of just a regular get method which takes one parameter get method which takes one parameter only which is the key only which is the key this one takes two the addition to this this one takes two the addition to this is a timestamp is a timestamp all right so let's take a look what the all right so let's take a look what the get get method requires it has three method requires it has three requirements number one requirements number one is returns a value such that set key is returns a value such that set key value timestamp value timestamp underscore previous was called underscore previous was called previously with the time previously with the time stamp underscore previous less than or stamp underscore previous less than or equal to timestamp equal to timestamp okay if it's not clear yet no worries okay if it's not clear yet no worries we'll go through one example then things we'll go through one example then things will be cleared will be cleared second requirement is that if there are second requirement is that if there are multiple such values it returns the one multiple such values it returns the one with the largest with the largest time stamp underscore previous so we're time stamp underscore previous so we're trying to find trying to find the most recent one if it's possible the most recent one if it's possible third is if there's no such values we third is if there's no such values we can return an can return an empty stream empty string here okay empty stream empty string here okay let's go through this one example let's go through this one example here's the input timestamp timestamp is here's the input timestamp timestamp is just just to initialize the constructor to call to initialize the constructor to call the constructor and initialize the the constructor and initialize the object object output is now which makes sense set set output is now which makes sense set set returns now right returns now right so set is always set written type is so set is always set written type is void so it doesn't return anything so void so it doesn't return anything so set set what do we set we said the key is full what do we set we said the key is full the value is bar the value is bar and timestamp is one so this is what we and timestamp is one so this is what we set set and then we call get we get foo and and then we call get we get foo and timestamp what timestamp what so we're going to get bar right this is so we're going to get bar right this is a perfect match a perfect match and then we can call get through time and then we can call get through time stamp three stamp three we call get foo foo is here timestamp we call get foo foo is here timestamp three three we don't have a timestamp three here the we don't have a timestamp three here the biggest one the most recent one the biggest one the most recent one the closest one that is up to three closest one that is up to three is one so we return bar here we return is one so we return bar here we return bar here as well bar here as well then we call set now we call set with then we call set now we call set with what because that with what because that with full it's still full and the bar full it's still full and the bar the value becomes bar two with the the value becomes bar two with the timestamp full timestamp full okay so here it doesn't necessarily mean okay so here it doesn't necessarily mean that the the key with the key that the the key with the key equals to full the timestamp is one equals to full the timestamp is one the value is part this entry doesn't the value is part this entry doesn't necessarily necessarily doesn't necessarily mean get removed doesn't necessarily mean get removed right right it's actually not it's just the meaning it's actually not it's just the meaning that we have a new entry that we have a new entry with a more recent timestamp matching to with a more recent timestamp matching to the the same key got added into this mutated same key got added into this mutated hashmap hashmap right so that is why when we call get right so that is why when we call get fu is key key is full and timestamp is 4 fu is key key is full and timestamp is 4 we're returning bar 2 here we're we're returning bar 2 here we're returning bar 2 here returning bar 2 here and then we when we call get full five and then we when we call get full five timestamp is five timestamp is five we're not returning bar anymore because we're not returning bar anymore because we have another timestamp which we have another timestamp which we have another entry with matching the we have another entry with matching the same key same key but with a more recent timestamp is four but with a more recent timestamp is four instead of one so when we turning this instead of one so when we turning this one we're returning one we're returning this one's value which is bar two here this one's value which is bar two here this is how this mutated hash map or this is how this mutated hash map or bitcoin time-based keyword install bitcoin time-based keyword install this is how it works if we can work this is how it works if we can work through a second example things will be through a second example things will be even more clear even more clear like say the input is the timestamp so like say the input is the timestamp so this is this is to initialize an object of this to initialize an object of this time-based key value style time-based key value style set so we set set what set set so we set set what set left this is the key and timestamp is 10 left this is the key and timestamp is 10 value is high and then we set again we value is high and then we set again we said left said left this is still the key the same key and this is still the key the same key and timestamp is 20. timestamp is 20. value is low so we set we set twice value is low so we set we set twice we set two entries in this we set two entries in this time based key value stall right we can time based key value stall right we can retrieve retrieve both 10 and 20. we can retrieve both both 10 and 20. we can retrieve both high and low you see high and low both high and low you see high and low both of them are retrieved of them are retrieved that means none of the entries based that means none of the entries based simply based on the keys are erased if simply based on the keys are erased if there is a more recent timestamp there is a more recent timestamp mapping to the same key comes in right mapping to the same key comes in right that's what it means and then we call that's what it means and then we call get one two three four five we call get one two three four five we call get five times so see here the first get get five times so see here the first get we call with we call with love the key is always love since we love the key is always love since we enter it only enter it only two left you can call whatever you want two left you can call whatever you want but it's not going to return anything but it's not going to return anything for the simplicity for the simplicity of this example it costs get five times of this example it costs get five times all with the all with the key equals to love and then with key equals to love and then with different timestamps different timestamps timestamp the first example timestamp is timestamp the first example timestamp is five five what are we going to get we're going to what are we going to get we're going to get nothing right it's an empty stream get nothing right it's an empty stream why is that because there is no such a why is that because there is no such a temp time step that is temp time step that is less than or equal to 5 right the less than or equal to 5 right the minimum is 10 minimum is 10 right so that's why it's returning empty right so that's why it's returning empty stream stream next we call getlove10 timestamp is 10. next we call getlove10 timestamp is 10. luckily we have one timestamp that luckily we have one timestamp that exactly matches 10 exactly matches 10 which is here that is why we're which is here that is why we're returning height and then returning height and then third time we call get we call get love third time we call get we call get love do we have a 15 time stamp in the do we have a 15 time stamp in the mutated hash map mutated hash map no we don't have it and then we try to no we don't have it and then we try to find find the last previous one that is the last previous one that is most closest to 15 which is what most closest to 15 which is what which is 10 right so we said we said 10 which is 10 right so we said we said 10 here we set timestamp 10 value to be here we set timestamp 10 value to be high high that is why this call will return high that is why this call will return high here here right i hope that makes sense and then right i hope that makes sense and then we call left still the same key we call left still the same key but timestamp is 20. so we have an exact but timestamp is 20. so we have an exact match so we just return no here match so we just return no here and then we call the same key key left and then we call the same key key left and then timestamp is 25. and then timestamp is 25. do we have a 25 timestamp in the in the do we have a 25 timestamp in the in the stall no we don't have it but the stall no we don't have it but the closest one that we have is a 20. closest one that we have is a 20. what does 20 have 20 maps too low that what does 20 have 20 maps too low that is why we're returning low here is why we're returning low here so the the idea that come to me is that so the the idea that come to me is that we can we can apparently we're going to use a map but apparently we're going to use a map but how can we have a one more dimension how can we have a one more dimension which is the time step which is the time step if we are simply using a regular hash if we are simply using a regular hash map the key map the key is just the key and the value is just is just the key and the value is just the value the value then how do we get control of the then how do we get control of the timestamp it's apparently one more timestamp it's apparently one more diagram diagram one more dimension in this hash map one more dimension in this hash map right right um there are multiple different ideas um there are multiple different ideas you can um you can um so basically you can have you can create so basically you can have you can create an object an object and then for the value of the hashmap and then for the value of the hashmap you can use that object this object only you can use that object this object only has two fields has two fields one is timestamp the other is the value one is timestamp the other is the value right you can do it that way right you can do it that way the problem that comes with that idea is the problem that comes with that idea is that you have to sort that you have to sort sort everything in that in the value set sort everything in that in the value set right based on the timestamp then you right based on the timestamp then you try of course you can do try of course you can do you can use a you can use a linked you can use a you can use a linked hashtag since the timestamp is hashtag since the timestamp is it is strictly increasing right it says it is strictly increasing right it says timestamp are strictly increasing timestamp are strictly increasing and then you can do a binary search that and then you can do a binary search that is one way is one way the more straightforward or the easier the more straightforward or the easier way for me way for me is i think we can use a tree tree map is i think we can use a tree tree map right we can use a tree map instead of right we can use a tree map instead of creating a customized object maybe you creating a customized object maybe you can do that can do that time and space complexity might not be time and space complexity might not be even worse to me i feel it's more concise that we can just use a tree map as the value as the type of the value of the mutated hashmap the key of the hashmap is still going to be the key it's still going to be the key and then the reason why we want to use a tree map is because for tree map all of the key set it's ordered by descent by natural order which in this case is what is exactly what we want right then first we'll call tree map get key and then we'll get a hash map inside this hash map the key is going to be the timestamp and it's in order so that we can very easily get whatever we need if it exists it's if it's if there's a perfect timestamp match we can just directly return otherwise we can call floor key which is going to find us the greatest the number that is less than or equal to the timestamp i hope that makes sense let me put the idea into the actual code hopefully that help that will help so here we'll have a map type is going to be stream and then the value type is going to be map then here what we'll have is integer and then string i'll just call it map so once we initialize this we can just call it hashmap all right what then we do set so first we want to check if map contains key this key if it doesn't or just initialize one put new tree map in here and then what we'll get is we'll get this right so we get this what do we get we get the one that we are going to get i need one more oops i need one more close parenthesis here and then oops this is wrong and i'll call it the time and i'll call it the time map for simplicity and then we'll get map for simplicity and then we'll get this this now we're set it time map now we're set it time map put time step and value put time step and value this is the sand method all all the way this is the sand method all all the way up to this point is very clear up to this point is very clear no any questions i don't believe so it's no any questions i don't believe so it's very straightforward right we can very straightforward right we can all that this class will have is just a all that this class will have is just a map the type of the map is a string and map the type of the map is a string and a a tree map all right and then we a little tree map all right and then we a little bit trick bit trick here in get is that we can call an api here in get is that we can call an api in tree set in tree set which is going to help us to get the which is going to help us to get the closest timestamp that is the small that closest timestamp that is the small that is is either smaller than or exactly equal to either smaller than or exactly equal to the timestamp the timestamp all right so first we'll have this i'll all right so first we'll have this i'll just call it time just call it time map again and then we'll call map map again and then we'll call map get key uh get key uh what if key doesn't exist uh let's not what if key doesn't exist uh let's not consider consider that do is there a constraint that do is there a constraint will be called this many times operation will be called this many times operation strictly increasing strictly increasing let's not consider keynote doesn't exist let's not consider keynote doesn't exist yet see if it can be accepted yet see if it can be accepted and then so what called previous and then so what called previous time time map time time map floor here so this floor here so this api is going to return us the number the api is going to return us the number the timestamp that is timestamp that is closest but still smaller than or equal closest but still smaller than or equal to this timestamp to this timestamp this is the beauty of using a tree map this is the beauty of using a tree map uh and then let's use integer uh and then let's use integer instead of into primitive type because instead of into primitive type because it's possible that it's possible that this one returns me and now if that is this one returns me and now if that is the case the case priv time equals now that means priv time equals now that means we don't have such a possibility we don't have such a possibility which is this one right which is in this which is this one right which is in this case it's written case it's written it's retaining an empty string which is it's retaining an empty string which is here here love the key does exist but the love the key does exist but the timestamp timestamp five there is no such a thing five there is no such a thing in the scheme a value like in the in the scheme a value like in the time-based key value stall time-based key value stall that is exactly smaller than or equal to that is exactly smaller than or equal to five five so we're returning empty string here so we're returning empty string here return empty string return empty string otherwise we'll just return otherwise we'll just return time map get time map get previous time all right and this is previous time all right and this is it let me hit the run code to see there it let me hit the run code to see there if there's any compile error if there's any compile error all right no compile error let me hit all right no compile error let me hit submit all right accept it as not super impressive in terms of time and memory um but it's fine or i guess there is no such a connotation that it's not all of the test cases are very valid it's not testing the counter case of whether the key exists in the key value stall or not 50 20. no big difference but anyway 50 20. no big difference but anyway here is the idea of how we can choose a here is the idea of how we can choose a combination of different data structures combination of different data structures of of existing diff different data structures existing diff different data structures do a combination of permutation to do a combination of permutation to whatever you want whatever you want to help solve the problem hashmap is a to help solve the problem hashmap is a very powerful very powerful and very mature non-existing data and very mature non-existing data structure feel free to use that to structure feel free to use that to the best of your knowledge um problems the best of your knowledge um problems like this may come in like this may come in in your real onsite or phone screens in your real onsite or phone screens which is very common which is very common so practice this hopefully this makes so practice this hopefully this makes sense sense if it does please do me a favor and if it does please do me a favor and gently tap the like button that's going gently tap the like button that's going to help a lot with the youtube algorithm to help a lot with the youtube algorithm and i really appreciate it and don't and i really appreciate it and don't forget to subscribe to my youtube forget to subscribe to my youtube channel as i have accumulated channel as i have accumulated a lot of different data structure a lot of different data structure algorithms computer science or algorithms computer science or interview or amazon web services interview or amazon web services certification exam tutorials certification exam tutorials hopefully i'll just see you guys in just hopefully i'll just see you guys in just a few short seconds in my other videos a few short seconds in my other videos thank you very much for watching i'll thank you very much for watching i'll see you guys in the next one | 2024-03-25 14:24:53 | 981 | LeetCode 981. Time Based Key-Value Store - Interview Prep Ep 107 |
|
PgQvXg4YOKg | hey hey everybody this is Larry this is day 27 of the legal daily Challenger day 27 of the legal daily Challenger Tuesday hit the like button hit the Tuesday hit the like button hit the Subscribe button join me on Discord let Subscribe button join me on Discord let me know what you think about today's me know what you think about today's forum and yeah in the video and so forth forum and yeah in the video and so forth um hope y'all are having a okay week and um hope y'all are having a okay week and excellent week whatever you like excellent week whatever you like um yeah end of September a couple of um yeah end of September a couple of days left let's get them let's go go go days left let's get them let's go go go go go go uh push Domino's 838 replace each Domino vertically upright and we sometimes we push some damage left or the right uh okay so then we'll go to do it stays upright okay so the left pushes the one next to one on the left okay so what does this mean this one means wait didn't draw they drew one for example two but not one okay fine uh so okay so I see so that that is a domino and L push forces as an L um and then that if it's not pushed or if it's how do I in let me I'm just reading the how do I in let me I'm just reading the output and kind of mapping it to here output and kind of mapping it to here um okay so the third one is still um okay so the third one is still because they didn't move but and this because they didn't move but and this other one is still because just left and other one is still because just left and right okay I mean right okay I mean um so you can phrase it um and it is just that whether a domino is closer to a left or closer to the right um of course if you're doing naively it is going to be n Square so let's not do that let's uh let's actually pre-calculate the courses left and of course is right and oh yeah uh or how and I'll be more precise um left from the right side and right from the left side right so yeah yeah and basically what we want to do is yeah and basically what we want to do is um okay so let's take we have um okay so let's take we have n is equal to length of dominoes n is equal to length of dominoes um then left is equal to say um then left is equal to say [Music] [Music] um let's say infinity right Infinity um let's say infinity right Infinity times n and now we said Infinity is times n and now we said Infinity is equal to 10 to 20 Works mostly for me equal to 10 to 20 Works mostly for me and then now we go from right to left and then now we go from right to left because we're going to see the closest because we're going to see the closest um foreign to the from right to left and this is actually similar to what is it diff or the the acute degree of the contest if you did that one where you know you just pre-calculate you know the closest one maybe I would miss remember that one though something similar to that in any case so yeah so um L then left of I is equal to zero um L then left of I is equal to zero otherwise F of I is equal to the left of otherwise F of I is equal to the left of I uh plus one plus one right something I uh plus one plus one right something like that like that um um yeah I mean it's a little bit awkward yeah I mean it's a little bit awkward because just because this is uh uh I plus one you know I plus one has to be less than n or something like this because otherwise then this is just we'll just keep it at Infinity I think that's okay it's a little bit awkward but it's a little bit okay um yeah and maybe the question is can we generalize this uh yes a little bit so let me rewrite this actually um let's go from left to right just to make it simplify a little bit um okay and then now we can just write it more naturally but it's like harder to make mistakes maybe so with dominoes is dominance of I is equal to Y then we set dominance of I is equal to Y then we set rate of I is equal to zero right else rate of I is equal to zero right else if I guess oh Sif if I guess oh Sif um um I minus 1 is greater than zero then I minus 1 is greater than zero then writes up writes up I is equal to Y sub I minus one plus one I is equal to Y sub I minus one plus one right and of course this can go over right and of course this can go over infinity per se but that's fine and the infinity per se but that's fine and the reason why I kind of delete data piece reason why I kind of delete data piece and quote it this way and so then now we and quote it this way and so then now we can abstract it a little bit can abstract it a little bit um so then we can go left uh uh closest um so then we can go left uh uh closest maybe something like this maybe something like this um and then you have a an array which is um and then you have a an array which is called Domino's and called Domino's and um a direction say right um a direction say right someone like this and someone like this and you know and and is still do um yeah and then here we just set it the direction right and then now we can say right as you go to closest uh Dominos um and right and then now left is equal um and right and then now left is equal to cosist to cosist of dominoes in Reverse left and then of of dominoes in Reverse left and then of course we reverse the answer anyway course we reverse the answer anyway um okay so then now we have left and um okay so then now we have left and right and and we are able to do the right and and we are able to do the abstraction in a very quick way and yeah abstraction in a very quick way and yeah and also of course if you're doing uh and also of course if you're doing uh tdd or just like testing which you tdd or just like testing which you should uh you could also just test this should uh you could also just test this now and that makes it easier to kind of now and that makes it easier to kind of you know yeah just you know yeah just makes it easier to do it um except I'm makes it easier to do it um except I'm one because I forgot to return the right one because I forgot to return the right okay fine but yeah okay fine but yeah and then now we can just do for eye in and then now we can just do for eye in range of range of and and um we also want to I think the one thing um we also want to I think the one thing that we might be have to be a little bit that we might be have to be a little bit careful with is just Infinity values so careful with is just Infinity values so we can do something like left of Pi if we can do something like left of Pi if you go to Min of infinity left of I you go to Min of infinity left of I um just I mean maybe you could handle it um just I mean maybe you could handle it earlier as well to be honest but I'm earlier as well to be honest but I'm just going to do it this way just to be just going to do it this way just to be a little bit queer and then here we go a little bit queer and then here we go if left of I uh well let's say we have if left of I uh well let's say we have an answer away right um I like using none because if you forgot to throw something in you'll see it on the X on the output versus like if you have a default value I mean maybe it'll give you a good answer but on the debugging it may mess you up a little bit I mean this one is easier to see I think so basically well first of all we want so basically well first of all we want to set a and sub I is equal to to set a and sub I is equal to abdominals of I right I guess it doesn't really matter because if this is zero then it'll just be that one anyway right so we'll do now we want to call someone if this is less than y sub I then answers of I is equal to left else or else if left sub I is greater than y sub I and sub I is equal to R else and oops why did that okay I don't know is it going to period right um do we want in a string okay we do one in a string so then we just return you know we join into a string that's pretty much it this is going to be linear time linear space hopefully it's also right it doesn't matter what it is if it's not right I see hmm I forgot a case or maybe I'm just really wrong oh yeah I [Music] saying that um just left I actually have saying that um just left I actually have done about this case but then I I was done about this case but then I I was too too slow to kind of remember it too too slow to kind of remember it while I was typing this out while I was typing this out excuse me but uh but yeah we also need excuse me but uh but yeah we also need to reset that's all I forgot to reset to reset that's all I forgot to reset that's why but that's the good thing that's why but that's the good thing about this abstraction is you only have about this abstraction is you only have to correct the code in one place so here to correct the code in one place so here um if this is your direction we actually um if this is your direction we actually you know want to set this you know want to set this um I think um I think else if Domino's of i as you go to else if Domino's of i as you go to period that um period that um then we I guess do this actually do this then we I guess do this actually do this thing and then else if this is the opposite direction then we actually want to set just as you go to Infinity again okay there we go so yeah so I think that okay there we go so yeah so I think that was a a a misfortune if you say uh was a a a misfortune if you say uh mistake a typo more than a typo just mistake a typo more than a typo just forgot uh to be honest but as you can forgot uh to be honest but as you can see that's the beauty of abstraction see that's the beauty of abstraction right is that because of this we fix it right is that because of this we fix it by fixing one place and we don't have to by fixing one place and we don't have to do in two places even this to be honest do in two places even this to be honest we can fix it in one place right we can we can fix it in one place right we can just be like uh and then now we just be like uh and then now we we could get rid of it in two places we could get rid of it in two places right right um um so yeah hopefully this is actually right so yeah hopefully this is actually right a device then it doesn't matter how a device then it doesn't matter how pretty the code is if it's wrong right pretty the code is if it's wrong right let's give it submit this is going to be let's give it submit this is going to be linear time in your space hopefully it's linear time in your space hopefully it's also right uh yeah well I don't know why also right uh yeah well I don't know why this is so much slower okay uh yeah 910 this is so much slower okay uh yeah 910 day streak so that's kind of nice why is day streak so that's kind of nice why is this type slow this is linear so I mean this type slow this is linear so I mean I guess we do a little bit more linear I guess we do a little bit more linear than we can I think that is one thing is than we can I think that is one thing is that if you do it if you buy two for that if you do it if you buy two for Loops like this way Loops like this way um it is a little bit faster only um it is a little bit faster only because because you know you're not doing two reverses you know you're not doing two reverses but but um especially if you're you know writing um especially if you're you know writing in the contest situation in the contest situation um you know you just want to um you know you just want to write them as fast as possible that set write them as fast as possible that set obviously there is obviously there is especially lead code is a little bit especially lead code is a little bit awkward because sometimes you do want to awkward because sometimes you do want to have time and one out of space and all have time and one out of space and all this stuff so I don't know uh okay cool this stuff so I don't know uh okay cool that's pretty much all I have for this that's pretty much all I have for this one let me know what you think line your one let me know what you think line your time in your space I think I don't have time in your space I think I don't have to explain that deeply into this one to explain that deeply into this one you've never did a little bit more you've never did a little bit more linear time and space linear time and space constant but yeah uh that's what I have constant but yeah uh that's what I have so stay good stay healthy to good mental so stay good stay healthy to good mental health I'll see y'all later and take health I'll see y'all later and take care bye | 2024-03-22 15:12:42 | 838 | 838. Push Dominoes - Day 27/30 Leetcode September Challenge |
|
RStZpY4ofv0 | hey hello there so today's the binary search question that I picked as the search question that I picked as the city for fine first and last position of city for fine first and last position of element in sorted array the question is element in sorted array the question is just as follows we have a sorted integer just as follows we have a sorted integer arrays and we want to find the starting arrays and we want to find the starting and ending position of a given target and ending position of a given target value the algorithm has to be in log in value the algorithm has to be in log in time so we apply binary search twice time so we apply binary search twice first to the first time to find the first to the first time to find the first position for the element the first position for the element the second time to find the last position of second time to find the last position of the element yeah so that's pretty much the element yeah so that's pretty much how to solve this in log in time I use how to solve this in log in time I use in binary search twice and two days ago in binary search twice and two days ago I was doing a little bit review so in my I was doing a little bit review so in my documents I was I have the template for documents I was I have the template for search leftmost and search rightmost I search leftmost and search rightmost I think the code has to be modified a think the code has to be modified a little bit from my last time the upper little bit from my last time the upper bound opposed originally said this to be bound opposed originally said this to be the size of the race abstract by one the size of the race abstract by one you know points to the array loss the you know points to the array loss the location that will actually cause location that will actually cause problems so after some analysis and very problems so after some analysis and very fun debugging when I try to just copy fun debugging when I try to just copy and pasting those two pieces of code and pasting those two pieces of code here and keep saying arrow arrow find here and keep saying arrow arrow find that I should actually increase the that I should actually increase the upper bound to be the full size of the upper bound to be the full size of the Ring so yeah just as a real force off Ring so yeah just as a real force off the memory I should try this one more the memory I should try this one more time with another language I guess so time with another language I guess so we're gonna have two methods one is we're gonna have two methods one is called binary search left which is going called binary search left which is going to take a reference to this vector and a to take a reference to this vector and a integer target what this does is to integer target what this does is to apply binary search to find the left apply binary search to find the left hand most occurrence position for this hand most occurrence position for this target value so initially the lower target value so initially the lower bound is 0 the upper bond is the array bound is 0 the upper bond is the array size it's not the array size subtracted size it's not the array size subtracted by 1 so the condition is same thing and by 1 so the condition is same thing and we are checking that if we are search we are checking that if we are search for the left we want the left and most for the left we want the left and most so what we want is that the the middle so what we want is that the the middle element we are looking at is less than element we are looking at is less than strictly less than the target so that strictly less than the target so that when we you know keep searching the when we you know keep searching the value that we find is going to be the value that we find is going to be the first one that's actually equal to or first one that's actually equal to or larger than the talked about you that's larger than the talked about you that's pretty much the binary search left the pretty much the binary search left the binary search right it's almost binary search right it's almost identical except that that we change identical except that that we change this condition to be less than or equal this condition to be less than or equal to so the left the one when it's you to so the left the one when it's you know finally equal to the height the know finally equal to the height the search space pinned down to one number search space pinned down to one number that's going to be the first number that's going to be the first number that's largely larger than that's largely larger than so as a result in this right code we so as a result in this right code we return Aleph to substract by one so use return Aleph to substract by one so use this two sub routines to solve this this two sub routines to solve this problem we're basically just gonna grab problem we're basically just gonna grab try to apply this on this array with the try to apply this on this array with the target value and do that for the right target value and do that for the right as well and then we pretty much just as well and then we pretty much just going to return the pal that was on going to return the pal that was on caveat to that we need to check the case caveat to that we need to check the case where we have negative on negative 1 where we have negative on negative 1 that's when actually the right is sorry that's when actually the right is sorry what what's happening hope my code is what what's happening hope my code is saved saved ok so that's when the ok so that's when the [Music] feels very tricky why that just happened yeah we wanted the right to be larger than or equal to L if that's the case then we can safely return this pal otherwise it will be negative or negative on the case will we not be able to find a target if that's the case then I'll and right the left and right the right is actually going to be smaller than L it can look at the code and reason about that yeah so pretty much that's just the code the binary search left and right the only difference is this equal sign and the return L minus 1 in the right version is the left version just strictly less than so that we always want to bump L to be at least target you at least equal to the target it would be the first one that equal to the target this one I will end up with the first one that's larger than target so we return negative 1 to be the last one that equal to the target if if it does exist and here we just have a little condition checking here to make sure that we don't return something that's that's funny you know if it's the case that we would likely to return funny that's because the number is not in there so we return negative 1 negative 1 yeah or or there could potentially be another case is that the array just have one number this will be catched in this condition check in here and we're returning negative 1 negative 1 as a result so I think this is the code I No initializer list cannot used on right can I just yeah yeah it works so this is can I just yeah yeah it works so this is the binary search code to solve this the binary search code to solve this question one to the left one to the question one to the left one to the right | 2024-03-20 08:48:01 | 34 | Leetcode 34 Find First and Last Position of Element in Sorted Array |
|
HinLw7adoH8 | hey what's up guys this is chung here again again so this time lead code number 1947 so this time lead code number 1947 maximum compatibility score sum maximum compatibility score sum okay so now this time we have a survey okay so now this time we have a survey that consists of n questions that consists of n questions right where each question's answer is right where each question's answer is either zero or one either zero or one okay and then the survey was given to m okay and then the survey was given to m students students right from zero to n minus one and also right from zero to n minus one and also same m mentors also numbered from zero same m mentors also numbered from zero to m to to m to m minus one basically each of m minus one basically each of students and mentors will answer often students and mentors will answer often questions questions okay and then the student's eye okay and then the student's eye is a list of integers which contains is a list of integers which contains all the answers of un questions for the all the answers of un questions for the student student same thing for the mentors right and and then basically each student will be assigned to one mentor and each mentor will have one student assigned to them right so basically one-to-one relations and and then there's like compatibility score of a student and the mentor pair is the number of the answers are the same for the book for the for the both for both the student and the mentor right for example if student answer is one zero one it means that for for answers for question zero student answer is one for for ounce for question one student answer is is zero two for two is one and the mentors answer zero zero one right similarly for for question zero one and two and the compatibility score obviously is two because only two of them are the same right and then our our task is to find the optimal student mentor pair to maximize the sum of the compatibility score right and we just need to return that compatibility score right so for example so we have three students and we have three mentors and when there are like also three questions in total right so the optimal uh the optimal uh pairing will be like this right where the final answer is eight okay and for this one it's like zero zero right so that's it and then the constraint is like this right i mean m and n is also only like eight right so you know every time when you guys say the constraints it's like only this like maybe smaller than 10 then it means that you know probably the time complexity will be like 2 to the power of 10 or 8 which means it's going to be a a full permutation right so that and that's exactly what we were going to do for this problem because there's no greedy way to optimally assign the method to any student so which means we have to try all the possible combinations for each student against against each mentor right basically what does it mean means that for student 0 we're going to try to assign a mentor from 0 to m minus 1 to the student to still than 0 and then for still the one we're going to try the same thing but we have to do like in the in the back tracking manner right because once the mender is gone we cannot assign this mentor to the other student that's why you know this is actually a common strategy for like a bit mask right where you know we're gonna have like a dfs okay we're gonna have like dfs where the uh the so the first uh uh the so the first uh parameter is gonna be the i i means parameter is gonna be the i i means basically basically now we are assigning the the mentor for now we are assigning the the mentor for the current uh student okay and the second one is going to be the mat the bit mask right so the bitmask is still is what is the uh is the status of the after all the mentors right basically zero means it has not been assigned one means it's already been assigned let's say we have a zero one zero zero one zero right then it means that okay we have assigned this mentor and this mentor which means only the zero ones can be used at this moment right and with this one right this two here we can basically we can try all the and then the last one of course is going and then the last one of course is going to be the score right right we're going to also maintain the current score for each of the pair and in the end we just we just maintain uh update update the final answer right uh whenever we have a sign uh each student visits corresponding mentor right and then we simply update the score right uh to find the maximum one so that's it right and pretty straightforward and let's do it then um i'm going to call it backtrack right so like i said the first i mask and score right and so if i is equal to m okay we haven't defined the m and n yet so m is going to be the length of student right basically the same also for the mentors and n is the number of questions going to be a number of uh do we need this n here probably we don't we don't even need this n okay oh no i think so that's the number of questions right so that's the number of questions right number of number of questions okay and then for the back tracking right so when when i reached the end then we know okay we have assigned all each mentor with each student with this mentor that's that's when we need we can update the answer right so let's do this now look answer right and the answer is the max um yeah and then we return right and then for j in range of m right so basically for the current student try to assign all try to assign all available mentors available mentors right to student right to student high right and we have in total we have high right and we have in total we have j j uh we have m mentors we just need to uh we have m mentors we just need to check if the mandate is available right check if the mandate is available right so basically the mask so basically the mask we check if that the mask value is uh we check if that the mask value is uh it's zero okay this one equals to zero it's zero okay this one equals to zero right it's a little bit uh bit right it's a little bit uh bit manipulation here right manipulation here right then we do backtrack right back track of then we do backtrack right back track of what backtrack of i what backtrack of i plus 1 right and then for mask it's plus 1 right and then for mask it's going to be the mask going to be the mask we're going to mark that mentor to be we're going to mark that mentor to be unavailable which means we're going to unavailable which means we're going to mark that one mark that one two into one right that's how we market two into one right that's how we market it into one it into one and then and then the score right so the score score plus score plus uh okay well yeah we need to have uh okay well yeah we need to have another helper functions to another helper functions to get the score right so we have student and we have the mentor right so answer is going to be 0 and for i in range of of n this time right so if s i is equal to m i then answer plus one okay return the answer right so here we think we can simply just call that helper function of students of of j okay yeah so that i think that's it right and then we can do a backtrack of zero zero zero okay right and then yep oh here oh right here so all right cool so it works right because all right cool so it works right because it can pass because of time complexity it can pass because of time complexity for this one is what um so we have i here right so i is like we have n right n times 2 to the power of of n right and then for each of them we have like what each of here we have oh then this is going to be another times for this one and times oh we have m m and i'm sorry so the i is m right the mask is so is 2 to the power of m and then inside here we have a and then here is another it's another n and then here is another it's another n right right this one is it's a of n here is o of m this one is it's a of n here is o of m right so that's the total time right so that's the total time complexity i think complexity i think right and so for this one do we need the right and so for this one do we need the dp here dp here uh to memorize the the the result you uh to memorize the the the result you know probably not know probably not um because you know i don't think there's any overlapped uh subs uh scenarios here because we have given because the i always i always moving forward right and every time is moving forward you know the state will be different so basically they will do we don't need to store we don't need to use like dp to store any of the previously calculated results because the eye is yeah i think this is one way of doing it yeah i think this is one way of doing it and the other one is what i think the and the other one is what i think the other one is other one is we can do a maximum at the beginning we can do a maximum at the beginning instead of instead of updating this one to the end so what i mean is that you know so for this one you know i'm passing this score along the way to the end to update the final answer right or we can what we can always we can return this this score all the way to the top to update the uh the answer so that we don't have to pass this one lot in the back tracking so this is what i mean um so here uh we don't need the score anymore right so instead whenever we reach the end we simply return to zero it means that we don't have any score that we can collect right and then here we have answer dot zero right and here uh we don't need this one anymore it's gonna be so something like this it's gonna be answer equals the max here we have this and then we don't need here we have this and then we don't need a score here a score here right it's going to be the mask and all we plus right this one and then grab score plus the backtracking right so this one is this this okay right and then we simply return the okay right and then we simply return the uh uh the answer in the end right that's the answer in the end right that's another way of solving this problem another way of solving this problem instead of passing the score along with instead of passing the score along with it we simply just accumulating it we simply just accumulating the the the score up right we pop it the the the score up right we pop it we ma we bubble it up to the very top we ma we bubble it up to the very top and then every time we and then every time we do a maximum of that so this one is a do a maximum of that so this one is a pretty this is pretty this is like a very standard uh classic dp like a very standard uh classic dp template right so if i run this one i template right so if i run this one i believe this should also work believe this should also work oops oh so and then we can simply return the back the back track right okay if i run this one this would yeah right so same similarly yeah right so same similarly and this one i know with this one you and this one i know with this one you know we can definitely use like a know we can definitely use like a memorization memorization in python right it's going to be a lru in python right it's going to be a lru cache right none right so this is like cache right none right so this is like very standard dp solution right with very standard dp solution right with like two like two uh two-dimensional dp right so if i run uh two-dimensional dp right so if i run this one this should also work oh i think i'm i was wrong about the i was i was wrong about the the scenario the branches analysis the scenario the branches analysis okay yeah i thought there wouldn't be any uh there wouldn't be any uh duplicated scenarios but given the uh the run time seems like the dp one definitely runs much faster than the non memor let me think oh i see why because okay i let me think oh i see why because okay i think i was totally wrong yeah sorry think i was totally wrong yeah sorry because when uh you know if the i you because when uh you know if the i you know know if the first person if the first person uh if per first person picked a mentor uh one and second student picked mentor zero right or if the per or if the first person a student picked picked mentor mentor zero and the second student pair is the mentor one then the end result of this i will be the same right basically and then when we add like when we are reaching the the person to here uh sorry the student two here you know we will end up with the same mask right basically basically both the first mentor and the second mentor will be has already been uh un uh used right so which means that no basically yeah you're i i was wrong about that so we should definitely use dp uh the memorization version of the this backtracking actually it's not a backtracking that i should call it dp here instead you know but but it did it it does have some backtracking mechanism uh concept in here right so this one should like call dp uh because you know like i said you know both of the this uh both this uh this branch and this branch will end up with the same state here right that's why you know we need to we should we should memorize this the result for this state so that you know when the second branch reaches the state it can simply return the value right that's why you know okay correction we should step for this one we should definitely use this kind of dp dp uh version right because you know like i said so for this one though the time complex they will be correct like like the one i said is going to be m times uh 2 to the power out of m right and then for here it's going to be a m times n right so this is going to be a time complexity this is the one with with the uh the memorization because you know i think the time complies complexity analysis for the previous one was not accurate because they could be duplicated or the duplicated branch yep i think that's it right i mean i know the uh this video is a little bit confusing because uh because of my mistake at the very beginning i thought uh we don't need to use dp to solve this problem but you know turns out we should use dp instead and yeah i think other than that it's like a if we now now i got to think about it this is a very like not another very classic uh dp template where it's a 2d dp state where the first one is the index second one is the beat mask right and then yep i think that's it and thank you for watching this video guys and stay tuned | 2024-03-25 13:38:41 | 1,947 | LeetCode 1947. Maximum Compatibility Score Sum |
|
Rg95a4-hhs0 | at all so today continuing on this be weekly contest 15 the third the problem weekly contest 15 the third the problem iterator for combinations so let's see iterator for combinations so let's see what the problem asks us to do so what the problem asks us to do so it's 1286 iterator for combination and it's 1286 iterator for combination and the problem says we we want to design an the problem says we we want to design an iterator class that has three things a iterator class that has three things a constructor so iterators usually have constructor so iterators usually have just the constructor next method and has just the constructor next method and has next and in this method the constructor next and in this method the constructor constructor has two parameters a string constructor has two parameters a string of characters that are sorted in of characters that are sorted in distinct lowercase English or sorted distinct lowercase English or sorted order they are distinct and they are order they are distinct and they are lowercase English letters and we have a lowercase English letters and we have a number combination length also as an number combination length also as an argument and two other functions next argument and two other functions next the written the next combination of the written the next combination of specific length combination length and specific length combination length and hasnext which returns true if and only hasnext which returns true if and only if there exists an X combination right if there exists an X combination right and so we wanna what we want to do here and so we wanna what we want to do here is we want to create an iterator that is we want to create an iterator that for ABC gives us a b a c and b c and so for ABC gives us a b a c and b c and so you can see here it gives us a B BC and you can see here it gives us a B BC and AC so you could see it gives us the AC so you could see it gives us the combinations in order right there is no combinations in order right there is no C a right because that's not in the C a right because that's not in the right order right and so how can we how right order right and so how can we how can we implement something like this so can we implement something like this so right away combinations here it's it right away combinations here it's it already tells us if they're in iterator already tells us if they're in iterator for combinations and that's exactly what for combinations and that's exactly what it was um and what I well asks us to do it was um and what I well asks us to do so right away we should think about so right away we should think about creating combinations right because if creating combinations right because if you look here the characters length is you look here the characters length is 15 right but the problem is that next 15 right but the problem is that next and has next may be called 10 to the and has next may be called 10 to the power of 4 times so next and has next power of 4 times so next and has next needs to be really efficient but the needs to be really efficient but the constructor initialization can be a constructor initialization can be a liberating it can take a little bit more liberating it can take a little bit more time right and so for to get a time right and so for to get a combinations we can just combinations we can just is backtracking that the permutations in is backtracking that the permutations in combinations and these kind of things combinations and these kind of things that generate a list of choices we we that generate a list of choices we we can use backtracking to solve that so can use backtracking to solve that so let's see how comes solve this problem let's see how comes solve this problem so as we said we as we will use so as we said we as we will use backtracking to solve this problem and backtracking to solve this problem and then I have a video I will put in the then I have a video I will put in the description that explains in details how description that explains in details how you can kind of a blueprint to solve you can kind of a blueprint to solve backtracking problems and that's what I backtracking problems and that's what I will be using here and for backtracking will be using here and for backtracking essentially what that video says is that essentially what that video says is that you need to find when like what is the you need to find when like what is the partial solution that that you will pass partial solution that that you will pass around in your recursive function for around in your recursive function for backtracking and we need to find well backtracking and we need to find well when when when does that back when does when when when does that back when does that partial solution becomes a solution that partial solution becomes a solution is the solution how can you know that is the solution how can you know that it's a solution so that you can just it's a solution so that you can just process it and then what does processing process it and then what does processing the solution look like and then at each the solution look like and then at each point of of salt like at each partial point of of salt like at each partial solution what are the candidates that solution what are the candidates that you can go to next and if you can come you can go to next and if you can come up with all of this then maybe you could up with all of this then maybe you could add some pruning for your backtracking add some pruning for your backtracking solution but essentially these are the solution but essentially these are the main steps and so what is our partial main steps and so what is our partial solution here so what we want is solution here so what we want is generate combinations of characters so generate combinations of characters so for ABC want to generate combinations of for ABC want to generate combinations of lengths let's say two that's what the lengths let's say two that's what the example says so what do we need to do so example says so what do we need to do so to generate combinations of length two to generate combinations of length two of ABC well starts with a and so start of ABC well starts with a and so start with a first and then add to it the next with a first and then add to it the next character a B or skip B and then do C so character a B or skip B and then do C so AC and then we also have BC okay but I want to do them in order oh sorry here pick B and then pick a her you have to pick the next one you can't pick the one before that's the difference with permutation and so we can only pick BC so this is the that list that we have right and so with the order you could see is a B first and then a C second and then three BC right and so here for the order thing that means that in our combinations must let's say we are at a position I and then when we move we can only move to the positions after it so our or Lascars position index so our for loop for the index in characters well it would be in the range starting from the position itself so that we can get that character and then you only move to the next you don't go backwards because we want only those in order right and so already we know that we need we need to know what is our character partial solution so that we can append B to it so we need the s which is string so far right and we need the index in the current we need to know two things actually we need to know the index in the current character set right so index and this is index in current character set and we need to know also the index in the combination itself like this a is index zero this B is index one so that we can know when we have a solution is when the length is equal to the length of the combination that we are asking we can also do length of s right actually let's do that so that we can reduce the state for ourselves but essentially this is all we need we need to know the index in the current characters so that we can only go so that we can process them in order and we need to know what s is and one do we have a solution well we have a solution when the length of s is equal to the combination length that the problem asks us to to follow right in this case when the length of the string is equal to 2 what is the plot processing a solution so the problem asks us to return every time when we call next we want to return the next the next combination right so we could either have a list add them to a list and every time keep keep track of the index so that every time we return the next in the order or the other thing we can do since next once you move next you can't move back so we don't need to keep track of the previous element we can just use queue and when we are asking next we can just pop the element I returned it and so here our processing can be we initialize in the constructor initializes a queue right first we initialize a queue and then here we can just pop from the front the here we can just sorry add add to the add to the back of the list because the order has to be a B first AC first BC first so BC has to be in the backup of the list so we append to the cube the the s the string right and then when we want to in the house in the next call we can just call Q dot pop left that will give us the front which means it will give us a B first and an AC and NB C now processing the candidates we said we have this for loop right so that we can get the right order so here that means we need to do a for I in the range of to get the next candidate character than we need to append and so index and then length of chars and what do we need to do we need to call our backtracking function again let's call it helper our backtracking function here so we need to call helper well the new string which is the partial state we just chose this I to be added to it so we do Charles of I and then what is the index of the next character to go to what we have to in advance the index by one so that we don't repeat the character itself multiple times so index plus one and that's pretty much it that's all our backtracking solution needs so now let's try to cut it so let's just try to cut this generate portion the other thing the other portion is really easy to do we'll do it only code but the the complete backtracking function for generating combinations in this case is well we will need to define our helper function that gets passed it s which is the partial solution and the current index in the character set and we check if the partial solution became is a solution right now so we check if the length of s is equal to the combination length then at that point we can just append it to the Q so the Q would be a that append s right and then after that that append s right and then after that we go through the candidates right we go we go through the candidates right we go through the candidates so for I in range through the candidates so for I in range of index and length of character we of index and length of character we called the function again and now since called the function again and now since we chose the character position I will we chose the character position I will do s plus and we need to go to the next do s plus and we need to go to the next next position in car cars and so I plus next position in car cars and so I plus one right and then in the next call we one right and then in the next call we will skip the the one in at position will skip the the one in at position index and world pass in the wallet in index and world pass in the wallet in this index plus one which is in this this index plus one which is in this case it will be doing AC right and case it will be doing AC right and that's pretty much it now let's just that's pretty much it now let's just take this cuddle up with the full take this cuddle up with the full solution for the combination iterator solution for the combination iterator okay so now let's call this solution up okay so now let's call this solution up so we already know the our generate so we already know the our generate function that we need to do but here function that we need to do but here what keep track of the characters we what keep track of the characters we have that were passed as parameters and have that were passed as parameters and the Skip track of the combination line and we will need to also have it define out our queue that will put elements end so collection is that thank you and want me to enforce collections here and then we will need to do general do the helper function with backtracking so that we can fill the queue with the all the combinations possible right and so that will be as we said the partial state s or the partial solution and then the in the current index that we are at in the character set and so we define that function partial solution and the current index and then we check if the length of if we have a solution so the length of s equal to if it is then we add to the queue we process of the solution which is just adding it to the queue here otherwise we all say return here we go through the candidates States so in generate in helper of no sorry in the range of index so we want to go from the count index all the way to the end because we want them in order length of characters and then we call a helper function again for the next state here and so that would be S Plus what the character that we chose and then and then the index of the next character to choose which is just I plus 1 sorry and that's pretty much it and for the next function while we could just as we said cut from the key word since part from the front of the queue since the the smallest combination we would be would have been added first so it would be at the front of the queue and so to part it off we do pop left but the problem is this will give us well let's see first of all this will give us and then if it's wrong we will it's part if it definitely is wrong we'll fix it so that we can see the error and then here we'll just check that soft queue is not empty so we could do it by checking that let's say the length is bigger than 0 this will check that it's not empty but we could also just convert this to a pool and it will be true if the list is not empty and it will be false if the list is empty that's something in Python um mmm this is soft target okay so actually it's pretty good it's already passes because we just added it okay so this solution passes yeah okay so this solution passes yeah so that's Co the other way we can use so that's Co the other way we can use this is a sterile I used like a function this is a sterile I used like a function here to generate because it's good to here to generate because it's good to get some practice with backtracking and get some practice with backtracking and in an interview also probably they won't in an interview also probably they won't let us use a library to do this but in let us use a library to do this but in Python there is this library called Python there is this library called import tool ETF tools import tool ETF tools sorry called it a tools that has this sorry called it a tools that has this function called combinations where you function called combinations where you could give it an iterable an iterable an could give it an iterable an iterable an iterable so it can be even a list of iterable so it can be even a list of characters and the length of the characters and the length of the combination that you want and it will combination that you want and it will generate the combinations for you in the generate the combinations for you in the right order so essentially it will be right order so essentially it will be doing this helper thing for us so if I doing this helper thing for us so if I use the example that we have ABC 2 and use the example that we have ABC 2 and just convert it to a list you could see just convert it to a list you could see it give us pairs of them and so we could it give us pairs of them and so we could just join this and get the list that we just join this and get the list that we want so we can just join X here and that want so we can just join X here and that will give us the strings that the will give us the strings that the combinations that we use to help us to combinations that we use to help us to generate and so instead of generating it generate and so instead of generating it ourselves we could just do this so Q ourselves we could just do this so Q would be equal to so we could just pass would be equal to so we could just pass or we could actually for our Q here just or we could actually for our Q here just passed since for a Q if we look at two passed since for a Q if we look at two important collections again so DQ also important collections again so DQ also accept accept I think it's accepts and iterables is I think it's accepts and iterables is just passed to the Q here just passed to the Q here now this passed with the iterator now this passed with the iterator combinations right and so here it would combinations right and so here it would be the characters like be the characters like and then the combination looks like so and then the combination looks like so that this and we don't need to define that this and we don't need to define this function here the only thing we this function here the only thing we need is because the combinations returns need is because the combinations returns to us a pair here one would pop the to us a pair here one would pop the first one we need to join them so that first one we need to join them so that we can give what the method expects back we can give what the method expects back right and that's pretty much it and the other solution of course is tonight's now use a queue and then just keep track of the index and increment us yourselves yourself and that's also valid yeah so we just want a fast way really I know of one way to get the next and the has next one that's all that matters really and so let's submit this okay so this also passes yeah so that's the for this problem if you enjoyed this video please like and subscribe thanks for watching | 2024-03-20 10:33:58 | 1,286 | Leetcode 1286: Iterator for Combination |
|
AwJfe6hnsfY | hey guys today we're going to talk about question question array which item is not equal to average array which item is not equal to average of neighbors of neighbors so you are given a zero index array so you are given a zero index array numbers of distinct integers numbers of distinct integers you want to rearrange the elements in an you want to rearrange the elements in an array such that every element array such that every element in the rear in the rear range array is not equal to the average range array is not equal to the average of its neighbors of its neighbors okay let's look at what does that mean okay let's look at what does that mean so basically what i mean is so basically what i mean is the ranger array should be the ranger array should be a property that such that for every a property that such that for every i i in that range in that range one one less than equal to less than equal to i i less than less than num star length minus one num star length minus one and nums i minus one and nums i plus one there were two is not equal to num i so basically right here so so for example if i at index one right will be two and is i minus one this position and i plus one is position play add up together divide by two shouldn't be the same as number two that's what it means so let's look at our approach you know so first i basically my mindset is i try to sort it first you know i try to sort the array and i change to list arraylist because it's more easier for me to remove it at the elements if i need to you know i need to swap the position if i need to change the position so i use the i change it change this array to the list first and then i sort it here i run through the you know front of i equal to one to the last element of the list so i check if the you know left if i the current index for example is one is the element at the left an element of the right divided by two that number is equal to number you know number two you know i need to change something and i need to basically re move it move the next one move the right one move the next one move the right one right one element to the right one element to the at the end of the array so basically at the end of the array so basically that's what i did here that's what i did here so you know so you know and i check and i check if the right most if the right most element is not equal to like that it's element is not equal to like that it's not at the end of the not at the end of the it's not at the end of the it's not at the end of the last element that i can move it you know last element that i can move it you know because if i because if i if the element is at the right if the element is at the right and most i cannot move to anywhere so i and most i cannot move to anywhere so i check if that condition is true so check if that condition is true so temporary equal to the temporary equal to the element element you know i plus one i remove the element you know i plus one i remove the element first and i add attempt to the end first and i add attempt to the end else else you know i swap you know the element at the current index i was the first element you know because was the first element you know because things we cannot move it because in this things we cannot move it because in this case else case case else case indeed indeed the i plus one element is at the end of the i plus one element is at the end of the list so i cannot move it to end the list so i cannot move it to end again so i move to the front again so i move to the front and then i convert back to the array and then boom i written result yep and for this one the time capacity should be of n because i run to every element in the nums array time and space complexity should be open too because i create another list to help space is open all right thank you guys you | 2024-03-25 13:23:29 | 1,968 | LeetCode 1968. Array With Elements Not Equal to Average of Neighbors - Weekly Contest254 Q2-Day 24 |
|
8S5jpVM3kWw | and I always suggest that if you read my graph concept playlist, then graph bill Wickham is very fine, try it once, for that remove the maximum number of cups, graph The name of the question is this The name of the question is this The name of the question is this and what is it, after and what is it, after reading it from my playlist of graph concepts, which is a cake walk, it has been reading it from my playlist of graph concepts, which is a cake walk, it has been explained in such a way and this explained in such a way and this question will be okay, just apply, question will be okay, just apply, nothing else but we will also see why DSE nothing else but we will also see why DSE happened to apply. look at the question, it is given in the question look at the question, it is given in the question that Alex and Bob, they have an that Alex and Bob, they have an undirected graph in which there are nodes, undirected graph in which there are nodes, okay, there are n notes, there are numbering of notes, okay, there are n notes, there are numbering of notes, one is three forages, geography is there, those are What will be the first type What will be the first type What will be the first type in which only Alice can move? Second type in which in which only Alice can move? Second type in which only Alice can move. Third type only Alice can move. Third type 3 in which both can move. Okay, so now the 3 in which both can move. Okay, so now the input will be given like this. First input will be given like this. First value type will be U and second will be the value type will be U and second will be the value of note. value of note. value of note. What is the maximum edge you can What is the maximum edge you can remove? Remove it. Okay and what is the meaning of traveling? Start from any note and go to any note Yes, the answer is asking Yes, the answer is asking Yes, the answer is asking how many can you remove? Okay, so now let's how many can you remove? Okay, so now let's understand from the example. understand from the example. Look here, this is the input. Here N = 4 means Look here, this is the input. Here N = 4 means total 4 notes. Okay, so the graph is something like this. 1234 is Here, the Here, the Here, the types are given here, these are the first types are given here, these are the first types, okay, the first entry and the remaining two are the types, okay, the first entry and the remaining two are the edges, these notes are clear till now, so edges, these notes are clear till now, so here we write separately which is which here we write separately which is which type, then which will be type three. type, then which will be type three. type, then which will be type three. in which both people can walk, which will be type, which will be green, that will be type you, type one, check, Let's do Let's do Let's do that if we start from here from the story also that if we start from here from the story also but for example, if Luck but for example, if Luck starts from here then let's see whether Alice starts from here then let's see whether Alice can go to every note or not. Okay, so can go to every note or not. Okay, so you have to go from one. Science, this is the blue one, you have to go from one. Science, this is the blue one, so both. so both. so both. like here a gaya because this blue is ahead so both people can walk in it ok now can go to four or not they see It will It will It will go to pay and then from here it will go to 4 because go to pay and then from here it will go to 4 because it can go on raid. So here Bob can go from story to story also to note. Okay, so now let's see how we will solve this. So now look, the most important question Why will it be solved and how? There is a Why will it be solved and how? There is a Why will it be solved and how? There is a question of DC in your mind. Okay, so question of DC in your mind. Okay, so first of all, you will not remove this mother of yours who is the most first of all, you will not remove this mother of yours who is the most beautiful, then someone else will remove her. Okay, so that will be a very long and complex method and that is probably the right method too. No, it is okay, what does it mean that BFS and DFS are a mistake, they cannot be made with it, okay, then DSC is a question of how and why, understand that, if you pay attention, then what is the best way to make it, like a mother takes I have I have I have 1234 notes, give, give, how many should I give for the starting major, how many should I give, how many should I how many should I give for the starting major, how many should I give, how many should I give, but I need to know the give, but I need to know the minimum number of edges, the minimum number of edges, the minimum number of agencies, I will lose my head, minimum number of agencies, I will lose my head, okay, so what will I do by okay, so what will I do by making only one catch? making only one catch? making only one catch? problems are there or not, then I will make another one ahead, let's see if all the problems are there or not, then I will make another orange one, then I will make another one, I will find out that okay, all the edges are negotiable, okay, this is the journey, all the edges are there, so we have How much further did I have to make, just by making one, two, three, all the graphs became traversable and if the exact change was given, then how many extra inches were given in vain. Okay, so my answer should be given only if it can be seen, but I have noticed one thing here. What did you do in the beginning, kept all the notes empty, alone slowly built it, while what did I teach you that in the beginning, what did I teach you that in the beginning, all the people are alone, then slowly all the people are alone, then slowly say, if you want to join, then they come in a group, say, if you want to join, then they come in a group, then they take the mother, they join. then they take the mother, they join. then they take the mother, they join. included in this group, then it is understood that brother, this question will be made from DSC. Okay, now let's see how to apply for DSO and yes, they will solve the bill. So when I was explaining it to you, now at You must have understood what You must have understood what You must have understood what we will do, we will do, in the beginning all the notes will be different, gradually in the beginning all the notes will be different, gradually I will travel through whatever edge I have given I will travel through whatever edge I have given and will see that if whatever I have and will see that if whatever I have given ahead is connecting, then given ahead is connecting, then connect. connect. connect. connecting will be connected, that is, we will connect in minimum numbers, and we will know exactly the life we have, and we will know the minimum number of connections, we will know from 10 U, okay and Now one thing is given in the question that brother, the complete tower should be there in the last. Okay, so what is the full meaning of complete that all the components should be in one group in the last. So what does it mean that when So okay, everyone is different, in the beginning So okay, everyone is different, in the beginning So okay, everyone is different, in the beginning everyone will start joining separately, if they start doing union, then in the end everyone should be in the same group, meaning in the end till now, how many components were there in the beginning, If we start doing union, If we start doing union, If we start doing union, then I need to get only one component then I need to get only one component which is there, it should be all in this only, only then the which is there, it should be all in this only, only then the entire entire graph will be successful. Okay, so let's try it once and see the example given graph will be successful. Okay, so let's try it once and see the example given and and see if it works with DSO. see if it works with DSO. see if it works with DSO. it will become clear further. Okay, when we run from the example, see if you understand from this example, then before starting the example, we should know two things. First of all, remember this, sorry, If the information of is correct, then only which edges will be there in the graph of this time both can work. Okay, so that is, if we define the robbers, If it does If it does If it does n't work separately, n't work separately, then we will create a DSO class and create two then we will create a DSO class and create two objects, one for 41, one for objects, one for 41, one for Bob, okay if we do that code Bob, okay if we do that code then it will be clear, but we then it will be clear, but we just need to know that both of them are separate. just need to know that both of them are separate. just need to know that both of them are separate. butter to handle, okay, for our ease, the first point, the second point is very important, understand that but as an example, I have two notes. Okay, now someone comes with a band, he has to so what did I do? so what did I do? so what did I do? is no one in front, then why should I Type 1 in front? He said, I have to put one of Type 1 in front Type 1 in front? He said, I have to put one of Type 1 in front for Bob, so right now I have zero for Bob, so right now I have zero present of Type 1, it can work in it, if present of Type 1, it can work in it, if Bob can't work, then one for Bob also. Bob can't work, then one for Bob also. Bob can't work, then one for Bob also. ok now tell me one thing, now some guy should come with type 3 first, ok, we are removing it now, if some guy comes with type 3, then what did I do, he turned me into type 3, ok, now let's Someone Someone Someone said, for whom should one of type 2 be fitted in front? For said, for whom should one of type 2 be fitted in front? For Bob, I would say that it is Bob, I would say that it is not necessary to fit because in type 3, both not necessary to fit because in type 3, both can work. Okay, so I did not fit. can work. Okay, so I did not fit. Okay, now someone else is saying to fit type 1 Okay, now someone else is saying to fit type 1 gas only. look, last time we had to make two separate front look, last time we had to make two separate front butts for Else and Bob, now butts for Else and Bob, now I got reduced to only one yard. You I got reduced to only one yard. You see what this means is see what this means is what will we do first, okay first What will be the benefit of 3, What will be the benefit of 3, What will be the benefit of 3, because both of them because both of them can walk, then in future we will take Type can walk, then in future we will take Type One Type. This is the request that may not happen, we will One Type. This is the request that may not happen, we will not have to make them not have to make them because Type Three will help us, so because Type Three will help us, so it is always safe. it is always safe. then it is okay, then observe type then it is okay, then observe type three should come first, after that you or one, whoever it three should come first, after that you or one, whoever it is, Arun Care, it is okay but if type three should is, Arun Care, it is okay but if type three should come first, then what will we do, we will sort come first, then what will we do, we will sort it in descending order with it in descending order with respect. respect. respect. go first then 22 then 11 will go. Ok then 33 so now let's start processing it in this order. Okay so look here let's start one by one so remember the LS's in starting. Pass Total Number How many components will there be 4 notes 1234 Bob will also have tax notes One Tu Three Four This was the same in DSP in the beginning all the notes are different so how many components in total do we have Now how many components does Alex have tax and How many components does Bob have? There are different components, then as we do the union, the components will be reduced, so first I will come to this. Okay, it is 3, which means it is for Alice There is There is There is talk of connecting both of them, it is okay for one and you, talk of connecting both of them, it is okay for one and you, first let's come to this, it means both of them are from different Jats, then both of them will have to be brought into the group, so what did I do, if both of them are in the group. Merged and made parents one. Okay, so one component is reduced. If we have blocked it, then we keep track of how many draws we have done. A similar science has been added to the group. This We will have to do the same We will have to do the same We will have to do the same for 'One' and 'Tu' is the for 'One' and 'Tu' is the parent of 'One' itself is 'You', both belong to different parent of 'One' itself is 'You', both belong to different groups, so we will have to merge both of them, groups, so we will have to merge both of them, so if I do it then the so if I do it then the size of the component is reduced by one, total three components size of the component is reduced by one, total three components will come now. will come now. will come now. Okay, so we have drawn one ahead, we have done this, Okay, so we have drawn one ahead, we have done this, now there is only one of them, so now there is only one of them, so look here this is a forest, okay look here this is a forest, okay now let's come, we now let's come, we will do this with both of them. will do this with both of them. will do this with both of them. connected, you and three have to be connected then first they ask you who is your parent, one is one, that okay, both are from different houses, so bring three here, The thing is, look, only two components are visible, The thing is, look, only two components are visible, The thing is, look, only two components are visible, both are correct, now here we come to one, that both are correct, now here we come to one, that means Alice is being talked about and one and means Alice is being talked about and one and three are being asked to be connected, the crosses of three are also one, so there is So, this time we did So, this time we did So, this time we did not draw this forward, we did not need this thing, not draw this forward, we did not need this thing, okay, similarly here too, one, two, four, one okay, similarly here too, one, two, four, one means we are talking about Alice, means we are talking about Alice, in this we are being asked to connect you and four, in this we are being asked to connect you and four, so so so parents are four themselves, so if they are from different houses, then four will also be unionized, then four came here and the size of the company got reduced and science made us draw it, only then. Ma, whatever is here, we will make plus one that we have drawn one more, it is just okay, now let's come here, we are also talking about one and you, so the payment of one is one, you are one only. talk of three and four. talk of three and four. Both are from different houses. Both are from different houses. Here we have done union. The size of the complaint has been Here we have done union. The size of the complaint has been reduced to 1. reduced to 1. So we will have to add plus one. We are already connected. If we just do it, then If we just do it, then If we just do it, then that brother, the entire graph should be equal, all the notes will be written at one place, all will be all the notes will be written at one place, all will be connected to each other and look, this connected to each other and look, this is also correct, all the components are inside it. is also correct, all the components are inside it. is also correct, all the components are inside it. everyone can travel, size as the complaint, is ok, so understand our story point something like this, is ok, so understand our story point something like this, first of all, what will be the story point, first of all, what will be the story point, understand the story that understand the story that 21 will be 21 will be a bob. a bob. a bob. I told you to sort because I want to process type three first. process it. What things will we pay attention to, how far forward we have drawn, we will keep the account Katra and the components of both will keep decreasing. [Music] It is clear till now, okay, so is clear till now, okay, so here we know that just by doing this, the here we know that just by doing this, the pudding code made from story point will pudding code made from story point will also be very easy, okay, so look, let us code it, so first of all If I have to write the code of DSC then like every time what If I have to write the code of DSC then like every time what If I have to write the code of DSC then like every time what I do is that I take a separate code of DSO I do is that I take a separate code of DSO from here which we have written from here which we have written but what I said that but what I said that DSO has to be written for two people and not for Bob for 41. DSO has to be written for two people and not for Bob for 41. So, let's create a separate class for them, let's So, let's create a separate class for them, let's create a class for DSO only. create a class for DSO only. Okay, remember that. What we did is, we pasted the complete code of our DC here. Okay, components should also be known. Write's components should also be known. Write's complaint. total number of notes done, so what did I say that I done, so what did I say that I will make diu for Alice, then there will be will make diu for Alice, then there will be n in DSO in which it is ok from node, we have learned this. Okay, after this what did I say that we It used to be first of all, what do we have to create separately for Alice and Bob, first of all, what do we have to create separately for Alice and Bob, so we have created it, so we have created it, after that we have to do sorting, it is done, okay after that we have to do sorting, it is done, okay now let's start our remaining sorry now let's start our remaining sorry points, let's write the account further. points, let's write the account further. How many age drops have we done till now, it is How many age drops have we done till now, it is zero in the beginning, now everyone is doing it, zero in the beginning, now everyone is doing it, okay, there are three levels in the agency, earlier it used to be that three levels in the agency, earlier it used to be that what is the brother's type, is his type okay so first let's so first let's ask in his world, ask in his world, that is, F. that is, F. that is, F. Alice, she is with her parents, okay, we will have to do okay, we will have to do union, we have done urine, okay, and now we go to you, similarly, let's do Bob's thing, who will have to make it, but pay attention to one more thing. who will have to make it, but pay attention to one more thing. When you are doing a union then the When you are doing a union then the component will also have to be reduced. If the component is component will also have to be reduced. If the component is missing then one less thing is done. Union is included missing then one less thing is done. Union is included in the code. Here is what the components do - we will have to do this too. So we were saying that the components are being If we have to do mines, then If we have to do mines, then If we have to do mines, then we should not miss this important thing. we should not miss this important thing. Okay, okay, till now everything is clear. If Okay, okay, till now everything is clear. If type is three, then type is three, then union is done with Alice, union is done with Bob and union is done with Alice, union is done with Bob and if add is further, then add account. if add is further, then add account. if add is further, then add account. ok, apart from this what can happen that type is equal tu is equal tu ok till now it is clear so see the story ok till now it is clear so see the story point is complete first made a graph for both of them after point is complete first made a graph for both of them after sorting all who has sorting all who has sorting all who has three then Babar Ali, both have to be done. If you are type one, then you have to do it only for Bob. If you are type one, then first you have to do it for him. Okay, now when everything is over, now when everything is over, what did I say in the last that IF The thing was that if we The thing was that if we The thing was that if we take out Alex's component, take out Alex's component, write a function here and write a function here and say, we will return a single component, [music] and Bob's single comment should be only one, OK, now let's run this example. happen myself, so I have missed this thing, happen myself, so I have missed this thing, I am fine with you, I am fine with you, okay this Music] | 2024-03-21 14:35:31 | 1,579 | Remove Max Number Of Edges To Keep Graph Fully Traversable | Leetcode - 1579 | DSU | GOOGLE | Live |
|
vOWJxCkvrzc | is another beginner problem called fizzbuzz it's quite popular it's a fizzbuzz it's quite popular it's a children's game where you you have to keep the sound of your face or it's a buzz giving an integer ends return a string of array answer one index where you basically had to uh you basically had to uh return fizzbuzz if I the eye position is return fizzbuzz if I the eye position is divisible by three and five or you turn divisible by three and five or you turn fifths if it's divisible by three or you fifths if it's divisible by three or you turn bus if it's divisible by five turn bus if it's divisible by five then you return I if it's not on develop then you return I if it's not on develop the conditioner true so basically more the conditioner true so basically more of like an ordering of like an ordering um so to give an example basically the um so to give an example basically the input is at the end where you just go input is at the end where you just go through each of the height position through each of the height position until the end and the output is the until the end and the output is the index of the string the constraint is greater than or equal to one and it's less than ten thousand we stand at the so yeah so for example you're given this so yeah so for example you're given this input as n their N is a input as n their N is a let's say your end is five let's say your end is five so you have to go through one two three so you have to go through one two three four five so the output would be uh if four five so the output would be uh if it's one then still one then two three it's one then still one then two three three is modular by three is four is neither uh divisible by five or four is neither uh divisible by five or four so this is still four and five is four so this is still four and five is Buzz right this is divisible by five so Buzz right this is divisible by five so this Buzz yeah so this will be your output array um the thing the thing to note is you need to be familiar with the operator called modular module is like the remainder of the number and to know if a number is divisible by a certain factories you use the module operator and then check if it's equal to zero so to those of you who are not familiar with modulo you better check it out um it's it's it's easily being taught in um in any programming course because it's very it's one of the most important basic operator that you need to know so let's go ahead in the code section so I'll just go with the loop where I starting from one I is less than the length of n basically less than equal so basically going through until the end value so I plus plus so the thing to note is there are multiple checks that you need to do because I modular 3 is equal to zero five five is equal to zero and you need to have a response which is an array so you could create an array the string and you could basically just and you could basically just this start with this start with you can start zero is the starting index you can start zero is the starting index so that's how you do this in go language so that's how you do this in go language n is the capacity n is the capacity well it's a yeah serious delay length is the number of items in the array so rest is equal to a pen press and then you append phase bus so you want to do this now you want to do this on the next one also just paste face Buzz okay so here is you want to put the eye okay so here is you want to put the eye but but you need to put a string because I isn't you need to put a string because I isn't it right so you need to convert it so it right so you need to convert it so the way you convert a string to any the way you convert a string to any interesting is interesting is oy oy oh i2a is your I here it's a function in oh i2a is your I here it's a function in Gola so let's see if this is going to work valid argument type and so no n is already in sorry okay that's the first someone let's okay that's the first someone let's submit it yeah there you go um so if you like this video please hit um so if you like this video please hit like And subscribe and we'll see you like And subscribe and we'll see you again in the next episode of this again in the next episode of this beginner course of lead coding beginner course of lead coding um and thank you for watching | 2024-03-22 10:48:36 | 412 | Fizz Buzz - LeetCode 412 |
|
sg82NDF34Hw | hey hey everybody this is larry this is day 28 of the march day 28 of the march leeco daily challenge uh hit the like leeco daily challenge uh hit the like button hit the subscribe button hit me button hit the subscribe button hit me on on discord let me know what you think about discord let me know what you think about dave's prom yes the questions are back dave's prom yes the questions are back let me know what you think let me know what you think uh and today's problem is we construct uh and today's problem is we construct original digits from english uh original digits from english uh yeah so i usually solve these lives i yeah so i usually solve these lives i was a little slow fast forward or was a little slow fast forward or watch it on faster speed or something watch it on faster speed or something like that uh but okay like that uh but okay given out of order english given out of order english representation representation of i'll put the digit okay of i'll put the digit okay what does that mean five four four five but only okay input only contains lowercase english letters and can be transformed okay okay um hmm i think this problem could be a little bit more specific but i guess it means that like there's an o and a n and a e and a zero some in some some uh format two okay and then the question is uh how do you do this right i mean the first thing you can do is just change this to a frequency table and then kind of go through it um one thing to notice that it is always valid um so that means that you know you don't have to worry about uh you don't have to worry about it like you know you don't have to worry about certain scenarios let's kind of play around with it let's have um let's have a mapping so yeah so frequency table we just do collections like count of s and you can think about this as a hash table and just go through that my dog process is just to spell out the words for a second so um and again one thing that i might do uh just have you know depending on how i uh just have you know depending on how i like to do it you um maybe i'll have like zero zero um one one two two two three three four four five five six six seven seven eight eight nine nine right okay so what does this mean right um i mean i assume that there's some way of doing it in a greedy way um for example because this is always valid if there's a z in there that means that you use all the z for zeros right um so you greedily do that way and i don't know if there's an easy way to kind of figure out how to uh you know six only has x for example um but then it gets trickier right with like one and two and so forth so hmm and i don't know that there's a easy way because five for example could be anything okay let's at least you know um let me think about this but yeah let's just have a map you know map string as you go to this and this is a technique that i mentioned from time to time uh i'm more conscious about so that i don't have to do it is that i can actually just pause this right um so we could actually we could split this by comma and then you know we could do for and then we return here that split and then we return here that split of the space right so then now we can of the space right so then now we can have have mappings as you go to this thing and if mappings as you go to this thing and if you want to you want to kind of see what oops what this looks kind of see what oops what this looks like i'll print it out real quick just like i'll print it out real quick just to kind of show you uh the one liners do to kind of show you uh the one liners do get a little bit messy and i apologize get a little bit messy and i apologize for that bit for that bit but uh but it's just about springing out but uh but it's just about springing out into four loops right so zero to map one into four loops right so zero to map one one to one and so forth one to one and so forth um you can probably map the first one to um you can probably map the first one to number but i don't think it actually number but i don't think it actually matters matters um because you return it in a string um because you return it in a string anyway and you return the string in in ascending order right so it doesn't really yeah yeah this is a little bit weird because yeah this is a little bit weird because now i'm like kind of doing it manually now i'm like kind of doing it manually and what i'm doing is that okay we know and what i'm doing is that okay we know that um that um you know z for example you know z for example like we were saying earlier and then like we were saying earlier and then there's a u and four there's a u and four x and six and then you know maybe you x and six and then you know maybe you could eliminate those right um could eliminate those right um but then after you eliminate those are but then after you eliminate those are you still able to do it you still able to do it well maybe so it's a little bit awkward um because basically okay because then now we want to do them in order maybe and in a greedy order and then let's do it one by one so now we can do we say we said um we said six because there's an x so we know that for every x this should be good right um and then after that let's see let's remove this i mean i think we said you so yeah so we could do that as well and maybe we could have an algorithm to do this to be honest but uh i don't know right uh let's see and then after that we can do the five because five have and maybe we could you know do a dependency graph yeah we could have win like a loop or something just to do this uh in a programmatic way but i guess now i'm mostly done so uh maybe not mostly done but well seven in that case is you know after all the fives v is unique again so we can do the seven and then here you know we did 2 for the let's see 8 for the g let's see 8 for the g uh and then now uh and then now [Music] nine i guess for the nine but it doesn't matter one for the one as well so that means that okay one and then nine and then three right so this is definitely very uh hacky in a way but you can kind of do it um you can think about it as a dependency graph where um oh no you're not even dependency graph you just do a while loop right you do a while loop to see like a if i contain any string over containing character that any other characters don't have you know uh we can use that in the beginning right so you could have write that um i did it manually so i don't know and then now uh we can do it um yeah let's get the answer put it in a way so for x uh for was it digit digit uh word in mappings um you know uh let's see is there a set division is there counter is there a set division is there counter division in python that would be pretty division in python that would be pretty cool but uh cool but uh but yeah so basically we will get a um a but yeah so basically we will get a um a frequency of the word frequency of the word so frequency or character words i guess so frequency or character words i guess i don't know i don't know oops it's equal to collection start oops it's equal to collection start calendar of the word calendar of the word and again this just sets up the and again this just sets up the frequency map is a very easy way to do frequency map is a very easy way to do in python in python but in any language even in python you but in any language even in python you can do it with a for loop can do it with a for loop right and then now we get um right and then now we get um we get how many you know how many what we get how many you know how many what is the smallest number is the smallest number um that um that has overlaps right um because now has overlaps right um because now um yeah for example z is the smallest um yeah for example z is the smallest one one um so then we are going to be terminated um so then we are going to be terminated by the z by the z so i think i worry a little bit about so i think i worry a little bit about making sure that i making sure that i am correct oh no no because there's am correct oh no no because there's always a valid always a valid um there's always a valid answer okay so um there's always a valid answer okay so that means that that means that you know i was worried a little bit you know i was worried a little bit about with like i mean i know that i about with like i mean i know that i already talked about this but i already talked about this but i i sometimes trick myself like if there's i sometimes trick myself like if there's five z's and one year then what do you five z's and one year then what do you do right do right or maybe in a different case there's or maybe in a different case there's only only two v's and two years but you need two two v's and two years but you need two years to contain you for seven years to contain you for seven well the thing is this is always gonna well the thing is this is always gonna be valid so you don't have to worry be valid so you don't have to worry about it as long as you're doing the about it as long as you're doing the right order right order and so as long as we trust that then we and so as long as we trust that then we go okay go okay um no let's just say um no let's just say min overlap mean count min overlap mean count is equal to uh let's just say some is equal to uh let's just say some infinity number infinity number so fault of infinity so fault of infinity uh and then now we go for each key and uh and then now we go for each key and frequency character right for frequency character right for c in frequency character dot keys c in frequency character dot keys um min overlap is equal to um min overlap is equal to the min of well itself the min of well itself or the min of frequency or the min of frequency character of c character of c or mappings no no no not mavericks f the other one of c right so basically this just does uh counts the number of possible uh characters there is and then well we um we appen the digit times um times min overlap as the answer but we also want to go for the keys again to um so yeah to kind of subtract that out from the frequency table because that's how many basically now we're consuming that many number of uh characters right so now we overlap and then we just and this should be maybe good uh we should sort it at the end because now we want to sort it by the digit order i mean this is a little bit lazy but that's fine you could do bucket sword or or whatever you know there's some linear time algorithms you want to call it that um but yeah and then we just joined it back into a string let's give it a go is this roughly okay yes i'm gonna give it a submit and hope yes i'm gonna give it a submit and hope it's okay it's okay a little bit lazy today on this edge a little bit lazy today on this edge cases oh no cases oh no [Music] [Music] um um why do i get that wrong though that's why do i get that wrong though that's odd odd actually i don't i don't expect that because i don't i don't convert it to because i don't i don't convert it to int in any way so int in any way so that's actually unexpected unless i uh that's actually unexpected unless i uh did something silly which is possible did something silly which is possible i've been very silly lately i've been very silly lately um seems like this is just returning one uh this is very well i actually was uh this is very well i actually was thinking about this thinking about this oh yeah i i miss wrote this one so oh yeah i i miss wrote this one so basically this calculates basically this calculates um i need to write this a different way i think i i set this wrong i set this up incorrectly but basically what i want is that okay for example if they're like eight z's we we should set this to z or z right um eight of them and not one i don't know why i did it this way now that i think about it um but the idea the algorithm is correct but my implementation is very bad maybe it's just today today i feel like i've been okay except for my implementation it's just been all over the place um let's think about how i want to do uh i think what i want is [Music] [Music] um yeah i i think i'm just having a i don't know everyone's gonna have one of these days and hopefully that makes sense but yeah i don't know why i did it i think i was thinking of something similar and i kind of skipped over it because i was going too fast i need to slow down that's one of my problems i've been going lately is that i've been i've been having too many problems in my head um and like i just speed two up too fast i go by too fast without really thinking about what i'm doing um but yeah so this looks good now um i should have tested that case i guess but um but yeah but basically that's what i wanted to do min overlap is just account of like the the you know like basically if you have the word zero how many times can it show up in the frequency map the most right um and one of those characters is going to be zed so so this is why this works i think i could be wrong let's give it a submit before i talk a little bit more okay cool yeah so so yeah so it's always going to be constrained by the z and because this is always valid we don't have to worry about additional checking or even make decisions because um you know if this fight like i said earlier there's five sets in s then we know there's gonna be five zeros no matter what and we just have to subtract the other ones um and that means that by definition um there will be at least five years at least five r's maybe always unique actually but at least five o's as well um because if they're more o's they just go to other characters so we definitely abuse the fact that this the input is always valid um so yeah so what is the complexity of this this is just going to be linear time um because we for each character in the string we put in a frequency map so this takes linear time and then here you can actually pre-cache this of course the mappings table and the frequency character of the map um and of course these overlaps uh calculation will at most the of alpha where alpha is the number of characters or number of characters in the alphabet which is 26 which is constant time if you want uh or of alpha if you prefer so yeah and this is of course uh this is just a 10 10 digits so it's gonna be a lot of you know so is it just the number of digits times the number of alphabet um and then plus a linear time for creating this frequency table um in terms of oh and i guess this is like i said i i did it the lazy way with sorting but there's only 10 elements so you could say it's you know 10 log 10 or digits times or digits times log digit or or or one depending on how you want to phrase it it's all you know as long as you're consistent with your reasoning and logic it's fine in terms of space this is uh o one because this or or alpha depending on you know how you wanna call it this is constant or all of them with digits if you like i or all of them with digits if you like i don't know um don't know um yeah uh what else what i was going to yeah uh what else what i was going to say yeah and then the answer is just say yeah and then the answer is just going to be linear going to be linear in the size of the output which you in the size of the output which you cannot do better i guess you can do it in price but but uh in python that's not really friendly for strings but yeah so roughly speaking this is all linear time uh let me know what you think uh hit the like button hit the subscribe and join me discord let me know what you think and hope you have a good day hope you have a good rest of the weekend and yeah have a you know stay good stay healthy and to go mental health i'll see you the next day | 2024-03-22 11:08:48 | 423 | 423. Reconstruct Original Digits from English - Day 28/31 Leetcode March Challenge |
|
k0ZAy1uj9bM | [Music] all right let's talk about the common all right let's talk about the common negative numbers in the sorted matrix so negative numbers in the sorted matrix so you are given an environmental grid you are given an environmental grid which is stored in non-disk increasing which is stored in non-disk increasing order and you have to return a number of order and you have to return a number of negative numbers in the grid so this is negative numbers in the grid so this is supposed to be super simple supposed to be super simple name is your char diagram so it's going name is your char diagram so it's going to be 4 3 2 negative 1 to be 4 3 2 negative 1 3 2 1 negative 1 3 2 1 negative 1 1 1 negative 1 negative 2 1 1 negative 1 negative 2 negative 1 negative 1 negative 2 negative 1 negative 1 negative 2 negative 3 right so this is supposed to negative 3 right so this is supposed to be be how many how many one two three four five six seven eight one two three four five six seven eight so so um this is supposed to be easy like when um this is supposed to be easy like when you traverse you traverse basically you just have to traverse from basically you just have to traverse from the top left the top left two bottom right right so you're going two bottom right right so you're going here after you finish here after you finish starting another row and then finish starting another row and then finish so it basically is dilated so it basically is dilated so what is the so what is the efficient way so the negative number is efficient way so the negative number is always starting for the last one right always starting for the last one right so this could be better like if we just so this could be better like if we just make it the other way so it's still make it the other way so it's still going to be the first row and then but going to be the first row and then but we do it reversely right this is going we do it reversely right this is going to be to be super easy so if you check the number is super easy so if you check the number is positive you break so you stop at this positive you break so you stop at this point so you go on the next row right point so you go on the next row right and this one you stop at this point you and this one you stop at this point you just go on this one and you stop at this just go on this one and you stop at this point point and then go on this row and you stop at and then go on this row and you stop at this point this point so this is supposed to be easy so this is supposed to be easy so let me just uh so let me just uh just start coding so you have very easy just start coding so you have very easy result i'm going to return result and i'm going to traverse the entire grid right so it's going to be stopped on video i listen gridlocking and i plus plus all right so i'm going to start it from the uh starting from the positive number to the negative numbers which is going to be what in i j preview okay lesson with uh real balance and then j plus first this is the um uh this is from positive sonata right so from positive to negative so i have to check if we ai aj is less than zero if this is true then the result plus plus so let me just go right all right so let's talk about the right all right so let's talk about the the other way so i'm still going to uh the other way so i'm still going to uh i'm just copy and paste i'm just copy and paste all right all right so let's talk about it so i'm starting from the last one starting from the last one to the beginning to the to the first one so if there's an uh value less than zero and then i increment else which is the positive number pause the number i i just break so you you are going to just find out this is more a little bit i'm not guaranteeing i mean it's a little bit uh efficient than uh negan number which is correct right see all right let's talk about timing space so this is going to be space constant and this is going to be time and by m so m represents the length of the grid and then m represent the width of the grid right doesn't matter which one you design like it should be m by n so this is the environment and this is the solution and i will see you next time | 2024-03-21 00:26:30 | 1,351 | LeetCode 1351 | Count Negative Numbers in a Sorted Matrix | Matrix | Java |
|
okH3HAPWTVs | Hello Hello children welcome to our college so today we are going to see the question its name today we are going to see the question its name is the next number is the next number that first let us understand the problem that first let us understand the problem what is the next number the next numbers which what is the next number the next numbers which give the number whose if you give the number whose if you do prime factorization then you will have ₹ 2 five do prime factorization then you will have ₹ 2 five Prime factors should be known conventions Prime factors should be known conventions governing loot in next numbers governing loot in next numbers if I talk about first 10 next numbers if I talk about first 10 next numbers then we will have 12345 680 if you then we will have 12345 680 if you do pre factorization of these then you will do pre factorization of these then you will get 235 in prime factors Top question get 235 in prime factors Top question is that you are given a number is that you are given a number is that you are given a number print the anniversary number, then how will you do it? So let's see this example, like I told you to print your 15th street number, I told you to print 150, so you printed 153, The next The next The next number will be the tourist from The Amazing Two Three number will be the tourist from The Amazing Two Three Arrested Daabi Into Five Race to the Scene, Arrested Daabi Into Five Race to the Scene, then you will get the Yagya Number today with all the combinations. You will be Yagya Number today with all the combinations. You will be able to calculate it and able to calculate it and generate Yagya Number till the end. generate Yagya Number till the end. generate Yagya Number till the end. you softened these numbers till distant and then you printed the numbers, I have given the brute force of this in the notes also, you can see it more than 5 times, so now let us see it in DP approach. What did we say in the DP approach that we have kept three points? Suppose you have calculated your destiny number, you have calculated your K plus one. When we look at the approach of username DP, we Or from this Or from this Or from this till the teacher, we have selected all the states, till the teacher, we have selected all the states, before that we have the dates, now before that we have the dates, now from those states we have to find the answer of the next question, so from those states we have to find the answer of the next question, so similarly we have the Takhli numbers lying there, similarly we have the Takhli numbers lying there, we had to do Kepler to find out the number, so we had to do Kepler to find out the number, so what will be in it, then joker. what will be in it, then joker. what will be in it, then joker. Vanasthali number will be minimum, it will be P1 * * * Three or P 3125, P 153, these numbers will be already generated, then the next number that is going to come will be all the stars of these numbers that will arise or the sum of five times. You should understand this because the next number will be 13, which is already a generator number, its price will be three, this will be five times, if this thing was not there, then assume that we have the next number coming out, Three Three Three or f5 should be there in the already generated numbers. or f5 should be there in the already generated numbers. If it is not there then the next next number Suppose now we have 10 next numbers, now we have to talk about length number, then what will be the number for 11th, smallest multiple, all already calculated numbers, i.e. next tension logged in numbers will be 1516 or If it comes If it comes If it comes from 100 or 125 then the already written numbers will let from 100 or 125 then the already written numbers will let us see the small small s multiple and us see the small small s multiple and in this case the next number will be 15 in this case the next number will be 15 so right now we were doing 325. so right now we were doing 325. Next time if we do into five then the Next time if we do into five then the next number will be caffeine so now we next number will be caffeine so now we not need to account for pimples multiples every time, we will not need to account for pimples multiples every time, we will keep this point first, we will keep keep this point first, we will keep increasing our multiples accordingly, we will increasing our multiples accordingly, we will see you in the court, if you understand it more as a son than a code, if you see you in the court, if you understand it more as a son than a code, if you look at its code, then first the maintenance would look at its code, then first the maintenance would take equal to two. take equal to two. take equal to two. there then I will keep the counter here for you for free and made a DPR for five plus one side's DP 2012 A DPF hi kya tha humare paas jo next DPF hi kya tha humare paas jo next next number will be two times next number will be two times next number will be two times seats or three times a day Pintu will be C3 or five times deep into CO then why will the digital numbers be multiple if to * dec21 If this was our number then we will do it for if we have the number then we will It came and It came and It came and we did it because in August 2002 this next we did it because in August 2002 this next number came out. There is no need to calculate the next number two two two number came out. There is no need to calculate the next number two two two two plus one separately. So two plus one separately. So we mix one with we mix one with our senior deputy chief and minus one and then our senior deputy chief and minus one and then see You, as we just saw, your You, as we just saw, your You, as we just saw, your number is 10:30, the test is well, you number is 10:30, the test is well, you understand the question, we will meet in this video of ours. | 2024-03-22 12:20:53 | 263 | Ugly Numbers - Dynamic Programming | C++ Placement Course | Lecture 35.18 |
|
itJ3Bn5ZC4k | Hello friends, today's problem is element maximum number of monsters. In this problem maximum number of monsters. In this problem we are playing a video game. In this we are playing a video game. In this we have to defend our city from monsters. we have to defend our city from monsters. We have to know the distance of each monster from our city We have to know the distance of each monster from our city and at what speed it will and at what speed it will come towards our city. come towards our city. come towards our city. distance and speed of each monster can be different. We have a weapon with the help of which we can kill a single monster. We can kill a single monster at a time, The weapon takes a minute to The weapon takes a minute to The weapon takes a minute to charge and after that we charge and after that we can use the weapon again, that means can use the weapon again, that means we can kill a monster in a minute. we can kill a monster in a minute. If the monster reaches our city If the monster reaches our city then we lose the game. then we lose the game. then we lose the game. end there. What we have to tell is that we have to return the maximum number of monsters that we can eliminate before they reach our whistle. Like in this example. We are given three monsters and their speed is given, then in what order should we eliminate the monsters? Obviously, eliminate the monster that reaches our whistle first, then eliminate the one that is reaching after that, then If we shorten the monsters on the basis of time at which If we shorten the monsters on the basis of time at which If we shorten the monsters on the basis of time at which they are they are reaching our city, reaching our city, then what will happen to us? The then what will happen to us? The monster arriving first should be killed first and monster arriving first should be killed first and then the second one. then the second one. then the second one. on and how can we calculate the time, we have given the distance and given their speed from the whistle, so if we calculate the distance by speed, then our time will be calculated, how much time will that monster take to reach our whistle, We will do distance by speed, We will do distance by speed, We will do distance by speed, in this example, our speed is in this example, our speed is given same, everyone is one, so whatever distance will be, that much given same, everyone is one, so whatever distance will be, that much time will be taken, how much time will it take, time will be taken, how much time will it take, first one will take one, then second will take first one will take one, then second will take three and third will take four, how much time will it take? three and third will take four, how much time will it take? Already our sorted order. Already our sorted order. Already our sorted order. everyone arrives, what will we do first of all, we will kill this monster who is arriving first, then we will kill this monster on the first time unit, we will kill this monster on the second time unit, we will kill all the So So So what will be our output if we take this example and what will be our output if we take this example and our speed is given i.e. our speed is given i.e. our distance will be the same amount of time it will take for the monster to our distance will be the same amount of time it will take for the monster to reach the whistle, how much time will it take, reach the whistle, how much time will it take, how much tooth will it take and first of all how much tooth will it take and first of all what will we do? what will we do? what will we do? see on time one, if this monster reaches our whistle then it means our game will be over. We could kill only one monster at a time, so we killed the one who was reaching first. After that, it will take one minute for our weapon to charge but in that time this monster will reach our city and our game will be over. In this case, if we are able to kill only one monster, then what do we have to Similarly, if we Similarly, if we Similarly, if we see this example 324 532, the see this example 324 532, the speed of our buses is different, speed of our buses is different, first of all we will have to find out the time of everyone, first of all we will have to find out the time of everyone, when will they reach, what will be our time, when will they reach, what will be our time, 3/5 i.e. 0.6, 2/3 i.e. 0.66 and 4/2 3/5 i.e. 0.6, 2/3 i.e. 0.66 and 4/2 i.e. i.e. i.e. in sorted order, if they were not sorted, what would we do? We would shorten the time based on time, then we would kill the first monster at zero second and then see which monster we would kill at the first time. When we go to kill for the first time, before that this monster will reach our whistle, hence our game will be over. In this case, if we are able to kill only one monster, then what do we have to return? One, then simply what will we do? First of all, we will find out the time at which our monsters are reaching the whistle and then we will shorten them. On the basis of time, we will kill the monster coming first and then the one arriving after that and so The number of monsters we will be able to The number of monsters we will be able to The number of monsters we will be able to kill means that after every kill kill means that after every kill we will increase our time unit by one we will increase our time unit by one and if the monster is coming after that then and if the monster is coming after that then we can do one more kill but if the we can do one more kill but if the next monster is coming before that then next monster is coming before that then next monster is coming before that then game will be over and all the fighters we have killed till then will be returned, so what will we do, we were given distance and speed vector, first of all we have to calculate the time vector, we will make a complete loop We will figure We will figure We will figure out when each monster will out when each monster will reach the seat and then we will shorten them in ascending order reach the seat and then we will shorten them in ascending order so that the monster that is reaching first is so that the monster that is reaching first is killed first and the one that is killed first and the one that is reaching later is killed later to reaching later is killed later to check that we are check that we are We will loop from zero to We will loop from zero to possible but it is also possible that that monster reaches our city before we go to kill, in that case our game will be over in the middle, so we will check the time at which we are If at that time If at that time If at that time our monster reaches the whistle, we our monster reaches the whistle, we can kill only one monster in a minute. can kill only one monster in a minute. If the time of our IS monster If the time of our IS monster is less than the time at which he reaches the whistle, is less than the time at which he reaches the whistle, that means we will not be able to kill him. that means we will not be able to kill him. that means we will not be able to kill him. our game will be over, in that case we will return all the monsters we have killed till I. If we are able to kill everyone, then we will return all the monsters we had in the last. What will be our time complexity from here? We will need a loop of this size. From here also, we will need a loop of this size. But for sorting, it will take us n lag off n so much time. So what will be our overall tongue stick? n lag off n will it dominate and If If If we take a vector of size n, what will be the space complexity we take a vector of size n, what will be the space complexity of n? Thank you guys. | 2024-03-25 13:10:40 | 1,921 | Eliminate Maximum Number of Monsters | Leetcode 1921 | Greedy | C++ |
|
iLznbwUkyyU | hey hey everybody this is Larry this is day day [Music] 20th of delico day challenge hit the like button to subscribe button drop me a Discord let me know what you think about today's problem um yeah so hope you enjoyed the intro I am still in Georgia I'm I'm right now I'm in uh an area called kaspaki um it's basically a mountain town Mountain area there's a lot of hiking and stuff so that's what you're seeing now um I just saw definitely check out the Instagram if uh if that's you know just in general but uh yeah uh I'm in a mountain Hotel it's kind of um it's actually very nice the internet is actually relatively fast but but uh but the lighting is kind of awkward so hopefully you don't miss my face too much if you do follow the Instagram anyway okay so let's look at look at today's problem 3.99 evaluate division okay so you're giving it away in a way of wearable pairs equation in a way of real numbers values where equation I is equal to a survive you survive and why is I as you go to hey okay each A or B sub I is a string that you are given some queries where query you are given some queries where query subj C sub D is and you must find okay subj C sub D is and you must find okay okay so there's no division by zero okay so there's no division by zero there's no contradiction by uh there's no contradiction by uh oh God oh God so this is kind of so this is kind of um uh what you might call it this is just going to be um shortest pathway I mean or it doesn't even have to be a short path but just like in a way connect account connected conductivity because as long as you're able to come from you know um two variables then you're able to get to it um that's one way to do it as well but uh let me see I think the other way of doing it is just using putting everything in um uh with respect to one number or something or one variable and then just represent everything with respect to that and then that should allow you to do it um yeah I think either one is fine I think I'm gonna do the breakfast search right because I don't know I actually don't remember how I did it last time but I feel like this time you know I'm feeling it uh yeah it's okay let me think about how I want to do this first so uh I mean it doesn't really matter what um basis we use uh meaning we just have to pick a variable and then kind of keep to it so basically so basically yeah I mean we'll just take like yeah I mean we'll just take like equations of zero zero and we'll call it equations of zero zero and we'll call it the basis okay the basis okay and then basically now we we try to and then basically now we we try to figure out yeah and then now let's just create the also this hotel even though it's very also this hotel even though it's very nice and very cozy maybe I gotta do it nice and very cozy maybe I gotta do it earlier because I think there is a table earlier because I think there is a table like outside but it's raining so so it's like outside but it's raining so so it's not very helpful but uh but yeah there's not very helpful but uh but yeah there's no that's why I'm doing it on bed and no that's why I'm doing it on bed and also in a weird setup but uh but yeah okay so in this case uh we just put an adjacency list you append to see oops we see and the other way around as well um okay um okay so I just I'm adjusting my setup a so I just I'm adjusting my setup a little bit because it's actually uh not little bit because it's actually uh not gonna lie very uncomfortable uh because gonna lie very uncomfortable uh because I'm just like doing it in a very awkward I'm just like doing it in a very awkward place but uh yeah okay okay yeah and then now set up the queue we append the basis uh we wanted to say the was it translation maybe or something like this um let's just say let's just call it ratio I don't know if you go to a lookup table thing right man and then of course ratio of basis is equal to one and then probably like the Q is greater than zero current as you go to Q top left and then for v c in decency list of current then what do we want to do we want to say um so okay so if we not in ratio that means we haven't done it yet then we have to append um we but we could also set the ratio now which is equal to ratio of current by the time assume or divided by C it um um yeah but that's easy to fix I think this yeah but that's easy to fix I think this is one of those things where if you is one of those things where if you think through clearly and Define your think through clearly and Define your things clearly you could get it quickly things clearly you could get it quickly um um but I I I'm Adam redefined it and but I I I'm Adam redefined it and honestly way tied to that I I hiked like honestly way tied to that I I hiked like 10 miles in the Mounds in snow slash and 10 miles in the Mounds in snow slash and everything and it was a mess uh and uh everything and it was a mess uh and uh and I carried all my camera equipment so and I carried all my camera equipment so it's really expensive uh very tiring it's really expensive uh very tiring very very uh exhausting is what I meant to say but uh exhausting is what I meant to say but yeah for yeah for you we encourse you we encourse um um and then now we we Translate and then now we we Translate uh uh something like ratio of U something like ratio of U I don't know it's something like this or I don't know it's something like this or some some some variation of this right um oh yeah I've checked because for some reason uh if you not in Ratio or we I forgot about that case I forgot about that case um I think what I want to do is actually um I think what I want to do is actually not this because not this because it's way easier to whatever it's way easier to whatever um what you need to do is at least print um what you need to do is at least print out out modify each step of the way right almost modify each step of the way right almost like uh like almost like uh like almost like testing a component so that we can like testing a component so that we can see see um because then now you can you know for example a is one B is 2 C is six that means it's it's a over C okay so that means that okay that's actually right uh what is this B over a um so um so B coming like this then this the most awkward way to write it I think uh oh what's PC obesity is killing oh damn I'm messed up it's a connected components thing I didn't realize that I thought for some we okay I actually miss read this a little bit um um I don't know if I've misread it I don't know if I've misread it I mean I did misunderstood it I don't I mean I did misunderstood it I don't know if I misread it uh in the sense know if I misread it uh in the sense that I thought when it said that all that I thought when it said that all queries will be evaluated I just thought queries will be evaluated I just thought that they're all connected but they're that they're all connected but they're actually not so that's fine I mean it actually not so that's fine I mean it basically now you have to do a connected basically now you have to do a connected components thing and then kind of do it components thing and then kind of do it that way let me try to think of this um that way let me try to think of this um a clean way to do it doing it a clean way to do it doing it um um yeah I mean I think we can just uh it's yeah I mean I think we can just uh it's not that big of an issue not that big of an issue so yeah I mean I think this is fine it's so yeah I mean I think this is fine it's just yeah it's because everything is self-contained so it this is actually um not relating to it so we can do something like okay we just redo this but so then now let's say about this right so now we have for you we in right foreign basis not in ratio then we do this I think that should be good even though it's very confusing maybe let me see if it works first okay so now it works okay let's give a submit I misunderstood it oh I see um because then now I'm doing two things that are not connected um I see I I think I I misunderstood it again about uh the input being always valid or again I just misread it uh in that single answer cannot be determined part um because then now they're in two different components so you can't do it this way um now I wish I did with connected but actually I mean we can do we're but actually I mean we can do we're gonna add the same idea for for Union gonna add the same idea for for Union fine except for you know uh yeah fine except for you know uh yeah we could definitely uh of just uh declaring your your your uh of just uh declaring your your your your parents and in this case your group your parents and in this case your group so then now [Music] it's not me but yeah it's I think it's just me but yeah it's I think it's just me trying to be lazy to be honest I think trying to be lazy to be honest I think the white boy could have uh to do it to the white boy could have uh to do it to be honest be honest um or not the right way to do it but but um or not the right way to do it but but uh what did I do how do I like put in a sauce uh because the right way to have done it is just to rewrite it but I think I was trying to um do um classic situation of you know like I did 90 of the code I just have to you know make changes so that it works and it's true but then like we just end up forgetting some cases and stuff like that as a result which happened here so yeah um this is gonna be linear time linear space we plus e is the linear part of it um because basically we look at each Edge once and we look at each node once and each and the nodes come from the edges right so um so yeah so this is linear in the size of the input um yeah that's what I have for this one let me know what you think I'm curious what I did last time uh I did Ford War show that's right I was thinking about doing foil washer and I forgot because I was thinking about connectivity um I I remember we break these things that n is equal to 20 so there's only at least the most 40 things and even then you know it wouldn't be because then you know it wouldn't take that long but uh but yeah to be honest I just forgot I mean it's probably best or like you know it's fun to try other things so it's fine too so yeah um cool uh that's all I have for this one let me know what you think stay good stay healthy to go mental health I'll see you later take care bye bye | 2024-03-24 12:19:27 | 399 | 399. Evaluate Division - Day 20/31 Leetcode May Challenge |
|
vt6_SPRaNC0 | hello everyone i hope all of you are having a great time and welcome to day having a great time and welcome to day fifth of december echo challenge let's fifth of december echo challenge let's quickly talk about today's question in quickly talk about today's question in today's question is palindrome today's question is palindrome partitioning here we are given an input partitioning here we are given an input string s and we need to partition the string s and we need to partition the input string input string such that the every possible division such that the every possible division leads to a palindrome leads to a palindrome we need to return all the possibilities we need to return all the possibilities for palin palindrome partitioning of s for palin palindrome partitioning of s and we already know the definition of a and we already know the definition of a palindromic string which is same when i palindromic string which is same when i trade it from the backwards direction trade it from the backwards direction so let's try and understand it by an so let's try and understand it by an example here we are given an input example here we are given an input string as aab string as aab so we need to split aab in such a manner so we need to split aab in such a manner that all the partitions are palindromic that all the partitions are palindromic in nature and we need to return all such in nature and we need to return all such possibilities so let's walk through the possibilities so let's walk through the first case we have divided aaa first case we have divided aaa into singular units a a and b into singular units a a and b as you can see these are of one unit as you can see these are of one unit length these are palindromic in nature length these are palindromic in nature and when you merge these three together and when you merge these three together in order then you will lead to the input in order then you will lead to the input string s a plus a plus b will lead to string s a plus a plus b will lead to the input string s the input string s similarly let's walk through the second similarly let's walk through the second case we have divided the input string case we have divided the input string at the second index between a and b such at the second index between a and b such that that it remains palindromic in nature it remains palindromic in nature followed by b so these are the only two followed by b so these are the only two possibilities in which the input string possibilities in which the input string can be divided such that all the can be divided such that all the substrings are palindromic in nature substrings are palindromic in nature so let's quickly walk through the so let's quickly walk through the presentation that i have created for presentation that i have created for this and let's get started palindrome this and let's get started palindrome partitioning lead code 131 it's a medium partitioning lead code 131 it's a medium level question on lead code and i level question on lead code and i totally feel the same totally feel the same oops it says we have already solved this oops it says we have already solved this question and yes we did it in the month question and yes we did it in the month of december 2020 of december 2020 it's more than a year back it's more than a year back and we use the backtracking approach to and we use the backtracking approach to actually come up with the algorithm i'm actually come up with the algorithm i'm attaching the link of the video attaching the link of the video and in case we have already solved and in case we have already solved backtracking one question we have also backtracking one question we have also done backtracking two question i'm also done backtracking two question i'm also attaching the link to its video and for attaching the link to its video and for that we use the dynamic programming that we use the dynamic programming approach approach use today's opportunity to revise both use today's opportunity to revise both these concepts and if someone is looking these concepts and if someone is looking for detailed backtracking playlist or for detailed backtracking playlist or dynamic programming playlist i'm dynamic programming playlist i'm attaching those two in the description attaching those two in the description below as well below as well i hope you enjoy both these solutions if i hope you enjoy both these solutions if you do please don't forget to like share you do please don't forget to like share and subscribe to the channel thanks for and subscribe to the channel thanks for viewing it have a great day ahead and viewing it have a great day ahead and stay tuned for more updates from coding stay tuned for more updates from coding decoded i'll see you tomorrow with decoded i'll see you tomorrow with another fresh question but till then another fresh question but till then good bye | 2024-03-21 11:46:22 | 131 | Palindrome Partitioning | Leetcode 131| Live coding session 🔥🔥🔥 | Backtracking |
|
quAS1iydq7U | all right so in today's problem we are going to look at the problem going to look at the problem next permutation how do we generate the next permutation how do we generate the next permutation given a sequence that next permutation given a sequence that we already have so if our sequence is 1 we already have so if our sequence is 1 2 & 3 the next permutation in that 2 & 3 the next permutation in that sequence is going to be 1 3 & 2 if I sequence is going to be 1 3 & 2 if I have 3 2 1 as my permutation that I'm have 3 2 1 as my permutation that I'm given the next permutation in the given the next permutation in the sequence is the first permutation sequence is the first permutation because this is the last permutation of because this is the last permutation of the numbers 1 2 & 3 the numbers 1 2 & 3 this is the last permutation so we just this is the last permutation so we just return the empty array there is no next return the empty array there is no next permutation 1 5 & 2 permutation 1 5 & 2 what is being next permutation the next what is being next permutation the next permutation is 2 1 5 when you're looking permutation is 2 1 5 when you're looking at these you might not see a pattern and at these you might not see a pattern and I myself I do not see a pattern but we I myself I do not see a pattern but we do not see a pattern until we understand do not see a pattern until we understand how permutations are built all right so how permutations are built all right so we have two choices to this problem we we have two choices to this problem we first we can generate every single first we can generate every single permutation until we hit the permutation permutation until we hit the permutation we are given and then we go one step we are given and then we go one step forward that will give us the next forward that will give us the next permutation the problem with that permutation the problem with that approach is we are going to be doing approach is we are going to be doing factorial time work and factorial times factorial time work and factorial times and whatever work we're doing in our and whatever work we're doing in our base case or our individual calls but we base case or our individual calls but we are going to go through at worst and are going to go through at worst and factorial permutations if we're given factorial permutations if we're given the last permutation and this is a very the last permutation and this is a very expensive way to go about things the expensive way to go about things the point of this problem is not to have you point of this problem is not to have you brute force it like this the point of brute force it like this the point of the problem is to see whether you really the problem is to see whether you really know how a permutation is built and know how a permutation is built and whether you can do a in-depth case whether you can do a in-depth case analysis if you have not seen my video analysis if you have not seen my video on building permutations and permuting a on building permutations and permuting a string I highly recommend that because string I highly recommend that because that will help you a lot with that will help you a lot with understanding what goes on here but understanding what goes on here but let's investigate now let's start let's investigate now let's start connecting the dots and see how is a connecting the dots and see how is a permutation built so if we're given 1 2 permutation built so if we're given 1 2 & 3 what we need to do is we need 3 & 3 what we need to do is we need 3 slots the point of a permutation is slots the point of a permutation is to exhaust the possibilities of placing to exhaust the possibilities of placing each one of these letters in a slot and each one of these letters in a slot and then recursing and then placing the rest then recursing and then placing the rest of the numbers so here's an example at of the numbers so here's an example at the first position we have the choice of the first position we have the choice of placing the 1 the 2 or the 3 when we're placing the 1 the 2 or the 3 when we're doing it like this temporal order gets doing it like this temporal order gets precedence so we're going to place the precedence so we're going to place the first item the least item which is 1 so first item the least item which is 1 so I want you to notice something 1 is not I want you to notice something 1 is not in our possibility space we are at the in our possibility space we are at the second slot we only have 2 choices we second slot we only have 2 choices we have 2 slots we have 2 choices and at have 2 slots we have 2 choices and at this second slot we can either put a 2 this second slot we can either put a 2 or 3 we can either put a 2 or 3 notice or 3 we can either put a 2 or 3 notice that so what you see here is we planted that so what you see here is we planted a 1 and that's exactly where our a 1 and that's exactly where our permutation stands in its state right permutation stands in its state right now they decided to plant a 1 and notice now they decided to plant a 1 and notice they decided to plant a 2 so at this they decided to plant a 2 so at this position we either could plant the 2 or position we either could plant the 2 or 3 the decision was made by this person 3 the decision was made by this person or power to this permutation panned out or power to this permutation panned out to place the 2 at this position at this to place the 2 at this position at this state it holds a state it is currently state it holds a state it is currently exploring the number of ways it can exploring the number of ways it can place two and then recurse we place the place two and then recurse we place the 2 and we explore all possibilities and 2 and we explore all possibilities and then after replaced the two our decision then after replaced the two our decision space is down to 3 now all we can place space is down to 3 now all we can place here is a 3 let's place the 3 and now we here is a 3 let's place the 3 and now we have exhausted our decision space at have exhausted our decision space at this slot all we could place is the 3 so this slot all we could place is the 3 so now we ask ourselves the question we ask now we ask ourselves the question we ask ourselves what is the next permutation ourselves what is the next permutation to 1 2 3 now do you notice how we to 1 2 3 now do you notice how we understand more about the problem we understand more about the problem we understand more about these states that understand more about these states that the permutation we are sitting in came the permutation we are sitting in came from where did it derive from what state from where did it derive from what state is this slot in this slot is in this is this slot in this slot is in this state of exploring the placement of to state of exploring the placement of to notice that we have exhausted all the notice that we have exhausted all the placements all we could place here is 3 placements all we could place here is 3 we've done 3 so what we need to do to we've done 3 so what we need to do to find the next permutation is backtrack 1 find the next permutation is backtrack 1 ok we back ok we back - one and again we're gonna get to the - one and again we're gonna get to the core algorithm but I just need you to core algorithm but I just need you to understand this walkthrough so we got understand this walkthrough so we got through the three and now this slot is through the three and now this slot is at the three is back in the decision at the three is back in the decision space and notice we planted on two we space and notice we planted on two we explored all of the possibilities that explored all of the possibilities that two's placement had to offer which was two's placement had to offer which was placing a three-year and now two has placing a three-year and now two has exhausted itself and the two returns to exhausted itself and the two returns to the decision space so now we can use the decision space so now we can use either two and or three at this position either two and or three at this position the next thing the two place is going to the next thing the two place is going to be a three before it was two two did all be a three before it was two two did all victim it's exploring this was on its victim it's exploring this was on its last permutation and now we place the last permutation and now we place the three and now notice three is not in our three and now notice three is not in our decision space anymore and now all we decision space anymore and now all we can place here is two and so now one can place here is two and so now one three and two so what is the overarching three and two so what is the overarching state the overarching state is we state the overarching state is we planted a one what else could we have planted a one what else could we have planted here we could have planted two planted here we could have planted two or three so all the while we're doing or three so all the while we're doing our exploring over here our exploring over here we are doing it off of the planting one we are doing it off of the planting one while we're doing our exploring here while we're doing our exploring here we're doing it off the planting three we're doing it off the planting three while we're exploring here we're doing while we're exploring here we're doing our planting off of two it is all about our planting off of two it is all about planting and exploring possibilities so planting and exploring possibilities so this is the next permutation so let me this is the next permutation so let me ask you what would the permutation after ask you what would the permutation after this be so what we notice is that a this be so what we notice is that a section that is decreasing has exhausted section that is decreasing has exhausted itself and reached its last placement if itself and reached its last placement if we try to find the next permutation what we try to find the next permutation what we would do is we would need to see we would do is we would need to see where we need to backtrack so what we do where we need to backtrack so what we do is we notice that two has exhausted all is we notice that two has exhausted all the possibilities so we need to erase the possibilities so we need to erase two and return it to the pool and notice two and return it to the pool and notice we have no more things to explore at the we have no more things to explore at the second slot we've tried the two we've second slot we've tried the two we've tried the three so we erase the three tried the three so we erase the three and so now we have explored all the and so now we have explored all the possibilities with one rooted in the possibilities with one rooted in the first slot now what is the next item to first slot now what is the next item to get routed to is the next item to get get routed to is the next item to get the routing and now our decision space the routing and now our decision space has adjusted itself to gets the planting has adjusted itself to gets the planting we're now exploring on - and now we have we're now exploring on - and now we have two choices for the second two choices for the second we can place the one or the three and we can place the one or the three and now we choose precedence on the lesser now we choose precedence on the lesser item so one gets the placement and then item so one gets the placement and then all we can put in the last slot is three all we can put in the last slot is three that's all we have left so this is the that's all we have left so this is the next next permutation this is the next next permutation this is the permutation after the permutation we permutation after the permutation we just made so I want you to start just made so I want you to start noticing a pattern what we're doing is noticing a pattern what we're doing is we're looking for a strictly decreasing we're looking for a strictly decreasing section because that is the section that section because that is the section that has exhausted itself this has exhausted has exhausted itself this has exhausted itself so this would get erased so the itself so this would get erased so the element before the strictly decreasing element before the strictly decreasing section is the element that still has section is the element that still has options to explore so now the next options to explore so now the next option would be to explore the three and option would be to explore the three and then so on so what we notice is the item then so on so what we notice is the item right before is strictly decreasing right before is strictly decreasing section is the item of interest that is section is the item of interest that is what we need to do our modulation on in what we need to do our modulation on in order to advance us to the next order to advance us to the next permutation because the strictly permutation because the strictly decreasing section has exhausted itself decreasing section has exhausted itself the item before that section has items the item before that section has items that it can swap between it still has that it can swap between it still has more choices for its slot so let's look more choices for its slot so let's look at a concrete example to see this at a concrete example to see this pattern so this is a very tricky case pattern so this is a very tricky case analysis problem this is not something analysis problem this is not something where you just instantly know the answer where you just instantly know the answer and I need you to make a few and I need you to make a few intellectual jumps here so that you can intellectual jumps here so that you can really let this sink in so what we just really let this sink in so what we just noticed is each of the decisions are noticed is each of the decisions are plantings so imagine I am given this plantings so imagine I am given this permutation we'll see why these are permutation we'll see why these are important but notice this person said important but notice this person said lemme plant six it goes out of our lemme plant six it goes out of our decisions base decisions base they said let me plant two it goes out they said let me plant two it goes out of our decisions base they said let me of our decisions base they said let me plant one and then one disappeared from plant one and then one disappeared from the decision space but notice here this the decision space but notice here this item is before a strictly decreasing item is before a strictly decreasing section remember we just established a section remember we just established a strictly decreasing section is on its strictly decreasing section is on its last permutation if this section is on last permutation if this section is on its last permutation what do we need to its last permutation what do we need to modulate we need to modulate what is modulate we need to modulate what is right before that strictly decreasing right before that strictly decreasing section why so when we are at slot section why so when we are at slot number three number three we have these choices we already we have these choices we already expressed all of zeros decisions if we expressed all of zeros decisions if we are on one if we chose one to be placed are on one if we chose one to be placed in the slots we have passed all of zero in the slots we have passed all of zero zero is behind us that's not going to be zero is behind us that's not going to be on our next permutation planting we need on our next permutation planting we need to consider what is the next item that to consider what is the next item that we plant here so these are the items we plant here so these are the items left to us our cut out of our decision left to us our cut out of our decision space so we have a 1 3 4 and a 5 and space so we have a 1 3 4 and a 5 and notice our 1 is the item that was chosen notice our 1 is the item that was chosen so the next item to take one's position so the next item to take one's position the position right before the strictly the position right before the strictly decreasing section the item is the next decreasing section the item is the next greatest item to the right of 1 what is greatest item to the right of 1 what is the next greatest item the next greatest the next greatest item the next greatest item is 3 so we look for the item that item is 3 so we look for the item that is the next greatest item in the is the next greatest item in the decreasing section we look for 3 because decreasing section we look for 3 because guess what 3 is next up in line to get guess what 3 is next up in line to get the placement at this slot and then 4 the placement at this slot and then 4 will get a placement mmm 5 so what we do will get a placement mmm 5 so what we do is we swap these items we swap the 1 and is we swap these items we swap the 1 and a 3 so that 3 gets its placement it is a 3 so that 3 gets its placement it is next okay so now we've almost completely next okay so now we've almost completely simulated going to the next permutation simulated going to the next permutation we've swapped the next routing before we've swapped the next routing before the decreasing section but notice that the decreasing section but notice that this is on the last permutation if we this is on the last permutation if we were going to plant at 3 so what we need were going to plant at 3 so what we need to do is turn this strictly decreasing to do is turn this strictly decreasing section into an increasing section so we section into an increasing section so we are on the first permutation of planting are on the first permutation of planting at 3 this would be the last permutation at 3 this would be the last permutation of planting at 3 we want to be at the of planting at 3 we want to be at the first permutation planting at 3 so we first permutation planting at 3 so we reverse this sub list we don't need to reverse this sub list we don't need to sort it we can just reverse it because sort it we can just reverse it because it's already in reverse sorted order and it's already in reverse sorted order and so now this is how we find the next so now this is how we find the next permutation notice we've only done permutation notice we've only done linear time operations we're not pulling linear time operations we're not pulling into factorial timing of Lex T we've into factorial timing of Lex T we've been able to use case analysis to stay been able to use case analysis to stay linear in how we solved the problem so 3 linear in how we solved the problem so 3 got its next routing and these suffix got its next routing and these suffix has been minimized when it is decreasing has been minimized when it is decreasing it as maximized it is on the end of it as maximized it is on the end of itself but when it is increasing then we itself but when it is increasing then we have have my's this we have minimized the routing my's this we have minimized the routing and guess what this is the next and guess what this is the next permutation and that is how you find the permutation and that is how you find the next permutation without using factorial next permutation without using factorial time or expending a brute force solution time or expending a brute force solution and so now the time and space and so now the time and space complexities are very straightforward complexities are very straightforward and is the length of the permutation and is the length of the permutation string we start with so the time string we start with so the time complexity is going to be O of n we're complexity is going to be O of n we're going to scale in a linear fashion as going to scale in a linear fashion as our input gets arbitrarily large this is our input gets arbitrarily large this is because all we do is linear time passes because all we do is linear time passes we're going to do a linear time pass to we're going to do a linear time pass to find the longest decreasing sequence find the longest decreasing sequence we're going to do a linear time pass to we're going to do a linear time pass to reverse that sequence and we're just reverse that sequence and we're just going to do a constant time swapping so going to do a constant time swapping so none of this is going to take us past none of this is going to take us past the linear time for space we're going to the linear time for space we're going to stay constant so the reason it's stay constant so the reason it's constant is we're just going to be using constant is we're just going to be using local variables we're just going to be local variables we're just going to be using pointers we're not going to be using pointers we're not going to be using anything that scales our space as using anything that scales our space as the input gets very large so these are the input gets very large so these are the time complexities so if you liked the time complexities so if you liked this video hit the like button subscribe this video hit the like button subscribe to the channel I hope this explanation to the channel I hope this explanation was as clear as possible this is not one was as clear as possible this is not one of those questions that scales well to of those questions that scales well to other questions it's really one of those other questions it's really one of those things where it's a raw case analysis things where it's a raw case analysis and really understanding the and really understanding the backtracking of permutations to be able backtracking of permutations to be able to analyze a solution like this it's not to analyze a solution like this it's not something that is going to apply for something that is going to apply for many things so that's all for this one many things so that's all for this one [Music] | 2024-03-20 08:36:48 | 31 | Compute The Next Permutation of A Numeric Sequence - Case Analysis ("Next Permutation" on Leetcode) |
|
HdFGyKDCZyM | hello everyone welcome back to another video in this video we are going to video in this video we are going to solve with Lead Core problem which is solve with Lead Core problem which is named as maximum difference between two named as maximum difference between two pairs so in this question you will be pairs so in this question you will be given an input array in which you will given an input array in which you will be given some numbers and you have to be given some numbers and you have to return the maximum output return the maximum output which will be the product of Maximum which will be the product of Maximum difference between two pairs difference between two pairs but what do you mean by duplex so let's but what do you mean by duplex so let's see from our first example let's try to see from our first example let's try to understand and see what should we are understand and see what should we are approach S40 S40 42 so when we subtract 42 by 8 we get 34 42 so when we subtract 42 by 8 we get 34 as and answer as and answer so this would be the answer for power so this would be the answer for power solution so what we can see from the solution so what we can see from the question is that first of all if we question is that first of all if we solve the a we will able to find the solve the a we will able to find the answer in N log n time complexity that n answer in N log n time complexity that n is the number of terms in your is the number of terms in your n okay so if we saw this using sort n okay so if we saw this using sort algorithm and Z Plus algorithm and Z Plus simply write 2 4 5 6 7 as a solution so let's see the code for the same first of all we are going to sort our array by using sort function and then we are going to find the total length of the vector and then we are going to use written simply return the last indexing so we are going to return the product of the last and last hurricane index abstracted by the first and the second index so now let's run the program and submit it and let's check if a code works or not so as you can see here we have successfully submitted our code and it's | 2024-03-25 13:02:33 | 1,913 | Maximum Product Difference Between Two Pairs - Leetcode 1913 - C++ |
|
rq0jeRMsErI | daily challenge which is 382 English random number random number so as per this question so as per this question uh we have given a single linked list uh we have given a single linked list written the random nodes value from the written the random nodes value from the linked list each node must have the same linked list each node must have the same probability of being chosen probability of being chosen so so uh there are two methods we need to uh there are two methods we need to implement solution and one is and get implement solution and one is and get random okay random okay so if you're given an English let's so if you're given an English let's suppose one suppose one two two three three and four and four so at every time get random get code so so at every time get random get code so you need to return any random number you need to return any random number from range one to four from range one to four okay this is the size of the link list okay this is the size of the link list and you need to return any node value and you need to return any node value randomly randomly okay okay so if you want to go in an easy way easy so if you want to go in an easy way easy services at the starting when solution get cold at the starting when solution get cold okay okay foreign so it is a very easy way to approach this question very very easy way that what are my observation like if I try to write my observations what was the observation key solution will give me the link list the whole okay and I need to return at the time where get random get code at the time where get random get code okay so these are the two observations okay so these are the two observations and as I know like if I want to go in a and as I know like if I want to go in a very easy way I will do this I will very easy way I will do this I will follow this approach error list mad dot follow this approach error list mad dot random that's it okay let me uh show you random that's it okay let me uh show you the code of this very easy approach the code of this very easy approach so what I just did I created an so what I just did I created an arraylist this is a global error list arraylist this is a global error list okay range at the time solution get cold okay range at the time solution get cold I am pushing all my elements into the I am pushing all my elements into the array array uh creating a random number generating a uh creating a random number generating a random number using math dot random and random number using math dot random and within the range dot size okay within the range dot size okay and simply returning range dot get like and simply returning range dot get like array array particular element array array particular element okay in order of one so this function is okay in order of one so this function is order of n order of n and this is order of one basically and this is order of one basically okay so but the space complexity here is okay so but the space complexity here is order of n order of n due to error list and time complexity is due to error list and time complexity is also order often also order often but if you are sitting in an interview but if you are sitting in an interview right now so you came up with this easy right now so you came up with this easy approach now the interviewer is asking approach now the interviewer is asking for a follow-up question what was the for a follow-up question what was the follow-up question follow-up question if you scroll down in this question if you scroll down in this question there is a follow-up question but if the there is a follow-up question but if the link list is extremely large and it is link list is extremely large and it is less is unknown to you less is unknown to you what is the interviewer is asking yeah foreign you need to imagine there is a link list or there is a stream with unknown size so can we resolve it with uh without using extra space that is a follow-up question from the interviewer okay so this can be resolved if we broad our mind if you like if you want to stop at the easy solution that is totally up to you but if you want to broaden up your mind so then devil came up within algorithm which is nothing but sorry this is the spelling reservo assembling I will tell you the simple way to understand this algorithm very very just keep your focus here just listen it just keep your focus here just listen it I will use very very simple words I will use very very simple words so the understanding of this algorithm so the understanding of this algorithm will be very very easy will be very very easy what is the simplest way what is the simplest way to describe this algorithm is to describe this algorithm is and the reservoir is happening algorithm and the reservoir is happening algorithm but this this sampling algorithm says but this this sampling algorithm says like uh I will choose like uh I will choose K elements from n numbers n is not defined to me right now okay it can be a stream or something anything choose K element from n numbers what is the main thing in this we need each element has should get selected sorry for the bad handwriting should get selected with the same probability keep in mind same same probability keep in mind same probability okay keep this definition in your mind okay keep this definition in your mind so it will be very easy for you to so it will be very easy for you to understand okay now what if I selected understand okay now what if I selected now why this Reservoir algorithm I am now why this Reservoir algorithm I am using Okay I I will give you one using Okay I I will give you one scenario let's suppose you are given a scenario let's suppose you are given a link list one two three you are picking link list one two three you are picking a random number in this range the time a random number in this range the time you are picking this uh the number from you are picking this uh the number from this range I added few numbers from here this range I added few numbers from here side and added few numbers for from here side and added few numbers for from here side but as per our easy approaches yeah problem generator problem generator problem generator what he wants to ask problem generator what he wants to ask keep thinking that way that the size is keep thinking that way that the size is unknown to me unknown to me there is a kind of strain is given to there is a kind of strain is given to you now you need to give me a random you now you need to give me a random number with an equal probability number with an equal probability okay okay so so now let me give in a small example let's now let me give in a small example let's suppose we have a stream one two three suppose we have a stream one two three four four and we need to and we need to pick random three elements from it so we pick random three elements from it so we will create a resolver okay as per this will create a resolver okay as per this algorithm the the reserver there is an algorithm the the reserver there is an array named as array named as reserver reserver which will first pick which will first pick the first three elements now the the first three elements now the probability probability of picking of picking randomly these elements probability I am randomly these elements probability I am saying probability will be one by three saying probability will be one by three of picking every element okay because of picking every element okay because there are in the reservoirs there are there are in the reservoirs there are three elements and the size is also three elements and the size is also three okay so the picking every element three okay so the picking every element is one by three but now what if 4 came is one by three but now what if 4 came into the picture into the picture so if 4 came into the picture I need to so if 4 came into the picture I need to pick now three elements only so one of pick now three elements only so one of the element will get replaced one of the the element will get replaced one of the element will get replaced if I need to element will get replaced if I need to pick 4. if 4 came into a string I need pick 4. if 4 came into a string I need to replace one of the element from this to replace one of the element from this so what will the probability in this so what will the probability in this case so probability will be nothing so case so probability will be nothing so let's suppose like one for one I will let's suppose like one for one I will see the probability see the probability so for one one stays with the so for one one stays with the probability of one stays with the probability of so what if p o four probability of 4 will not of node go get selected probability of 4 at the time when 4 is not selected because there can be a transform because 4 cannot be selected I need to pick random elements so that will be nothing but one by four because that is the another element came into the stream so which is nothing K plus 1 okay one element came into the stream if two elements came into same so the total size will be K by K plus 2. same will be K plus 3 of 3 elements came now one element came into picture so this will be 1 by K plus 1 this is nothing but K plus 1 okay so the probability of choosing the probability what I am saying po4 is not selected not selected probability of 4 does not get selected is one by four plus what if p what if the fourth element got selected what is the probability of that that is into I need to replace either 2 or into I need to replace either 2 or either 3. either 3. so the probability of that is two by so the probability of that is two by three I can select either 2 or either three I can select either 2 or either three three and if I see this that will came and if I see this that will came three by four now for uh selecting four three by four now for uh selecting four randomly in this randomly in this the server array the randomly picking the server array the randomly picking element a probability of every element element a probability of every element get paid with a probability of three by get paid with a probability of three by four as per the definition of the four as per the definition of the reserver algorithm the reserver reserver algorithm the reserver algorithm is saying make sure each algorithm is saying make sure each element which gets selected should get element which gets selected should get selected with the same probability now selected with the same probability now here the probability of each and every here the probability of each and every element is same which is three by four element is same which is three by four this is the only thing we need to this is the only thing we need to tackle in this problem this is the only tackle in this problem this is the only thing we need to tell the interviewer or thing we need to tell the interviewer or the program generator yes the program generator yes there is a way there is a way if we want to think in that way if there if we want to think in that way if there is a strain given to us with the unknown is a strain given to us with the unknown size I can use Reservoir algorithm and size I can use Reservoir algorithm and in Reservoir algorithm what I will do I in Reservoir algorithm what I will do I will make the probability of selected will make the probability of selected every element same every element same by using this formula now let me write by using this formula now let me write the formula here as well what we the formula here as well what we implemented here implemented here so what what will be the formula came so what what will be the formula came here that is nothing here that is nothing probability of probability of okay what will the uh what will be the okay what will the uh what will be the formula what we did in the element which formula what we did in the element which we need to select we need to select okay so let me uh take that number as x okay so let me uh take that number as x x was in the reserver multiply probability of x K plus I K plus I okay okay so from this formula so from this formula I came up to this I came up to this and the probability of each element get and the probability of each element get picked up is same okay so this is the picked up is same okay so this is the simplest definition of reservoir simplest definition of reservoir algorithm algorithm okay let me give you a brief of this uh okay let me give you a brief of this uh code of this as well code of this as well so I created a head so I created a head okay and I put all the values in my head okay and I put all the values in my head and this will be order of one operation and this will be order of one operation noun in this case the scope is one the noun in this case the scope is one the key the size of the reserver is one and key the size of the reserver is one and here I am here I am selecting uh matte dot random is less selecting uh matte dot random is less than 1.0 here I am doing nothing I am than 1.0 here I am doing nothing I am calculating the probability nothing else okay and every time while current is not equal to null I am incrementing my scope okay and I am updating my chosen value when when the probability is getting satisfied okay and at the end I am returning chosen value okay so this is order of one this whole thing is order of n so the whole time complexity will be order of n the space complexity will be order one okay uh that's it from this current video uh if you like this if this video helped you so like this video And subscribe to this channel thank you very | 2024-03-24 11:55:28 | 382 | 382 Linked List Random Node Reservoir Sampling simple Explanation |
|
jxS9syPWpRM | hey there welcome to pomodora Jo for Thursday November 9th 2023 today we're Thursday November 9th 2023 today we're looking at lead Cod problem 1759 count looking at lead Cod problem 1759 count number of homogeneous substrings this is number of homogeneous substrings this is a medium problem all right so we're a medium problem all right so we're given a string s we need to return the given a string s we need to return the number of homogeneous substrings of s number of homogeneous substrings of s since the answer may be too large return since the answer may be too large return it modulo 10 9th + 7 and then it it modulo 10 9th + 7 and then it describes what this homogeneous describes what this homogeneous substring is a string is considered substring is a string is considered homogeneous if all of the characters in homogeneous if all of the characters in The String are the same so it's just the The String are the same so it's just the same character repeated a substring is a same character repeated a substring is a contiguous sequence of characters within contiguous sequence of characters within a string so that means all the a string so that means all the characters have to be grouped together characters have to be grouped together they have to be next to each they have to be next to each other so let's take a look at this other so let's take a look at this example a BB CC C A A all right so each example a BB CC C A A all right so each one of these characters can be a one of these characters can be a substring by itself so that's a b b c substring by itself so that's a b b c all the way a so that means we have 1 2 all the way a so that means we have 1 2 3 4 5 6 7 8 so that's eight substrings 3 4 5 6 7 8 so that's eight substrings that are homogeneous cuz they're just that are homogeneous cuz they're just one character and that character is the one character and that character is the same as itself so that's eight right same as itself so that's eight right there then we have B and B that's there then we have B and B that's another one so that's nine and then we another one so that's nine and then we have these two C's the first two C's have these two C's the first two C's that makes 10 so the first two C's make that makes 10 so the first two C's make 10 the second two make 11 and then all 10 the second two make 11 and then all three make 12 and then we can group three make 12 and then we can group these two A's together so that gives us these two A's together so that gives us 13 so we have 13 13 so we have 13 total homogeneous total homogeneous substrings all substrings all right cool so let's put 25 minutes on right cool so let's put 25 minutes on the pom over timer and we will get the pom over timer and we will get started so for this one we're going to started so for this one we're going to move fast so let's see what we can do move fast so let's see what we can do here we'll have some result we'll set it here we'll have some result we'll set it equal to zero and at the end we'll equal to zero and at the end we'll return our return our result all right so for this one we'll result all right so for this one we'll start simply we're going to have a start start simply we're going to have a start and an end index so we're going to be and an end index so we're going to be going through our string one pass the going through our string one pass the start index will start the current start index will start the current substring the end index will be the substring the end index will be the index of the end of this current index of the end of this current substring and we'll just count how many substring and we'll just count how many of these characters are the same so of these characters are the same so let's do that so we'll have some start let's do that so we'll have some start set it equal to zero we'll have some end set it equal to zero we'll have some end set that equal to zero now we're going set that equal to zero now we're going through the entire string so while start through the entire string so while start is less than the length of our string S is less than the length of our string S I think we might be using this more than I think we might be using this more than once so let's get that out once so let's get that out here we call it s length or here we call it s length or slen so this is just the length of our slen so this is just the length of our string all right so now while the start string all right so now while the start is less than our string length so first let's get our current character so our current character C is just going to be the string at this start index all right now while we still have the same character so while our string at the end index is equal to C and while end index is still in range and end is also less than our s length then we can keep moving our end down further so our result will increase by one because we found one new substring and then our end will increase by one as well we'll go to the next index all right so we're moving our end further down the line as long as this character is the same as our current character now when we break out of that Loop that means we found a new character or we're at the end of our string that means we have some substring window here we have a start index and an end index so let's get the Delta the difference indices all right now this might take a indices all right now this might take a little bit of explaining so see if I can little bit of explaining so see if I can draw a little diagram here so we've just draw a little diagram here so we've just found some start index and end index found some start index and end index index for a bunch of characters let's index for a bunch of characters let's just say it's a so a a a a a now we have just say it's a so a a a a a now we have some start index that's going to be here some start index that's going to be here start and some end start and some end index that's here okay so let me see if I can explain this so now that we have the start and end index of our range we can see that one unique string would be the entire list of these letters here so that would be 1 2 3 4 5 six so this would be these six A's together would be one unique substring but we also know we could remove one and that's also a unique substring so that's two and then three four five and six so we can get six way so this is a little bit difficult to way so this is a little bit difficult to describe so I'm going to try this with a describe so I'm going to try this with a little diagram here so imagine you have little diagram here so imagine you have eight A's you found your start you kept eight A's you found your start you kept going down the line until you found your going down the line until you found your end you found eight different A's so if end you found eight different A's so if you start it at start and go to end you start it at start and go to end those eight A's will give you one unique those eight A's will give you one unique substring or one homogeneous substring or one homogeneous substring but you can also get one let's substring but you can also get one let's see so all eight will give you one but see so all eight will give you one but then you can remove one from the start then you can remove one from the start let's say and the remaining seven give let's say and the remaining seven give you second one and then you can remove you second one and then you can remove another one and the remaining six give another one and the remaining six give you another one so you can keep removing you another one so you can keep removing one a for each of these A's until you one a for each of these A's until you get down to one a left so you can have 8 get down to one a left so you can have 8 7 6 5 4 3 2 and 1 so that gives you 7 6 5 4 3 2 and 1 so that gives you eight unique substrings for one a that eight unique substrings for one a that you remove you get a unique substring so you remove you get a unique substring so you can remove up to eight A's you get you can remove up to eight A's you get eight unique eight unique substrings so imagine you anchor your substrings so imagine you anchor your end point this a becomes your end point this a becomes your anchor now you can add one a for each anchor now you can add one a for each one of these additional A's so you start one of these additional A's so you start with one a you can add seven more A's so with one a you can add seven more A's so that's going to give you seven that's going to give you seven homogeneous substrings two A's 3 A's homogeneous substrings two A's 3 A's Four A's five up to eight A's that's Four A's five up to eight A's that's seven seven substrings so you start with that substrings so you start with that seven next you change your Anchor Point seven next you change your Anchor Point you anchor at this you anchor at this a a okay so you had seven unique substrings okay so you had seven unique substrings with your previous a now you're going to with your previous a now you're going to Anchor with this a how many A's can you Anchor with this a how many A's can you add to this a well you can only add six add to this a well you can only add six more A's but you can add one at a time more A's but you can add one at a time so that's 6 5 4 3 2 1 so now you have so that's 6 5 4 3 2 1 so now you have seven more seven more substrings so what's the total here well substrings so what's the total here well for every for every a you can basically add the number of a you can basically add the number of A's in that that step so you can start A's in that that step so you can start with eight and then you move down to 7 6 with eight and then you move down to 7 6 5 4 3 2 1 so you can basically add the 5 4 3 2 1 so you can basically add the sum of all of those individual integers sum of all of those individual integers in the range from one to our Delta in the range from one to our Delta here all right I'm hoping this makes here all right I'm hoping this makes sense so what we want to do here is we sense so what we want to do here is we want to increase our result by the sum want to increase our result by the sum of the range from one to our Delta so if we apply this to our example of the eight A's this will give us one a and then 2 A's 3 A's 4 A's 5 A's basically this will take us from 1 through 7 Delta is eight but this range is not inclusive so you go from one through seven and you'll sum those so you'll you'll basically get seven to start with and then you'll add six you'll add five and then add four add three add two add one so that's doing the same thing that we were doing with our moving our end points around I'm hoping this makes sense this is really hard to picture and I'm not describing it super well so now we've gone through while our end is still the same character we're going to update our Endo once it's not the same character anymore or we've run out of characters then we find our Delta we can update our result by summing the range of our Delta and then we do need to reset our start we're going to set our start now to our end point and start again so start will equal end and then we restart all right one quick thing before we do this let's swap this around we want to check our bounds before we try to use them so let's do this well the end is less than the length of our string and then we can use it and our end is equal to our string at this index is equal to hopefully this works okay seems to work let's see if we tests wrong answer okay let's use this tests wrong answer okay let's use this test test case now the wrong answer here is not case now the wrong answer here is not because we calculated wrong look how big because we calculated wrong look how big this answer is going to be it's because this answer is going to be it's because we didn't follow the instructions I need we didn't follow the instructions I need to return this answer modulo 10 the 9th to return this answer modulo 10 the 9th + 7 all right let's do that + 7 all right let's do that here 10 to the 9th plus here 10 to the 9th plus 7 okay try this 7 okay try this again all again all right passing that new test case let's right passing that new test case let's see if we can pass all the see if we can pass all the tests and we pass and let's see we don't tests and we pass and let's see we don't do very well we only beat 28% for 29% do very well we only beat 28% for 29% for runtime 77% for memory all right for runtime 77% for memory all right let's jump back here really quick let's jump back here really quick because there is something we can do because there is something we can do this was more of an example of how you this was more of an example of how you could do this you find the start and end could do this you find the start and end indices and then you calculate these indices and then you calculate these different sort of permutations they not different sort of permutations they not really permutations uh different Windows really permutations uh different Windows within our range so this is one way to within our range so this is one way to do it there is another way to do this do it there is another way to do this and should be faster so let's do that and should be faster so let's do that here let's see we don't need start but here let's see we don't need start but we do need let's see we'll do this all right so for this one we'll need to keep track of our previous character so I still need this starts as string and if this character is equal to string and if this character is equal to the previous character so it's the same the previous character so it's the same character that we just had character that we just had then we're going to keep track of our then we're going to keep track of our character counts so our count here I'll character counts so our count here I'll call it current call it current count will increase by one we have one count will increase by one we have one more length of our more length of our substring so let's have some current substring so let's have some current count out count out here all right now if it's not the same here all right now if it's not the same so we have a new start for our substring so we have a new start for our substring well in that case we have to reset our well in that case we have to reset our current count so our current count gets current count so our current count gets reset to one we're starting out with a reset to one we're starting out with a new single lettered new single lettered substring and then we do have to set our substring and then we do have to set our previous character equal to this previous character equal to this character now here's the trick at this character now here's the trick at this point we can take our entire current point we can take our entire current count and we can add it to our result so count and we can add it to our result so result plus equals our current count so this is doing basically what we did with our Loops but it's doing it in a much more compact way so in this case we're going to keep track of our current count as we're going so our current count is going to keep growing 1 2 3 4 5 6 7 now in our previous implementation we would calculate that same range and sums by finding our start and end indices and then we would add one 2 3 4 5 6 7 we would sum that range now we're actually keeping track of our range in our current C count we're going to start at one it'll go to 2 3 4 so on and so forth and we'll just be adding that entire I guess current count to our result similar to the way we did it with our range in this case we're just doing it as we go all right let's run this see if this is any faster all right seems to work let's see if it's faster though and it's significantly faster so now we're at an 84% for runtime and a 30% for memory so it takes a little bit more memory but it is much faster so this is definitely a better solution all right well we are out of time but I hope you enjoyed this I hope you had fun I hope you learned something I hope you can go out and write better | 2024-03-22 12:34:47 | 1,759 | Pomodoro Joe - LeetCode 1759 - med - |
|
dokjJjEQ1CQ | [Music] hey everyone ali here today's problem is called subsets and it's been asked by these companies now let's take a look at the question together so the problem gave us an integer array called nums which consists of unique elements and it asked us to return all possible subsets or in other words the power set it also said that the solution set must not contain duplicate subsets and at the end it said to return the solution in any order so the order is not important for us it seems pretty easy question but let's look at the given examples also so for example if the input is one two three uh the output is null one two one two three one and three two and three and one two three itself or if the noms array just has one elements one zero the output is null and zero or the array itself it also gave us several constraints the first one is that the length of the numsari is from 1 to 10 and each item in the nums array could be from -10 to 10 and also again all the numbers of gnomes are a are unique so as you can see it's an easy to understand question and i don't think so that we need to talk about that further more so let's jump directly to the algorithm section and see the suitable algorithm to solve this problem with before i run the algorithm and show it step by step to you let me talk a bit about the intuition of this algorithm that i want to use one of the best algorithms for this problem is based on bit masking but what is bit masking in bitmasking we kind of map each subset of the given set to a binary number of size n then in this binary number which is known as bitmask we search for once and whenever we see a 1 we add its corresponding element in the set to the subset so for example here our input set is one two three now i wanna write all three bit binary numbers from zero zero zero to one one one and then look for ones to find out all the subsets so the first number that i have is 0 0 0 and as it doesn't have any 1 so it means our subset is null so it shows the null subsets then we have zero zero one and as you can see we have a one here and now we have to look or compare this binary tree to the set that we have so zeros shows that we do not add them to this offset but one shows that we have to add the corresponding number or element in the set to the subset so here three will be add to our subset or the next number is for example 2 which is 0 1 0 in binary so again we have two zeros and these two zeros map to one and three so we do not add one and three but we add two because the middle uh bit is uh one so we have to add two and it's the same when we have two ones or even three ones we just look to the number of ones and add the corresponding element to subsets so for example if we have uh this binary number we add one and three that corresponds to these two ones and ignore two so the subset would be one and three or when we have one one one we add all the elements of the set to the subset okay now let's run the algorithm to understand it better so first of all we are here and we have all zeros so nothing we have so the current subset is null and the output is also so this is checked then i clear current so this is checked then i clear current and go to the next number and go to the next number so we have one here so we have one here and don't forget that we traverse this and don't forget that we traverse this number number from right to left from right to left so this one corresponds to three in the so this one corresponds to three in the nums array so the current uh subset that nums array so the current uh subset that we have is three we have is three and i also add it to the output let me and i also add it to the output let me erase this and put everything in one erase this and put everything in one place so we can place so we can save more time so save more time so we have we have three three and we clear current and go to the and we clear current and go to the next number next number so it's 0 1 0 and it corresponds to 2 so it's 0 1 0 and it corresponds to 2 so the current subset that we have is 2 so the current subset that we have is 2 and also i add that to the output and also i add that to the output and then we clear the current subset and and then we clear the current subset and go to the next number go to the next number so it is 0 1 1 and so it is 0 1 1 and because we see that from right to left because we see that from right to left so it means so it means that we have a three and two in this that we have a three and two in this subset so it is three and two subset so it is three and two and i also add it to and i also add it to uh the output uh the output then again clear current and go to the then again clear current and go to the next number next number which is one zero zero and which is one zero zero and again we read it from right to left again we read it from right to left so it corresponds to 1 and we add 1 here again we clear it and go to the next one it is one zero one so it has one and so three one so three one and we also add it to the output and we also add it to the output again we clear current and go to the again we clear current and go to the next number it is one one zero so we next number it is one one zero so we have have one and two one and two in the subset two again we clear current again we clear current and go to the next number which is one and go to the next number which is one one one one one and and is the nums array itself so as we expected we found eight subsets uh of the set and you may ask that why i wrote current because it seems you know kind of extra that's because on the code section we need that so i'll cover that later on the code section and now that we understood the algorithm and we have kind of a intuition to that let's jump to the code and see how should we write the suitable code for this algorithm we take the nums array as our input and we return a list of integer lists which shows all the subsets so first of all i just declared the output which is a list of integer lists and then i assigned n with the length of num's array and then we have a nested for loop and in this nested for loop we want to solve the most challenging part of implementing this algorithm but what is the most challenging part of our implementation as you remember from the algorithm section we wrote bitmasks to calculate subsets now the challenge is with the zeros on the left side of each beat mask because we need to store them in the memory to calculate these offsets but we cannot do it simply in the code so normally if i store 0 0 1 for example i lose all the zeros on the left side and the actual value that is being stored in the memory is one to solve this problem we need to use a trick the trick that i used is with the index of the for loop so as you can see in the for loop the range of the i is from 2 to the power of n to 2 to the power of n plus 1. so considering this is the num array as n in this case would be 3 the range of the i would be from 8 to 15. now if i write corresponding binary numbers range of i would be from 1 0 0 0 which is 8 to 1 1 1 1 which is 15. and if we ignore the first bit of these binary numbers i range would be from 0 0 0 to 1 1 1. as a result we have generated all required bitmasks and also saved zeros on the left side of each bitmask in the memory so problem solved now let's see what happens inside this nested for loop so first of all i just created the current list that we use in the algorithm and then i assigned i to the temp then i wrote another for loop and in this for loop we iterate through the nums array to find all the subsets but how do we do this as you remember from the algorithm section we traversed each bitmask from right to left to find ones and added the corresponding numbers to the list of subsets here i want to do it kind of different to make our code more efficient so this time instead of traversing each bit mask we just consider the rightmost bit of each bitmask and then shift each bitmask to the right for example consider that our current bitmask is one zero one so we just look at the rightmost bit which is this one and on each iteration we shift this number to right so for example now we have one zero one and this bit is one on the next iteration this number would be zero one zero and the rightmost bit would be zero and the next one is zero zero one this way we not only traverse every bit of the bitmasks but also save more space and time now let's see that on the code so we take the rightmost bit by this mode 2 and if it's equal to 1 we take its corresponding number from the nums array as one of the subsets elements and then we do the right shift by this line afterwards we add each founded subset to the output list and after we found all the subsets we return the output now let's submit the code in leadcode.com so it's been accepted so it's been accepted and now let's talk about time and space and now let's talk about time and space complexity for time complexity we have a complexity for time complexity we have a nested for loop nested for loop and the boundaries of the first for loop and the boundaries of the first for loop is from 2 to the power of n to 2 to the is from 2 to the power of n to 2 to the power of n plus 1. power of n plus 1. this adds an o of 2 to the power of n to this adds an o of 2 to the power of n to the time complexity the time complexity also on each iteration of the first loop also on each iteration of the first loop we iterate through the whole numbs array we iterate through the whole numbs array once which adds an o of n to the time once which adds an o of n to the time complexity therefore the time complexity complexity therefore the time complexity is o of n times by 2 to the power of n is o of n times by 2 to the power of n and for space complexity in the worst and for space complexity in the worst case we have to keep all the subsets of case we have to keep all the subsets of length n length n thus we have 2 to the power of n subsets thus we have 2 to the power of n subsets of length n which means that the space of length n which means that the space complexity is o of n times by 2 to the complexity is o of n times by 2 to the power of n | 2024-03-20 11:59:50 | 78 | Subsets (LeetCode 78 - Medium) |
|
T_06TtC3E-0 | In the shift of flash lights of liberty, we are this relationship, that soft morning, Samsung, I am the bank relationship, that soft morning, Samsung, I am the bank garage, by the way, here it is 1234, given that it garage, by the way, here it is 1234, given that it can become many of its mornings, DJ can become many of its mornings, DJ Seven is a question in itself, so pay Seven is a question in itself, so pay attention to it, then its 1234 1234 attention to it, then its 1234 1234 attention to it, then its 1234 1234 time starting from two is like two two three two three four earth starting from Mars time is like 3034 husband again starting Sardar Asset Isko So then total if I see then chain * inflation but oo a system But if the NGO people have But if the NGO people have But if the NGO people have exercise number, then exercise number, then I have added one, they I have added one, they can ride in one, two, three, four, skin, 1, this is one, two, can ride in one, two, three, four, skin, 1, this is one, two, this is 123, 1234, then after that, two, three, two, three, four, this is 123, 1234, then after that, two, three, two, three, four, square, three, loot, square, three, loot, cloth. cloth. cloth. Gare Natthu MP Service interval will be less like 130 60 2.5 inch plus dad clams and this is the question demand at the time of service that you physical cleanliness fold this fold this joint this 123 low floor sorry second one ok ok like austrian 687 398 this is our subscribe to now we have passed the increase by tightening the platform hit one left and have passed the decrease you have to give any number within this range to the points if I It is It is It is okay by conferencing the numbers, how will all these Namaskar organizations okay by conferencing the numbers, how will all these Namaskar organizations look pregnant and look pregnant and request a quality solution for this, but for now, request a quality solution for this, but for now, whatever we do, let us do it from Madrid and the whatever we do, let us do it from Madrid and the same complexity will go in square route, then same complexity will go in square route, then not in square and in square law. not in square and in square law. not in square and in square law. specific Baahubali printer, okay, so first of all, our task is to say that whatever will remain with me with the name, what will we do with it, if it is needed, it will come for it, songs, songs, request, share to you, a smudge request, why do you need invent exercise, 200 I think I think I think that drop in plus that drop in plus wave fight exercise should be done and let's see what will wave fight exercise should be done and let's see what will remain. Let's make the index. IDA remain. Let's make the index. IDA CEO, the sign of which is zero percent. Now we CEO, the sign of which is zero percent. Now we get the chords. Point raised, it is get the chords. Point raised, it is asked. So, this is the decision and asked. So, this is the decision and request. request. And And half the request is something like zero six. half the request is something like zero six. half the request is something like zero six. start, if Ali has a problem now, we will make it grand. This is also the judge. These were the last budgets and if we want to see, then first we will make one. Every time we come to tell me tomorrow, we will make one. Is it Will Will Will request from sample to sahu plus request from sample to sahu plus request to us 6.15 to 6.15 we will add request to us 6.15 to 6.15 we will add our sa masala ad that our sa masala ad that use IDX plus plus job hide apps and then use IDX plus plus job hide apps and then increment it. Will increment it. Will we give a good report to those who we give a good report to those who subscribe to me? subscribe to me? subscribe to me? we will carefully look at the code [Music] I have written it till now, you can see it [ Music] Music] Scientist Dr Jhal Ajay has got Jhal Jhal Jhal, Jhal, I have I have yet to fry, we have space yet to fry, we have space yet to fry, we have space helped 1234 and I have a smudge of ours in which how many pages will there be and its form into 4th round at this point divide divide to address and 108 Thomas at justice ne point 560 inductive do this g what do I If the form of this day works, then If the form of this day works, then If the form of this day works, then I request to zero Anniversary for Dhoni's I request to zero Anniversary for Dhoni's request to come, if it bursts, a rally will also be taken request to come, if it bursts, a rally will also be taken out, yes and a prosperous, what are we out, yes and a prosperous, what are we doing, we have a number market song which is doing, we have a number market song which is on 0, som place is equal to two according to on 0, som place is equal to two according to jail, see jail, see jail, see Baby Boy all updated at that time. If this one is in front of me, his 0h index has also been hired. We will press the zero position in the evening. On this question, get arrested in the evening and Di is ok Di is ok Di is ok and this note will be circulated again and it will make ₹100 and this note will be circulated again and it will make ₹100 ok what will we do Sampla ok what will we do Sampla Surgical Strike Name 100 Index and Surgical Strike Name 100 Index and Smallcap Index - 2012 Less than had been done by the Smallcap Index - 2012 Less than had been done by the communities now it will be printed so communities now it will be printed so what will we do 100 index on the vehicle of index what will we do 100 index on the vehicle of index Will put the husband and press the index, the Will put the husband and press the index, the test is fine, now test is fine, now how many tubes will the updater give, then the round how many tubes will the updater give, then the round election will be 9483, election will be 9483, 12336, the updated oil of the evening is 12336, the updated oil of the evening is equal to six, okay, where is it, we will do equal to six, okay, where is it, we will do something about it. something about it. Sadhus of ideas in this award Sadhus of ideas in this award scheme will invest in vouchers 2 3 things scheme will invest in vouchers 2 3 things and one person will melt and give Shiva okay and one person will melt and give Shiva okay understand the name is this and no and number you six understand the name is this and no and number you six plus 4 6 plus form request that this we are plus 4 6 plus form request that this we are here on yours Adidas ki here on yours Adidas ki here on yours Adidas ki heat, it is okay, now let's see, it is equal to a blind person, should I reach waste oil - history, the value like this will not work towards these schools, now we will go on high flame, maintenance had come, we should comment, there is a Since the Since the Since the old number was done its work has been done old number was done its work has been done and in the evening we dished it a little bit to the and in the evening we dished it a little bit to the statutory the studio creature will go again and will statutory the studio creature will go again and will be high so first of all what should we do be high so first of all what should we do destroy James James of one okay who destroy James James of one okay who see this is our waste pimple see this is our waste pimple This style of ours will start listening to the heavy weapon list This style of ours will start listening to the heavy weapon list that the one with the name 'Zahr Naav Chahiye' that the one with the name 'Zahr Naav Chahiye' did 28 in this two time interval and did 28 in this two time interval and presented it here and the address's presented it here and the address's watch plus is okay JK Rowling imitating two to watch plus is okay JK Rowling imitating two to friend WhatsApp to WhatsApp friend WhatsApp to WhatsApp friend WhatsApp to WhatsApp took two three, then set the second spy pipe as your friend, you made its value six backward, then the name is African test and you completed it and set the vestige seven plus two 9 nine vehicles and filled the index with cement and I am like the one from If it is for, now it will go back after, If it is for, now it will go back after, If it is for, now it will go back after, then we will come back and then we will come back and paint on the walls, I have come Mishra, this is done to paint on the walls, I have come Mishra, this is done to us, our jo jaaye reset-1, us, our jo jaaye reset-1, our relationship will break at zero, and where did this of ours our relationship will break at zero, and where did this of ours start, ICICI Back to start, ICICI Back to Tujhe Ko Shampoo Tujhe Ko Shampoo Tujhe Ko Shampoo cost to 13 then the number is 138 3G alum and after that Idea is ok at 2128 after that in the evening did you change the job dress and you set the press release 1017 and how much did the value of idiots become You are right even now, if we see that the efforts have already been made then it will not work quietly, otherwise we will fry the potatoes and leave the vegetables behind, active high cost reduction in this is requested Srila, It will start from I but if you It will start from I but if you It will start from I but if you understand the volume then it is okay but now understand the volume then it is okay but now what will we do from the evidence Request what will we do from the evidence Request name is the weakest to whom the dowry is name is the weakest to whom the dowry is set on this we set it here and value of its index is set on this we set it here and value of its index is tank then the potato will go Excellent tank then the potato will go Excellent high that if she complains is okay high that if she complains is okay high that if she complains is okay who have come, now there will be bake to injured in treatment, so if I could outline, that is, I want my complete Gurjar song, that is the previous one, when I have decided that I have lagged behind, what should I do, I will start it, I will And I will submit the range from left to right, let me And I will submit the range from left to right, let me And I will submit the range from left to right, let me see how see how we will do arrange we will do arrange dot solid in the evening we got rid and dot solid in the evening we got rid and Jai Hind I request to left - 110 Jai Hind I request to left - 110 why close loop that tweet why close loop that tweet keep it according to dating IS ALWAYS THINK WAY TO RIGHT keep it according to dating IS ALWAYS THINK WAY TO RIGHT - - - placid and eye lashes behind it? There is an answer na Kabir Nagar which Mishra will add it from the districts and answer plus request you fennel my last will add it later in the day Junaid hai that serial remind me to see that Congress leaders are making something on our border committee and some romantic Tiwari must have been there because you can know that is why it is plus to this will take [ plus to this will take [ Music] Music] Gaant is a request [ Gaant is a request [ Music] This birth anniversary is on the way The birth anniversary is on the way The Indian is this Indian is this Indian is this what will I do always? Answer: Pacific coast to some models. Then it is written like this. Jhaal's answer is equal Jhaal's suppressed mode. Jhaal's suppressed mode. Research's Research's sirvi seems to be buried below and last sirvi seems to be buried below and last sirvi seems to be buried below and last leaving, turn off the mode of getting the answer done, let's copy a specific copy a specific [Music] [Music] Ajay ko hua tha hua tha and kitna hai jhal, the chances of history are ours to submit this year, we jhal, the chances of history are ours to submit this year, we should stop and it is should stop and it is activated and activated and activated and then if you like the voice of Vishnu Meena, who is optimized by this, then give it once in the comment and inside this we will talk about its time complexity, then if I see the total, then I have entered the name B Plus is the account from number 122 which gives B Plus is the account from number 122 which gives B Plus is the account from number 122 which gives them the wavelength of this, we have a new everyone them the wavelength of this, we have a new everyone which has such rank depth, so I can say which has such rank depth, so I can say that the total fans are crazy about these numbers that the total fans are crazy about these numbers and they will be left behind in sodium and square and they will be left behind in sodium and square law and square stomach. law and square stomach. law and square stomach. is no chicken recipe and some other submissions, we can optimize it which will be using mountain, so if you find it below and once again, I will tell you in this video, thank you very much for Size video mandated to the Size video mandated to the Size video mandated to the spot setting was on | 2024-03-21 11:17:29 | 1,508 | Range Sum of Sorted Subarray Sums| Leetcode 1508| Leetcode Biweekly 30 | Java| Hindi |
|
Nxzstmv_U0U | hey guys Greg here and let's solve valid pal drum so a phrase is a pal drum if pal drum so a phrase is a pal drum if after converting all the uppercase after converting all the uppercase letters into lowercase letters and then letters into lowercase letters and then you remove all the non-alpha numeric you remove all the non-alpha numeric characters it's a palindrome if it reads characters it's a palindrome if it reads the same forwards and backwards and they the same forwards and backwards and they give you a simple definition alpha give you a simple definition alpha numeric means letters and numbers okay numeric means letters and numbers okay so it's saying that the text might have so it's saying that the text might have non-alpha numeric stuff like question non-alpha numeric stuff like question marks and exclamation marks and whatever marks and exclamation marks and whatever so here it actually has some commas in so here it actually has some commas in there and the explanation of why this is there and the explanation of why this is still a pound from is because if you still a pound from is because if you ignore all this stuff so if you ignore ignore all this stuff so if you ignore the commas and the spaces if you just the commas and the spaces if you just look at the letters and the numbers if look at the letters and the numbers if there were any then it's there were any then it's amap and so on forwards and it's amap and so on forwards and it's amap backwards so it's going all the way amap backwards so it's going all the way it's the same forwards and backwards and it's the same forwards and backwards and we're also saying that if it has we're also saying that if it has uppercase letters just convert those to uppercase letters just convert those to lowercase letters first so that actually lowercase letters first so that actually is a pal drum so we return true for race is a pal drum so we return true for race a car will we remove the spaces and so a car will we remove the spaces and so it's just race a car that is not a pal it's just race a car that is not a pal androme there's saying it cuz it's funny androme there's saying it cuz it's funny because race car without the a race car because race car without the a race car is a paland Drome but race a car is not is a paland Drome but race a car is not now the best way to do this is a now the best way to do this is a two-pointer approach where we have a two-pointer approach where we have a pointer L at the left and another pointer L at the left and another pointer r at the end and people are pointer r at the end and people are going to be annoyed when I call this two going to be annoyed when I call this two pointers because I know like they're pointers because I know like they're more so indices it's just this is the more so indices it's just this is the index zero and this is the index n minus index zero and this is the index n minus one where n is the length of the string one where n is the length of the string and sure they're not really pointers but and sure they're not really pointers but like variables are basically pointers so like variables are basically pointers so we're just going to avoid that we're just going to avoid that conversation it's we're going to call conversation it's we're going to call this a two-pointer technique cuz that's this a two-pointer technique cuz that's what it's called now at every single what it's called now at every single step we want to make sure we're looking step we want to make sure we're looking at a lowercase English letter and both at a lowercase English letter and both of them are and so since they are both of them are and so since they are both looking at one well are they equal to looking at one well are they equal to each other if they're not equal to each each other if they're not equal to each other then we could immediately return other then we could immediately return false except they are equal to each false except they are equal to each other okay what does that mean well we other okay what does that mean well we need to keep scanning this forward so we need to keep scanning this forward so we will move L over one and we will move R will move L over one and we will move R over one towards each other now we do over one towards each other now we do the same thing we make sure they looking the same thing we make sure they looking at a lowercase English letter this is at a lowercase English letter this is this sort of is it's an uppercase this sort of is it's an uppercase English letter we'd first kind of make a English letter we'd first kind of make a copy of this and actually just look at copy of this and actually just look at the character of a and so now they're the character of a and so now they're both looking at lowercase English both looking at lowercase English letters are they equal to each other yes letters are they equal to each other yes they are so we need to keep this moving they are so we need to keep this moving forward L is going to move over and R is forward L is going to move over and R is going to move over now again are they going to move over now again are they looking at lowercase English letters or looking at lowercase English letters or a number by the way numbers are fine too a number by the way numbers are fine too uh no it's not here okay so basically we uh no it's not here okay so basically we found that L was looking at a non-alpha found that L was looking at a non-alpha numeric character and so we're actually numeric character and so we're actually going to just move L over and we're not going to just move L over and we're not going to touch R because we just had an going to touch R because we just had an issue with L and so we'll just move L issue with L and so we'll just move L forward okay now they're both looking at forward okay now they're both looking at letters but we just need to make a letters but we just need to make a lowercase version of this we say are lowercase version of this we say are they the same yes they are they're the they the same yes they are they're the same as each other so we will move them same as each other so we will move them forward okay same thing's going to forward okay same thing's going to happen here with L we find that we don't happen here with L we find that we don't like what it's looking at so we're only like what it's looking at so we're only going to move L forward now they are going to move L forward now they are both equal to each other and it's both equal to each other and it's actually at this point where we can actually at this point where we can immediately without even checking the immediately without even checking the spot we can immediately return true at spot we can immediately return true at this point so we can immediately return this point so we can immediately return true if we've gotten this far that means true if we've gotten this far that means it reads the same forwards as it does it reads the same forwards as it does does backwards and then there's just one does backwards and then there's just one other letter here now what you could do other letter here now what you could do if you wanted is just to make sure that if you wanted is just to make sure that like these are still the same character like these are still the same character like you could say like is r equal to l like you could say like is r equal to l yes it is of course because they're the yes it is of course because they're the same letter well you don't really need same letter well you don't really need to do that we can make the Y Loop to do that we can make the Y Loop condition here just while R is less than condition here just while R is less than L okay we don't need to include the L okay we don't need to include the equals to because that's this case here equals to because that's this case here we don't really care we always know that we don't really care we always know that when they're equal to each other of when they're equal to each other of course they're going to be the same course they're going to be the same thing and so that's not going to matter thing and so that's not going to matter okay now this is going to yield a big o okay now this is going to yield a big o of n solution okay we're really just of n solution okay we're really just moving one pointer L over to the right moving one pointer L over to the right and we're moving another pointer R over and we're moving another pointer R over to the left and so that's basically just to the left and so that's basically just going through two times and so we have o going through two times and so we have o of N and the space complexity of this is of N and the space complexity of this is actually a constant solution okay so actually a constant solution okay so time is O of n but space is Big O of one time is O of n but space is Big O of one because we're not storing anything other because we're not storing anything other than these two you know pointers or than these two you know pointers or indices okay so we're going to start by indices okay so we're going to start by getting n is the length of the string getting n is the length of the string and we'll initialize our two pointers and we'll initialize our two pointers we'll get L is going to be zero the we'll get L is going to be zero the first position position and R will be first position position and R will be nus1 that's the last position so then we nus1 that's the last position so then we can just do as we said while L is less can just do as we said while L is less than R if not s at L do is alum if the than R if not s at L do is alum if the character at L is not alpha numeric as character at L is not alpha numeric as we said we just want to move on and so we said we just want to move on and so we'll do L plus equal 1 and we'll we'll do L plus equal 1 and we'll immediately continue okay we don't want immediately continue okay we don't want to worry about R here if L had an issue to worry about R here if L had an issue we're just going to move L over now same we're just going to move L over now same thing for R this is just going to be a thing for R this is just going to be a copy paste if we don't like what R is copy paste if we don't like what R is looking at then we are going to just looking at then we are going to just move our down one okay so we will move move our down one okay so we will move them closer to each other if either of them closer to each other if either of them ran into an issue now at this point them ran into an issue now at this point we know that they're both looking at we know that they're both looking at alpha numeric characters and so we're alpha numeric characters and so we're going to just check if s at l. lower going to just check if s at l. lower okay that's going to convert it to okay that's going to convert it to lowercase that is not equal to S at r. lowercase that is not equal to S at r. lower then we can immediately return lower then we can immediately return false okay so we know they're looking at false okay so we know they're looking at either a number or a letter and if it's either a number or a letter and if it's a number lower actually works on that as a number lower actually works on that as well the string of five. lower is still well the string of five. lower is still just five so we're checking if they are just five so we're checking if they are equal to each other if they are not equal to each other if they are not equal to each other we can immediately equal to each other we can immediately return false cuz it did not read the return false cuz it did not read the same forwards as it did backwards now if same forwards as it did backwards now if they were equal to each other then we they were equal to each other then we will be over here and so we will just will be over here and so we will just move L over one and we will move R down move L over one and we will move R down one at the exact same time if we get one at the exact same time if we get outside of this Loop we must be happy outside of this Loop we must be happy with our result and so it we return true with our result and so it we return true let me just zoom out a second so you can let me just zoom out a second so you can see the code on one screen sorry just to see the code on one screen sorry just to typo I put a lowercase L right there and typo I put a lowercase L right there and that is our solution so as we said the that is our solution so as we said the time complexity of this algorithm is time complexity of this algorithm is going to be Big O of N and the space going to be Big O of N and the space complexity is going to be Big O of one complexity is going to be Big O of one okay we're not storing anything other okay we're not storing anything other than l r and N here all right I hope than l r and N here all right I hope that was helpful drop a like if it was that was helpful drop a like if it was and have a great day guys bye-bye | 2024-03-21 11:23:46 | 125 | Valid Palindrome - Leetcode 125 - Explanation + Python Solution |
|
VlXhHl4fIGk | hello and welcome to another video today we're going to be working on today we're going to be working on combination sum 4. combination sum 4. in this problem you're given an array of in this problem you're given an array of distinct integers in a Target and you distinct integers in a Target and you want to return the number of possible want to return the number of possible combinations that add up to the Target combinations that add up to the Target test cases are generated so the answer test cases are generated so the answer can fit in a 32-bit integer so for this can fit in a 32-bit integer so for this example one two three Target is 4 output example one two three Target is 4 output is seven because we can have one one on is seven because we can have one one on one and one two one two one one three one and one two one two one one three two and one two and three two and one two and three so the first combination sum you didn't want to count combinations multiple times right so one one two and one two one were counted as one combination but now we want it kind of like the ordered matters and so we can have the same we can have different sequences of the same numbers and they want to count as the same combination so the way we're going to want to do that is pretty straightforward we're going to want to do this just like the first one except now when we pick a number so let's say we like pick this number in our new Target is let's say we like choose to pick number two and our new Target is two now we can pick any number again as opposed to before where we said like okay let's just let's just maybe like sort these or something and then if we pick one we can either pick one again or we can pick something higher but when we pick two we can't pick one again because we don't want to go back right so if you don't want to go back you don't want to have something like one one two and two on one but now we do so actually at every single iteration we're gonna have to try every single number right we don't want to keep track of like what we used and what we didn't we're actually going to try every single number so what that's going to look like essentially is something like this so let's say our Target is four we can actually draw this out and draw out all these combinations so let's give us some and we are going to obviously Implement and we are going to obviously Implement caching but let's say our Target's four caching but let's say our Target's four and we have numbers and we have numbers one two three and I'm just gonna say one two three and I'm just gonna say that that for anything that gives us a negative for anything that gives us a negative term number we're not going to include term number we're not going to include because that'll be some base case for us because that'll be some base case for us like you know if the if the number makes like you know if the if the number makes I guess we can actually handle that in I guess we can actually handle that in the actual minimization itself we can the actual minimization itself we can just say like okay look if the number is just say like okay look if the number is um you know if the number that we're um you know if the number that we're subtracting for the Target makes our subtracting for the Target makes our solution negative let's just not even do solution negative let's just not even do that that so so let's figure out essentially how we let's figure out essentially how we would do that right would do that right so let's just go through this so so let's just go through this so essentially we have Target four we can essentially we have Target four we can pick any one of these so let's just say pick any one of these so let's just say we pick one we pick one now our new Target is three but also we now our new Target is three but also we can pick two can pick two so our new Target would be two and we so our new Target would be two and we can pick three can pick three and our new Target would be one and our new Target would be one now when we have three we want to do the now when we have three we want to do the same thing we can pick one our new same thing we can pick one our new Target is two we can take two our new Target is two we can take two our new Target is one and we can pick three and Target is one and we can pick three and our new chart is zero and this is a our new chart is zero and this is a solution solution so now we actually have a solution right so now we actually have a solution right that's one of them that's one of them so now let's go through this so we can so now let's go through this so we can pick one pick one where our new I might run out of space where our new I might run out of space here but we'll see our new Target is one here but we'll see our new Target is one we don't even need to really write which we don't even need to really write which number we picked we just need some more number we picked we just need some more count like how many of these paths lead count like how many of these paths lead to zero so we can pick one our new to zero so we can pick one our new Target is one we can pick two our new Target is one we can pick two our new Target is zero that's also a solution Target is zero that's also a solution and we can't pick three because then and we can't pick three because then we'd be at a negative Target we'd be at a negative Target okay now for this one we can only pick okay now for this one we can only pick one so we would just pick one and our one so we would just pick one and our new Target would be zero we're not I'm new Target would be zero we're not I'm not going to write down what I'm picking not going to write down what I'm picking I'm just gonna write down our targets I'm just gonna write down our targets and then we just count these number of and then we just count these number of zeros right actually zeros right actually a little bit clearer so this is a one a little bit clearer so this is a one because we picked one or the two okay because we picked one or the two okay now for this two we can pick one then now for this two we can pick one then our new Target will be one we can pick our new Target will be one we can pick two under Target will be zero and we two under Target will be zero and we can't pick three then for this one we can't pick three then for this one we will just pick one enter your target will just pick one enter your target will be zero for this one we will pick will be zero for this one we will pick one energy Target will be zero one energy Target will be zero and for this one we'll pick one energy and for this one we'll pick one energy chart equals zero so you can just count chart equals zero so you can just count out like how many different ways you got out like how many different ways you got to the zero so we have one two three to the zero so we have one two three four five six seven and hopefully that's four five six seven and hopefully that's correct correct so that is correct we have seven so that is correct we have seven Solutions Solutions and we don't really care like what and we don't really care like what numbers we use we're just counting numbers we use we're just counting combinations so essentially all we're combinations so essentially all we're doing is it's pretty straightforward doing is it's pretty straightforward right we have some Target we try to subtract then if our new Target is negative that's invalid right so that's going to be like zero or we can just check for that beforehand right like if our new Target is negative we'll just not we'll just not recurse there otherwise recurse with new Target until Target equals zero and then once the target is zero that is like our base case so for a DP solution let's go through it so for DP we need three things right we to base case and three recursive so for the state we're just going to we don't really care about what index we we don't really care about what index we are on because we're going to try the are on because we're going to try the whole array right so we don't really whole array right so we don't really care care okay now for the base case okay now for the base case Target equals zero that means we return Target equals zero that means we return one right because that's like a solution one right because that's like a solution obviously if Target is less than zero if obviously if Target is less than zero if we somehow have that let's return zero we somehow have that let's return zero we could do that as well we could do that as well and then finally we can we can use a and then finally we can we can use a little bit of tricks to end early so little bit of tricks to end early so let's say we have like one two three but let's say we have like one two three but our numbers aren't guaranteed to be our numbers aren't guaranteed to be sorted and the time complexity of this sorted and the time complexity of this solution is going to be uh N squared so solution is going to be uh N squared so we can actually sort our numbers so we we can actually sort our numbers so we can end early so let's say we have some can end early so let's say we have some numbers we'll just sort them so we'll numbers we'll just sort them so we'll just say they'll always be sorted just say they'll always be sorted then what we can say is we can have a then what we can say is we can have a few more base cases here right we few more base cases here right we actually technically let me think actually technically let me think yeah I don't think we need we don't need yeah I don't think we need we don't need all of our base cases yeah I don't think all of our base cases yeah I don't think I don't think we need like all of our I don't think we need like all of our things but this is going to help for our things but this is going to help for our recursive okay so Target is less than recursive okay so Target is less than zero we're going to return zero fine zero we're going to return zero fine now what about the recursive case now what about the recursive case so the recursive case is literally so the recursive case is literally and this is where the Sorting will help and this is where the Sorting will help Loop through numbers subtract Target or after subtract number right right so if our Target here is like four we so if our Target here is like four we would subtract one and so on we get a would subtract one and so on we get a new Target then new Target then we can just to make it more optimal then we can just to make it more optimal then if new Target if new Target is negative is negative we can break the loop we can break the loop otherwise keep going otherwise keep going and I'll explain that in a second so and I'll explain that in a second so let's say our numbers are one two let's say our numbers are one two five six and our Target is four so we five six and our Target is four so we would subtract like one from the Target would subtract like one from the Target and we would get three which is fine and we would get three which is fine right that's fine for new new Target right that's fine for new new Target we'd subtract two from the target we'd we'd subtract two from the target we'd get two totally fine but now we subtract get two totally fine but now we subtract five and we get negative one that means five and we get negative one that means that like five can be in our solution that like five can be in our solution and because we sorted anything past five and because we sorted anything past five also can't be our standard Solutions also can't be our standard Solutions that's what sorting is kind of nice that's what sorting is kind of nice because essentially in hdp we will have because essentially in hdp we will have to Loop through the whole thing but as to Loop through the whole thing but as soon as one number is invalid as soon as soon as one number is invalid as soon as one number is bigger than the target one number is bigger than the target then the whole rest of the arrays and then the whole rest of the arrays and valid so we can save some time there but valid so we can save some time there but that's pretty much it so we just have a that's pretty much it so we just have a state we have a base case where the state we have a base case where the target is zero we return one target is target is zero we return one target is negative then we have an invalid negative then we have an invalid solution then we have this recursive solution then we have this recursive thing where we Loop through every single thing where we Loop through every single number and we subtract it from the number and we subtract it from the number and keep going until we either number and keep going until we either leave through the whole thing or Target leave through the whole thing or Target is negative and then for each one of is negative and then for each one of those we will just add so we will do those we will just add so we will do like a result plus equals DP like a result plus equals DP of using that number right so you add up of using that number right so you add up all of these states together all of these states together so let's say we had one two three four so let's say we had one two three four we would say okay well if our Target is we would say okay well if our Target is four let's say we had we had States one four let's say we had we had States one two three so let's get rid of it two three so let's get rid of it actually so we have this and our Target actually so we have this and our Target is four then we would say like okay our is four then we would say like okay our result is something it's going to be result is something it's going to be result plus equals result plus equals DP of 4 minus 1 and then plus equals DP of 4 minus 1 and then plus equals uh DP of 4 minus two and so on right uh DP of 4 minus two and so on right every possible new state you just add to every possible new state you just add to the result then finally you cash in your the result then finally you cash in your return so also yeah in a base case you return so also yeah in a base case you need caching as always but that's pretty need caching as always but that's pretty much it so it's pretty straightforward much it so it's pretty straightforward all we do is we just Loop through all of all we do is we just Loop through all of our numbers and we just keep trying them our numbers and we just keep trying them all and for anything that works we add all and for anything that works we add it to the result it to the result now we can code now we can code so we are going to sort like I said so we are going to sort like I said because it does help to make it faster because it does help to make it faster we're going to have a visited we're going to have a visited and then we're gonna have a DP and then we're gonna have a DP that takes in a Target that takes in a Target and so if Target and so if Target zero let's return one zero let's return one actually know if Target can be negative actually know if Target can be negative let me think about this let me think about this I don't think it can be I don't think it can be yeah because we're just going to check yeah because we're just going to check for that before but but you can also for that before but but you can also check uh yeah we're gonna check out that check uh yeah we're gonna check out that before to end our Loop prematurely so I before to end our Loop prematurely so I don't think our Target can ever be don't think our Target can ever be negative because we can check for that negative because we can check for that before but we're gonna see if we have an before but we're gonna see if we have an error so we also have to check for error so we also have to check for visited so if Target visited so if Target and visited and visited let's return visited let's return visited okay now we are going to do our Loop so we're gonna make the results equal to zero and we're just going to say four number in numbers if the target is less than the number meaning Target minus the number will be negative let's just break because that's never going to be a valve solution so that's why you don't have to check for negative Target because we're just going to be checking here which will allow us to under Loop prematurely and it'll save us a lot of time then we just do res p p Target Target number and then we need to just return and then we need to just return DP DP using the original Target using the original Target here okay let's see what happens I don't here okay let's see what happens I don't think we can get negative so I think think we can get negative so I think this should be fine yeah so you can see this should be fine yeah so you can see it's pretty efficient runs all over the it's pretty efficient runs all over the place kinda I think most solutions are place kinda I think most solutions are kind of similar so you can see it's kind kind of similar so you can see it's kind of inconsistent as far as the results of inconsistent as far as the results but pretty good but pretty good so let's think about the time and space so let's think about the time and space here so obviously for the Sorting that's already n log n but it's not going to matter because this target can be so so if it can be up to a thousand this is if it can be up to a thousand this is going to be Target here going to be Target here but it's also going to be times the but it's also going to be times the length of mountains right so if you length of mountains right so if you think about it think about it for an N log n solution quote unquote for an N log n solution quote unquote like sorting this is going to be n log n like sorting this is going to be n log n which this is like the end part right so which this is like the end part right so basically we're saying this is better basically we're saying this is better than or yeah sorting is basically free than or yeah sorting is basically free as long as Target as long as Target is greater than log of 200 right is greater than log of 200 right and and yeah and log of 200 is like yeah and log of 200 is like exactly but you know somewhere around exactly but you know somewhere around 10. so as long as the target is greater 10. so as long as the target is greater than 10 this is better and once the than 10 this is better and once the target gets small enough this is target gets small enough this is basically the linear time anyway so the basically the linear time anyway so the store is going to take longer than the store is going to take longer than the um um yeah the sword is gonna start sword is yeah the sword is gonna start sword is gonna take less time than this part gonna take less time than this part for unless it's for a very small number for unless it's for a very small number in which case it doesn't really matter in which case it doesn't really matter because either way it will be fast so because either way it will be fast so you if you wanted to you could get rid you if you wanted to you could get rid of this sort and you could uh could get of this sort and you could uh could get rid of the sore and you could get rid of rid of the sore and you could get rid of the break and then you could say if the break and then you could say if Target is less than zero return zero Target is less than zero return zero this should also technically work I this should also technically work I believe believe it will just theoretically be slower it will just theoretically be slower yeah it is a little bit better the other way or you know a decent amount better usually so and there we go okay so that's going to be roughly this you you can if you want to you can say like well you know maybe maybe the sort might take longer so you could say like Plus on login if you want to which would make some sense but yeah so assuming your target is bigger than the login which it almost always is it's going to be faster that way okay and for the space um so we have this visited and visited um so we have this visited and visited can have any number up to Target so the can have any number up to Target so the space is just going to be oh of Target space is just going to be oh of Target oh yeah oh yeah and I think uh that's actually gonna be and I think uh that's actually gonna be for this problem so not too bad and then for this problem so not too bad and then they asked what if negative numbers are they asked what if negative numbers are allowed how does this change a problem allowed how does this change a problem what limitations do we need to add so what limitations do we need to add so actually I believe with the Sorting I think it is just fine I want to say like we can test some stuff but I want to say it would just work for anything because we're kind of doing the same thing as long as we sort I think it would be totally fine and it would work right there you could test it on your own if you wanted to I'm not going to do this video but yeah it's gonna be it for this one uh and uh if you like this video please like it and subscribe Channel for a lot so I'll see you in the next one thanks | 2024-03-24 11:44:35 | 377 | Combination Sum IV - LeetCode 377 - Python - Memoization |
|
00qH6CfmB-M | hey yo how's it going guys babybear4812 here coming at you one more time here coming at you one more time today with uh what i think is a tricky today with uh what i think is a tricky problem actually the problem is evaluate problem actually the problem is evaluate division problem number 399 only code division problem number 399 only code it's tagged as medium uh i i really it's tagged as medium uh i i really think this one should be think this one should be tagged hard but i don't make the rules tagged hard but i don't make the rules uh so it's it's currently being asked by uh so it's it's currently being asked by amazon google facebook bloomberg and amazon google facebook bloomberg and microsoft uh microsoft uh you've heard of some of those companies you've heard of some of those companies and i think what makes it and i think what makes it tricky in part at least um is because tricky in part at least um is because i think that it's a bit deceiving in the i think that it's a bit deceiving in the sense that it puts those of you with the sense that it puts those of you with the uh who are mathematically inclined at a uh who are mathematically inclined at a slight disadvantage i think usually an slight disadvantage i think usually an advantage but advantage but this time around i think it makes it a this time around i think it makes it a bit trickier because of where your kind bit trickier because of where your kind of head goes or may go by default of head goes or may go by default so let's uh let's take a look at the so let's uh let's take a look at the question then we'll dive into the question then we'll dive into the solution solution so it says we're given equations in the so it says we're given equations in the form a over b equals k form a over b equals k where a and b are variables represented where a and b are variables represented as strings k is a real number and it's a as strings k is a real number and it's a floating point number okay floating point number okay given some queries return the answers if given some queries return the answers if the answer does not exist return the answer does not exist return negative 1.0 negative 1.0 they do tell us the input is always they do tell us the input is always valid we can assume that our value valid we can assume that our value we're evaluating queries uh with no we're evaluating queries uh with no division by zero no contradiction division by zero no contradiction none of that stuff so we don't need to none of that stuff so we don't need to worry about error checking and all that worry about error checking and all that um um i i think this would get a bit messier i i think this would get a bit messier if we if we needed to so we don't really if we if we needed to so we don't really need to worry about that here need to worry about that here so uh we're given equations values so uh we're given equations values queries and queries and and obviously the expected uh result so and obviously the expected uh result so uh what i've actually done is i've uh what i've actually done is i've copied it over here copied it over here because i think it's a bit easier to because i think it's a bit easier to look at this way um and and let's kind look at this way um and and let's kind of take a quick walk through of what of take a quick walk through of what the you know how to understand the input the you know how to understand the input and then ultimately what we want is and then ultimately what we want is output and and afterwards you know output and and afterwards you know how we're going to get there so first how we're going to get there so first thing we're given is thing we're given is is uh i wrote as an e for equation so is uh i wrote as an e for equation so we're told we've got these two equations we're told we've got these two equations a divided by or they're not equations a divided by or they're not equations yet but yet but statements you know a this represents a statements you know a this represents a divided by b this represents b divided divided by b this represents b divided by c by c the equation would be along with this the equation would be along with this values array you're given values array you're given is a divided by b equals two b divided is a divided by b equals two b divided by c by c equals three okay or 2.0 3.0 equals three okay or 2.0 3.0 these are the queries that are going to these are the queries that are going to be running as input okay be running as input okay so in this specific example what we need so in this specific example what we need to do to do is to say let's evaluate what would a is to say let's evaluate what would a divided by cv divided by cv a divided by c turns out to be six so we a divided by c turns out to be six so we expect the output to be six expect the output to be six b divided by a we expect to be 0.5 b divided by a we expect to be 0.5 so on and so forth we return everything so on and so forth we return everything in this in this result in this in this result okay over here so okay over here so the reason i think this may put some of the reason i think this may put some of you mathematically inclined folks you mathematically inclined folks uh at a disadvantage is because your uh at a disadvantage is because your head head may originally go kind of like minded to may originally go kind of like minded to like oh this looks like linear algebra like oh this looks like linear algebra so so it's like well i've got you know if i it's like well i've got you know if i know that a over b is is two and know that a over b is is two and and b over c here maybe just algebra not and b over c here maybe just algebra not even linear algebra per se even linear algebra per se um b over c is three well i can kind of um b over c is three well i can kind of you know maybe try to move variables you know maybe try to move variables around set the equations equal somehow around set the equations equal somehow and then and then maybe you realize that you know a or b maybe you realize that you know a or b times b over c is just times b over c is just you know those cancel out so you get a you know those cancel out so you get a over c equals six it's like okay cool so over c equals six it's like okay cool so like like you're picturing these systems of you're picturing these systems of equations in your head and um and so you're picturing these these equations in your head and figuring out how to work those out mathematically and if you if you try to take that approach i i think you'll be sitting here and kind of scratching your head for a while um and and that's why i think that this one is is tough and not obvious because it's easy for your head to go here keeping in mind the context that we have given you know we're on lead code you're preparing for your tech interview we need to think about what we're going to do um in terms of like do there exist data structures that can kind of help us out here okay and so keep that in the back of your mind as we as we kind of walk through i just want to look at a few cases of this output first so we get a real holistic understanding then we'll jump back to this point on on what we need to do with data structures here all right so like i said it you know a over c is six okay we kind of mathematically put that together here b divided by a well we have a divided by b which we we know is 2.0 that's a very ugly two that looks like a one all the way 2.0 um we so b over a must be reciprocal half it's like okay fine simple enough then we get ae well we realize like e is not really in there and so we're returning negative one here because as for instructions it said uh we return negative 1.0 if the answer does not exist so we're like okay so this is one scenario maybe i'll kind of put a star here so we got regular division that's one scenario uh division with an unknown variable like we didn't have an e in here so we're just gonna return negative one when we see a variable there so you might start to to think like okay maybe i've got a i've got to keep these variables for maybe like a set or a hash table uh that'll tell me all the different letters or variables that i come across and um and then you know if i see one that i don't like i'll just spit out negative one no matter what a divided by a so number divided by itself is is 1.0 it's like all right cool that's that's easy enough so maybe we put a star there um and then we get x and x we're returning negative 1 here even though we we kind of know that any number divided by itself barring 0 of course will give us 1 but because x is unknown in the context of the variables we're given here we will return negative 1. so it looks like three things are two things three things are happening here one thing that's happening is when we've got you know one scenario is if we say uh the numbers aren't even in the set so first we have of check the numbers in b okay that's easy we return negative one okay that's easy we return negative one um um otherwise i think the really simple case otherwise i think the really simple case is a number divided by itself is a number divided by itself so maybe i'll say you know uh shorthand so maybe i'll say you know uh shorthand a divided by a a divided by a we have something like that we can we have something like that we can return one and when i say return i mean return one and when i say return i mean i just add it to this uh this results i just add it to this uh this results array here and then the third one which array here and then the third one which is really where the bulk of the work is is really where the bulk of the work is is actually going to be you know regular is actually going to be you know regular division and and this is where we're division and and this is where we're going to make our going to make our make our money that is extremely ugly make our money that is extremely ugly writing put a question mark here for now writing put a question mark here for now so like i said regular division this is so like i said regular division this is where things just get where things just get weird so again this linear algebra weird so again this linear algebra approach approach ain't gonna help all so much so we think ain't gonna help all so much so we think ourselves and especially when you're ourselves and especially when you're when you're looking at this kind of when you're looking at this kind of cross multiplication here it cross multiplication here it kind of looks like well you know if i kind of looks like well you know if i know what a over b is and i know what b know what a over b is and i know what b over c is over c is is there a way for me to get from a is there a way for me to get from a directly to c directly to c this is what kind of did it for me when this is what kind of did it for me when i tried to do this and i noticed the i tried to do this and i noticed the cross multiplication that cross multiplication that these items cancel each other out it was these items cancel each other out it was like well i can get to a like well i can get to a or i can get from a to c via b or i can get from a to c via b potentially and i think that's kind of potentially and i think that's kind of the key in the key in in kind of recognizing that in fact we in kind of recognizing that in fact we may need some sort of may need some sort of like a graph structure to order this like a graph structure to order this question question and and this is like i think that's the and and this is like i think that's the crux of the problem crux of the problem is it's i don't think it's obvious at is it's i don't think it's obvious at least it definitely wasn't to me least it definitely wasn't to me um that like a standard evaluate um that like a standard evaluate division problem division problem we would actually solve with the graph we would actually solve with the graph so let's think about that for a second so let's think about that for a second you know if i you know if i i'm going to keep i'm going to keep i'm going to keep i'm going to keep using this example i've got a b b c or 2 using this example i've got a b b c or 2 and 3. and 3. if i've got let's say i got a if i've got let's say i got a if i try to turn that into a graph i if i try to turn that into a graph i have a have a so if i think about a divided by b well you said that was going to give us 2.0 okay cool and we know b divided by c is 3.0 right and what did we say a divided by c was well a divided by c when it was 6.0 and so it actually it turns out if you kind of follow this logic that if we multiply every value along the way from start to finish we get the value of that of that division that we want and i think that's pretty damn cool like again i don't think that's intuitive at all uh it wasn't for me like i said i'm sure there's at least one person watching who like it wasn't intuitive for them either but that's that's the key here to excuse me excuse me again excuse me excuse me again the the interesting thing is is that we the the interesting thing is is that we can actually can actually also notice that let's reverse this also notice that let's reverse this relationship so relationship so i can go b divided by a and all that i can go b divided by a and all that will be is the reciprocal of this value will be is the reciprocal of this value so this will be 0.5 so this will be 0.5 and and this one c divided by b and and this one c divided by b will give me uh right 1 over 3 which will give me uh right 1 over 3 which would be zero point would be zero point uh three three i'll leave it at zero uh three three i'll leave it at zero point three three right which is the point three three right which is the float float so all of a sudden i can do a divided by so all of a sudden i can do a divided by b a over c b a over c e over a b over c c over a c over b e over a b over c c over a c over b i can do all three of these once i set i can do all three of these once i set them up in this in this graph structure them up in this in this graph structure and so that is and so that is like understanding this and getting to like understanding this and getting to here is a large chunk of the work the here is a large chunk of the work the coding is a bit involved as well coding is a bit involved as well i'll be honest so maybe this might be a i'll be honest so maybe this might be a bit of a longer video probably in around bit of a longer video probably in around the the 20 minute mark or so but 20 minute mark or so but yeah this is like this is what we need yeah this is like this is what we need to get we need to understand that there to get we need to understand that there are three different scenarios that we are three different scenarios that we deal with deal with and that we we can actually represent and that we we can actually represent these these not the queries but the equations and not the queries but the equations and the values that we're given in the the values that we're given in the context context of a i guess bi-directed graph in a way of a i guess bi-directed graph in a way so yeah the um the way we're going to so yeah the um the way we're going to want to think about setting this up by want to think about setting this up by the way the way you can pause the video if you want to you can pause the video if you want to think about how you would set this graph think about how you would set this graph up up um i i'd like to be an adjacency list i um i i'd like to be an adjacency list i think those are the most intuitive think those are the most intuitive and maybe we can do something like this and maybe we can do something like this as we're adding items in we can kind of as we're adding items in we can kind of say well say well um i have a here and and what do i want um i have a here and and what do i want my my my value to be well you know age is just my value to be well you know age is just pointing to b right now but there's no pointing to b right now but there's no reason why there couldn't be another reason why there couldn't be another variable d variable d in here and you know maybe we're given in here and you know maybe we're given what a divided by d is and so what a divided by d is and so it could have many more um many more it could have many more um many more other other kind of neighbors so typically we put kind of neighbors so typically we put that in an array of source right that in an array of source right the issue is if we want to actually the issue is if we want to actually triggers through triggers through all of these and while we're traversing all of these and while we're traversing to know the value of the division at to know the value of the division at every step which is what we need every step which is what we need then i would argue we actually need to then i would argue we actually need to put one more nested object in here so put one more nested object in here so here we have a is connected to b and here we have a is connected to b and then a then a b 2.0 would be the value b 2.0 would be the value okay my next one that i would have okay my next one that i would have would be something like you know this is would be something like you know this is how do i how do i there uh then we've got b so from b there uh then we've got b so from b we can actually go to two places we can we can actually go to two places we can go to a go to a which will give us 0.5 or which will give us 0.5 or you can go to c which will give us 3.0 you can go to c which will give us 3.0 right b divided by c was three right b divided by c was three so that's the the b value entry and then so that's the the b value entry and then i i think you get it for c i i think you get it for c which we're gonna go to b n and uh which we're gonna go to b n and uh yeah equals to c c goes to b so when yeah equals to c c goes to b so when we're adding these we're adding these in with every kind of a equation value in with every kind of a equation value that we visit we also gotta add its that we visit we also gotta add its reciprocal and so we can we can jump in reciprocal and so we can we can jump in any direction all right any direction all right so that's what we're gonna do we're so that's what we're gonna do we're going to going to we're going to build this graph we're we're going to build this graph we're going to set ourselves up through these going to set ourselves up through these three scenarios three scenarios and then we're going to think about when and then we're going to think about when we actually need to do the division well we actually need to do the division well actually we're not going to think but we actually we're not going to think but we kind of went through it we realized that kind of went through it we realized that to do this division we're going to have to do this division we're going to have to do some graph reversing to do some graph reversing the solution i'm going to implement is the solution i'm going to implement is dfs so i believe you can implement the dfs so i believe you can implement the same thing with same thing with uh with bfs i just find efs a touch more uh with bfs i just find efs a touch more intuitive all right so what we're going intuitive all right so what we're going to end up doing here is we're going to to end up doing here is we're going to call some sort of a call some sort of a recursive helper function to to do a dfs recursive helper function to to do a dfs for us for us to see if we can actually get to where to see if we can actually get to where we want to get so we want to get so uh at this point i've talked long enough uh at this point i've talked long enough i'm sure you're sick of me already i'm sure you're sick of me already let's uh let's jump into the code and let's uh let's jump into the code and see what we can make happen there see what we can make happen there so i'll move this over and give so i'll move this over and give ourselves plenty of space here ourselves plenty of space here a couple things we want to do one was we a couple things we want to do one was we wanted to say make graph wanted to say make graph and then two was do calculations all and then two was do calculations all right right so um i'm not going to do any error so um i'm not going to do any error checking here because we were told the checking here because we were told the input would be valid and all that input would be valid and all that so we're kind of safe there so the graph so we're kind of safe there so the graph we said that we we said that we wanted was there's just going to be a wanted was there's just going to be a dictionary and dictionary and i i know there's a way to do this with i i i know there's a way to do this with i think like default uh think like default uh dictionaries and and maybe grouping by dictionaries and and maybe grouping by using the zip functions let's make this using the zip functions let's make this a slightly bit less verbose but i'm a slightly bit less verbose but i'm going to stick with the first principles going to stick with the first principles here and really here and really build it out from scratch okay um build it out from scratch okay um so what we want to do is this is we want so what we want to do is this is we want to start by going through all the to start by going through all the equations equations um in uh in order to um in uh in order to the equations and the values excuse me the equations and the values excuse me so we can see so we can see um so we can see like who the what the um so we can see like who the what the neighbors are neighbors are the neighbors really like where the the neighbors really like where the division is happening with the values of division is happening with the values of that division that division so what i'm going to do is this is i'm so what i'm going to do is this is i'm going to say going to say so typically what i want to do you know so typically what i want to do you know in equations comes in this in equations comes in this in this nested array format so what i in this nested array format so what i could do is something like i'll call could do is something like i'll call them them num and and then for numerator and num and and then for numerator and denominator uh denominator uh in equations okay in equations okay except i also want the values as well so except i also want the values as well so i again i think i again i think you can definitely zip these like the you can definitely zip these like the equations and the values together but equations and the values together but what i think i'm going to do is i'm what i think i'm going to do is i'm actually going to actually going to track the index with i and i'm going to track the index with i and i'm going to i'm going to have to put these in i'm going to have to put these in parentheses so then we can actually parentheses so then we can actually uh enumerate through equations what this uh enumerate through equations what this allows to do is basically say allows to do is basically say look at the index i'm in for each look at the index i'm in for each equation so i can find the corresponding equation so i can find the corresponding value value and then get the numerator and and then get the numerator and denominator as well which which kind of denominator as well which which kind of come in this come in this in this one package here so what i want in this one package here so what i want to say is this to say is this is if my numerator is not in my graph is if my numerator is not in my graph then what i want to do is i want to say then what i want to do is i want to say graph numerator is going to be some graph numerator is going to be some empty object for now then or if it's empty object for now then or if it's already in there already in there we can say that graph the numerator is we can say that graph the numerator is going to have going to have so this is now referring to an object so this is now referring to an object right that object we want to have right that object we want to have a key of denominator and the value that a key of denominator and the value that we want there is the actual value of the we want there is the actual value of the of the division so what we'll do is of the division so what we'll do is we'll say we'll say equals values at equals values at i right and so the other thing that we i right and so the other thing that we want to do also is want to do also is is to do the other way around now so is to do the other way around now so we're doing numerator denominator and we're doing numerator denominator and then we're going to do then we're going to do denominator over numerator so we'll say denominator over numerator so we'll say if denominator not a graph if denominator not a graph then graph the denominator is also going then graph the denominator is also going to be some empty object to be some empty object and finally um graph denominator and finally um graph denominator at numerator now again pointing the at numerator now again pointing the other way around uh will be other way around uh will be oops will be equal to 1 divided by oops will be equal to 1 divided by values of i so just the reciprocal and values of i so just the reciprocal and that's all we need to do that's going to that's all we need to do that's going to be be the adjacency list for our the adjacency list for our excuse me for our graph uh again points excuse me for our graph uh again points both ways both ways and actually tells us what the values of and actually tells us what the values of the division is the division is now here's the the second part was to now here's the the second part was to actually do actually do calculations okay so we're going to need calculations okay so we're going to need to have some sort of to have some sort of i'll call it a result right and i'm i'll call it a result right and i'm super creative uh we're going to return super creative uh we're going to return the result after we the result after we walk through well all these queries so walk through well all these queries so the the queries are basically as follows the the queries are basically as follows we are going to want to say uh for maybe we are going to want to say uh for maybe i'll call the numerator and denominator i'll call the numerator and denominator again again in in queries right so queries is also a in in queries right so queries is also a yep it's a nested array so we can say yep it's a nested array so we can say for for numerator and denominator for for numerator and denominator in in queries all right in in queries all right and so here we said there were three and so here we said there were three scenarios and the first scenario we had scenarios and the first scenario we had just double check uh so if the number is just double check uh so if the number is not in a set if we're dividing a number not in a set if we're dividing a number by itself or regular division by itself or regular division so we can say uh if num so we can say uh if num not in graph or then not in graph not in graph or then not in graph then what we want is to then what we want is to resolve that append a float of negative resolve that append a float of negative one or a negative 1.0 one or a negative 1.0 otherwise we said if if otherwise we said if if the numerator equals the denominator the numerator equals the denominator then result not append then result not append one okay if only the question was this one okay if only the question was this easy easy but we got to do that last part else but we got to do that last part else what we're going to want to do is we're what we're going to want to do is we're going to you know basically result that going to you know basically result that append append um the result of a dfs call so self.dfs um the result of a dfs call so self.dfs and we'll figure out what the heck we and we'll figure out what the heck we want to pass into there want to pass into there eventually this will run through all the eventually this will run through all the queries and we will spit out the final queries and we will spit out the final result result so to actually make this this dfs graph so to actually make this this dfs graph we're gonna have to we're gonna have to push in a couple things one is going to push in a couple things one is going to be the graph i'm sorry i said dfs graph be the graph i'm sorry i said dfs graph dfs dfs traversal of a graph first thing we're traversal of a graph first thing we're going to put in is the graph itself going to put in is the graph itself we're going to want the numerator and we're going to want the numerator and the denominator which will kind of act the denominator which will kind of act as our as our starting and ending point we're going to starting and ending point we're going to want to keep a product want to keep a product going because we said as we jump from going because we said as we jump from one end to the next we need to multiply one end to the next we need to multiply by whatever by whatever the result of the division is uh so i'll the result of the division is uh so i'll keep that as as keep that as as one for now and we're going to keep it one for now and we're going to keep it out of one so once we start multiplying out of one so once we start multiplying things they're not things they're not there's no kind of value that's already there's no kind of value that's already altering the modification altering the modification finally the last thing i'm going to pass finally the last thing i'm going to pass in is actually going to be a visited in is actually going to be a visited uh set or array so i'll create a new set uh set or array so i'll create a new set here here and we'll use that just to keep track of and we'll use that just to keep track of the nodes we've already visited so we the nodes we've already visited so we don't end up don't end up getting in cycles during our dfs so getting in cycles during our dfs so this is actually it apart from obviously this is actually it apart from obviously this helper function which we're going this helper function which we're going to write now to write now this is the the bulk and the entirety of this is the the bulk and the entirety of what's going to go into this main what's going to go into this main calc equation method so now for the calc equation method so now for the actual implementation here the first actual implementation here the first thing we're going to want to do is to thing we're going to want to do is to say say let's take our visited set and add to it let's take our visited set and add to it the the the numerator or maybe our our starting the numerator or maybe our our starting point maybe i'll call this start and end point maybe i'll call this start and end i feel like that might be a a bit more i feel like that might be a a bit more intuitive intuitive um once we do that we also want to say um once we do that we also want to say let me um let me think let me um let me think let me get all my neighbors from this let me get all my neighbors from this from this actual point so from this actual point so i want to get all right so let's get this thing implemented first thing we want to do is to take the visited set and add to it the starting point and with that starting point we want to get its neighbors as well so we can say something like neighbors equals um this will be uh excuse me graph of start all right and then we've actually got um what i'm going to do is i'm actually going to set an answer variable i'll set that answer variable to the negative one by default and we're eventually going to return it because what we want to do is to basically do our dfs and search through all the different possible paths if we don't ever end up finding and doing any multiplication that we need this answer is going to stay as negative 1 so that's what we're going to return otherwise otherwise we're going to return the answer itself so we'll we'll modify that variable in just a few steps really what we want to ask ourselves first is whether or not the point that we want to get to this end is in our neighbor set right now or in our neighbor object so if the end is in neighbors then all that we want to do is we want to see that the answer is going to equal to the product we have so far times like the value to get to this to this end here so times i guess it would be neighbors end all right that's it otherwise so we wouldn't get into this if this was the case we wouldn't get into this else statement we would jump and return the answer otherwise we're now essentially going to need to loop through all of the neighbors and check each one of them individually now the neighbors uh exist within an object themselves because graph of star rate is is another object so what we can do is we can say for a neighbor and value in and we'll do neighbors dot items so this is actually going to return a nested array of key value pairs from this object and what we're going to say is this if there's a neighbor that we haven't visited yet go visit it okay so if uh neighbor not in visited then we want to go visit it in particular we are curious like like we're curious in knowing what the answer is going to be after we visit it once we do this multiplication as we go so i'm going to say that the answer is going to equal self d of s and we're passing in the graph the neighbor is our new starting point the end point is still the same uh the product we're going to keep and we're going to multiply it by the current value that we're at right now okay so we can take that value into the count and then keep going and finally be visited okay now we do all this work once we jump out of here we want to know did we actually find an answer or not well we found an answer if we're no longer a negative one here right so if answer is not equal to negative one then we're like oh or float of negative one like oh sweet like i i found an answer i don't i don't want to keep checking any more neighbors like i got to where i needed to go so i'm gonna break once i break that'll take me out here we're going to return our answer and everybody's happy and that's it guys i want to leave like the code here so you can see the whole thing in one screenshot let me let me run it first and just make sure i didn't make any silly mistakes but i think we'll be good that should work i'm gonna submit it there we go 98.82 um yeah so just a quick recap what we did was we essentially noticed that this is a problem that we need to answer using graphs and i hope the intuition we kind of built up there helped convince you of that then we had to make the graph itself we had to do the calculations there were three different kind of conditions for combinations that we had to do and finally to do that that last one we had to do it by doing a dfs through the graph that we created so this was our quick little dfs that we put together uh i know this was a long video i think it was a problem that deserves a long video because i i don't think it's it's intuitive at all so i hope you guys enjoyed it i hope you guys found it useful if you did you know what to do you know what to click you know who to share with um yeah and if not or you know if you have any other comments questions suggestions drop them down below as always i'm happy to address them and i will see you guys next time | 2024-03-24 12:19:09 | 399 | EVALUATE DIVISION (Leetcode) - Code & Whiteboard |
|
SgHRFZDHtrE | hey hey everybody this is Larry this is day 18 of the leco d challenge hit the day 18 of the leco d challenge hit the like button hit the Subscribe button like button hit the Subscribe button join me on Discord let me know what you join me on Discord let me know what you think about today's F and uh yeah if think about today's F and uh yeah if you're celebrating it or maybe I'm a you're celebrating it or maybe I'm a little bit late anyway happy St little bit late anyway happy St Patrick's Day uh New York it's Patrick's Day uh New York it's apparently a big apparently a big thing chaos thing chaos everywhere but um all right let's take a everywhere but um all right let's take a look at today's form 452 hope everyone look at today's form 452 hope everyone had a good weekend and hope everyone's had a good weekend and hope everyone's uh you know upcoming week is as good as uh you know upcoming week is as good as I don't know it's just good I guess but I don't know it's just good I guess but yeah uh let's take a yeah uh let's take a look not going to lie if I wub my eyes a look not going to lie if I wub my eyes a lot my apologies I'm having lot my apologies I'm having um it's spring is here so or more or um it's spring is here so or more or less I guess so I'm just having allergy less I guess so I'm just having allergy stuff and yeah I may sneeze a lot during stuff and yeah I may sneeze a lot during the video apologies ahead of time but the video apologies ahead of time but yeah let's take a look 452 minimum yeah let's take a look 452 minimum number of arrows to burst balloons there number of arrows to burst balloons there spal balloons taped to fat worldall that spal balloons taped to fat worldall that at represent XY point the balloons at represent XY point the balloons represent the 2D aray X start y start or represent the 2D aray X start y start or sorry X start xn Den know a balloon CR sorry X start xn Den know a balloon CR horizontal diameter stretch from X to xn horizontal diameter stretch from X to xn horizontal diameter okay yeah you do not horizontal diameter okay yeah you do not know the exact Y coordinates of the know the exact Y coordinates of the balloon I always going be shot positive balloon I always going be shot positive uh vertically in a positive y direction uh vertically in a positive y direction from different points on X a b from different points on X a b x okay so it's not really a 2d thing I x okay so it's not really a 2d thing I mean you could think of as 2D but okay mean you could think of as 2D but okay so then you have 10 to 16 so this so then you have 10 to 16 so this is kind of the same idea that we've been is kind of the same idea that we've been playing with the last couple of days playing with the last couple of days with Intero so so basically what what is with Intero so so basically what what is the actual question right so you have the actual question right so you have these points minimum number of hours these points minimum number of hours that must be shot to burst all balloons that must be shot to burst all balloons oh that's a fun oh that's a fun one one [Music] um so you may be tempted uh the reason why I'm kind of just pausing is a little is because this is actually kind of trickier than um you may imagine it to be maybe not I don't know but the idea here is that uh first of all greedy doesn't work right you can probably construct some stuff where um or like yeah yeah GRE doesn't work right because you can struct like a lot of balloons on the left side a lot of balloons on the right side they're tied together by one balloon if you I don't know or something like this right where um if you try to do it you know it'll be well m maybe I say that in the wrong way um I think greedy does work or there is a greedy solution but I just mean like you have to really um the work in fact I guess greedy does right basically um but it's not a at right basically um but it's not a at least for me it's not an obvious thing least for me it's not an obvious thing though this is a medium so maybe is though this is a medium so maybe is obvious it's just that Larry's a little obvious it's just that Larry's a little bit slow today uh so slow that I'm bit slow today uh so slow that I'm referring to myself in the third person apparently say we're scanning from left right in a number line a 1D number line right in a number line a 1D number line and basically you scan from left to and basically you scan from left to right well right well when you think about it when would you when you think about it when would you shoot the shoot the balloon you would always shoot the balloon you would always shoot the balloon at the last point that you can balloon at the last point that you can if it's not already popped right and if it's not already popped right and what I mean by that is that um yeah because if you because you scan from left to right and you don't shoot that balloon at the last point that you can shoot it in a greedy lazy like you call lazy and that you want to just like shoot that as late as possible um and because if you don't shoot it at the latest then it then um whatam call it well then then you just miss the balloon you have to shoot that balloon no matter what right so I guess you're in that way it's like a forc greedy um and the thing the kind of really um the only thing that you might really um the only thing that you might have to kind of think about is that um is that you know when you shoot you may hit multiple balloons and that's basically the idea all right let let's kind of play around with that idea then and then let's get to it I don't know if I'm getting an I don't know if I'm explaining quite better maybe maybe I could draw it out but I don't even think drawing out really matters but I I guess I'll draw it out because I think there are a couple of cases that is in my head that I I think I'm just not saying out loud explicitly um cuz I think I see the edge cases but it's just that or not even edge cases cuz it's not it does I don't think it affects the problem or least my solution implementation but I think I'm not articulating it that part well right uh all right let's just PL in oh oh there you go I was holding my pencil backwards and I was like why is this not drawing well uh maybe I am slow today but yeah you have a number line and let's just say you have a selection of balloons and I just per of balloons by some intervals right and what I'm saying here is that you always only care about the right end points right well in terms of shooting so there other you have to care about the left end points by other reasons but yeah you only care about the right and points by shooting right and the reason is because um if you're going from left to right if you don't shoot it at this point there's no other time to shoot it for this balloon right and kind but of course you know if uh if you care about this one for example um you know you might not need to shoot this one because by shooting this one this one's also popped right so that's basically the idea and then there's some like you know uh thing so in a way you're kind of forced to shoot at that time and yeah still not sure I explained it that well but we we'll play around the code so then for XY in goodbye uh we actually want to sort this goodbye uh we actually want to sort this right cuz the input is just in random order I'm trying to think whether we sorting I guess we only care about the sorting I guess we only care about the right end point right because that's the right end point right because that's the only end point that we are um that we only end point that we are um that we are actually shooting the balloons and are actually shooting the balloons and then the left side will come into play then the left side will come into play anyway because um the left side will come in um because left is before the right side um because left is before the right side sorry I'm trying to think through some sorry I'm trying to think through some scenarios I don't know that I want to scenarios I don't know that I want to implement it this way actually so I'm implement it this way actually so I'm going to take it back uh some some stuff going to take it back uh some some stuff but yeah but basically the way that I but yeah but basically the way that I want to do it is just separate out the want to do it is just separate out the start and the end so that maybe I have start and the end so that maybe I have like four like four index uh XY and in well I guess just index uh XY and in well I guess just start and then in no need to confuse start and then in no need to confuse more and points more and points right and I'm just going to have some right and I'm just going to have some defense right and maybe I would have two defense right and maybe I would have two type of Defense one is the beginning and type of Defense one is the beginning and one is the end right so we'll do um uh the x axis right uh the start and right yeah and maybe the index so that we keep track of which one we care about right and then the same idea uh for the end and then now we can sort it and then now we can just pause the events right um yeah for X the type and the index in events uh and maybe we have um uh we keep track of which one we already burst right first it I don't know or shot I don't know Force time n right and then we also have maybe a a current is a set of end points that we care about and then here we go okay so if T is equal to start then we care then we want to set current is we add index to it and that's pretty much it I think we don't even have to care about X I don't think right and by definition it is not bursted but then now uh else which is T is equal to n of course there's only two scenarios then now now shoot up well first of all we want to make sure that it is not bursted so if not if bursted oops it burst of index then we just continue you know we already shot it there's no reason to need to shoot it and then after else um we want to shoot right and what happens when we shoot well when we shoot we get rid of everything in set that's basically the idea so for uh for I don't know for C and current oops uh we want that first of C is true because that means that you know when we shoot we shot everything also I have to keep track of the number of shots I forgot uh and here we shoot right so we shot once we burst all the balloons by sing them to burst and I think that should be good um there is a Nuance here that I didn't really talk about which is that what happens when it's tiebreaker right meaning that um the S point and so basically if you have one into here let that at the at the beginning and end that at the at the beginning and end points then what happens well you just points then what happens well you just have to think through what happens right have to think through what happens right which is that when you shoot straight up which is that when you shoot straight up at the endide at the endide um you want to catch the I think so um you want to catch the I think so anyway unless I'm just reading this anyway unless I'm just reading this wrong wrong um then you also want to catch the um then you also want to catch the beginning of the next one so in that beginning of the next one so in that case you want the starts to go before case you want the starts to go before the the end so that when you go by the time you end so that when you go by the time you get to the end all the tiebreaker stuff get to the end all the tiebreaker stuff would have burst and you would have would have burst and you would have gotten good right that's one way to do gotten good right that's one way to do it and yeah so that's want it real quick it and yeah so that's want it real quick uh I think an old gr I have to use click uh I think an old gr I have to use click on use example tou I we got uh hopefully on use example tou I we got uh hopefully this is right this is right what what what all these like running what what what all these like running time is so weird all over the place but time is so weird all over the place but uh I'm just going to take a look real uh I'm just going to take a look real quick this is pretty much this is quick this is pretty much this is actually exactly what I did except for actually exactly what I did except for now what is the faster way that I now what is the faster way that I did did H oh I am dumb uh I guess I I did the same I did the last time uh I meant to do it or I meant to fix it but I forgot which is that we have to um reset the set right all right all right because that is actually pretty bad that that messes up the complexity a lot uh and also as you can see it doesn't have to be a set it could be an array because we just go through it anyway but uh yeah uh so what's the complexity here right so this is n o of n but this is going to be n log again so yeah so after that everything is all of n all of end Loop all of One stuff and yeah so this is n log and dominated by um yeah I think that's all I have for um yeah I think that's all I have for this one to be this one to be honest yeah honest yeah um the idea is just kind of like playing um the idea is just kind of like playing with intervals and stuff like that I with intervals and stuff like that I think you know it's something adward k a think you know it's something adward k a lot um definitely get familiar with it lot um definitely get familiar with it uh we don't have a premium problem which uh we don't have a premium problem which I'm going to do an extra problem after I'm going to do an extra problem after this so stay tuned hit the Subscribe this so stay tuned hit the Subscribe buttton leave a comment for support and buttton leave a comment for support and yeah that's all I have for today have a yeah that's all I have for today have a great weekend if you if I will see you great weekend if you if I will see you soon uh or weekend have a great week I soon uh or weekend have a great week I don't see you soon but stay good stay don't see you soon but stay good stay healthy to your mental health uh let me healthy to your mental health uh let me know what you think about this Farm in know what you think about this Farm in the comments uh join in in Discord I'll the comments uh join in in Discord I'll see yall later and take care byebye | 2024-03-22 14:23:18 | 452 | 452. Minimum Number of Arrows to Burst Balloons - Day 18/31 Leetcode March Challenge |
|
FqpfLr76a1k | hi everyone welcome back so it's quite a tough welcome back so it's quite a tough contest contest this week and i'm planning to make this week and i'm planning to make videos for question two videos for question two and question three so stay tuned and and question three so stay tuned and today let's solve the question uh today let's solve the question uh maximum length of sub array with maximum length of sub array with positive product okay the question statement so given an array on nums we have to find the maximum length of subarray where the product of all the elements in this array is positive so it's pretty straightforward for example one we can see that the product of all the elements in the array is positive so the output will be the length of this array which is four and example two we can take the sub ray one negative 2 and negative 3 and their product will be positive so the output will be 3. and example 3 is either the sub rate negative 1 or negative 2 or negative 2 and negative 3 so the result will be 2. and you can see that the tricky part in this question is that in the array there can be positive and there's a very similar question 152 and there's a very similar question 152 the maximum product sub array but the maximum product sub array but in that question we have to calculate in that question we have to calculate the maximum the maximum product of the subarray but in this product of the subarray but in this question question is to find the maximum length of the is to find the maximum length of the subarray subarray with a positive product but the with a positive product but the algorithm we will use algorithm we will use are the same which is dynamic are the same which is dynamic programming programming and it's quite rare that you have to use and it's quite rare that you have to use dp dp to solve median questions in the contest to solve median questions in the contest but basically to use a dp you have to but basically to use a dp you have to first think of what is the intuition first think of what is the intuition of the dp array and its initial states of the dp array and its initial states and the state transition functions and the state transition functions and the data structure we will use are and the data structure we will use are two dp arrays two dp arrays which is positive and negative array which is positive and negative array and the meaning of this array is the and the meaning of this array is the length length of the longest sub array of the longest sub array which ending at the current element num which ending at the current element num side side with positive or negative product with positive or negative product now let's look at a code so the first now let's look at a code so the first part of the code part of the code is to set up the dp initial states is to set up the dp initial states so the initial state of the positive and so the initial state of the positive and negative array negative array is a rail of zeros and the size is a rail of zeros and the size is the size of the array nums is the size of the array nums and you will see later why we initialize and you will see later why we initialize both arrays to zero both arrays to zero and if the first element in the num's and if the first element in the num's array is array is positive then we will set positive then we will set positive 0 to 1. otherwise positive 0 to 1. otherwise we will set negative 0 to 1. we will set negative 0 to 1. and first initialize the output variable and first initialize the output variable result to the first element in the result to the first element in the positive array and next next part is the dp state transition equation so go through the array and if the element is bigger than zero then positive i will be equal to one plus a positive i minus one and negative i will be 1 plus a negative i minus 1. if negative i minus 1 is bigger than 0 otherwise uh reset to 0. and if the element is negative then positive i will be 1 plus negative i minus 1 if negative i minus 1 is bigger than 0 otherwise reset to 0 and negative i will be 1 plus positive i minus 1. and finally update the result to the maximum of a result or a positive i and now let's see the code in action and here we are we will look at example 3 because the nums array has all negative positive number and 0 and the output should be 2. and remember the dp array is the length of the longest sub array ending at the current element numpsi with positive or negative product so the first element is a negative so we will set the first element and next element is negative so we will and next element is negative so we will use this equation positive uh use this equation positive uh i is equal to one plus negative i minus i is equal to one plus negative i minus one one which means that uh this sub ray which means that uh this sub ray negative one and negative two its length negative one and negative two its length is two is two so we will update a positive so we will update a positive array the second element from 0 to 2. array the second element from 0 to 2. and for the negative array we'll update and for the negative array we'll update from 0 to 1 from 0 to 1 using this equation negative i is equal using this equation negative i is equal to to 1 plus positive i minus 1. 1 plus positive i minus 1. and why why is that because if you think and why why is that because if you think it's true it's true the dp array is the length of the the dp array is the length of the longest sub sub ray longest sub sub ray up to the current element so if the up to the current element so if the current element current element is negative and is negative and which means that if we only have a which means that if we only have a negative a sub rate negative a sub rate up to this point then the product of the up to this point then the product of the sub rate sub rate on its left should be positive so that on its left should be positive so that is why is why uh it should be one plus positive i uh it should be one plus positive i minus one minus one and here we also update rest uh from and here we also update rest uh from zero to two using the equation here and the next element is negative three so the longest uh positive product sub ray is uh the length is two so update positive array from zero to two and longest uh negative product sub rate is three so here is three and rest still and now we have a zero and you can see and now we have a zero and you can see that that because we initialize the positive because we initialize the positive and negative array to zero so here and negative array to zero so here uh the element won't be updated uh the element won't be updated it will remain zero and you can think of it will remain zero and you can think of it like it like we will reset the length of the sub ray we will reset the length of the sub ray to zero to zero so that is the main reason why we so that is the main reason why we initialize initialize the dp states to 0 at the beginning and finally we have a positive number so we'll update the positive array from zero to one finally let's review so the main finally let's review so the main algorithm we use algorithm we use for this question is dynamic programming for this question is dynamic programming and the data structures are two dp and the data structures are two dp arrays arrays positive and negative and their meaning positive and negative and their meaning is the length is the length of the longest sub array ending at of the longest sub array ending at the current element num site with the current element num site with positive positive or negative product and time complexity or negative product and time complexity linear time space complexity is linear linear time space complexity is linear too too but if you think it through you will but if you think it through you will notice that because of a dp array notice that because of a dp array uh every dp value only depends on the uh every dp value only depends on the previous one previous one so we can actually reduce the space so we can actually reduce the space complexity complexity to a constant space using to a constant space using the code here okay and that's all for today thanks for watching if you like this video please give a like subscribe to my channel | 2024-03-21 14:17:23 | 1,567 | LeetCode 1567. Maximum Length of Subarray With Positive Product(Python) |
|
ku2EKgqMp0M | hey guys this is Jay so how's everything going in this video I'm going to take going in this video I'm going to take another easy problem eight four four another easy problem eight four four backspacing string compare we're given backspacing string compare we're given two strings as ante return if they're two strings as ante return if they're equal when they both are type in the equal when they both are type in the empty text editors hash ming's backspace empty text editors hash ming's backspace character know that after backspacing character know that after backspacing and empty text the text will continue and empty text the text will continue empty so a B back slash C so this will empty so a B back slash C so this will generate AC this the same with eight generate AC this the same with eight this so they are true okay so the ABC a this so they are true okay so the ABC a be back pack then empty right be back pack then empty right so this empty also so they are equal so this empty also so they are equal this a empty empty C so it becomes C and this a empty empty C so it becomes C and this is empty a empty so we still see a this is empty a empty so we still see a so we see this is B so it's not the same well we can just a mimic the real typing right so for the a be back slash back space see first we type a uh-huh and then a week type B okay and then back slap backspace we get a and type C right so we get a C well how could we do it we could just create an array to do this right we could just create a empty array and then look through it and we if we met like backspace we can just pop it like okay first we get a and then B and backspace and really pop and then a B and this AC right and at last we compare if they are equal yeah that's it so the solution would be like we create a youtube function called get result get like get typed okay we get input we use a rate hope t use array to hold the DBT letters A for let factor of input if character if equals to backspace we will just pop right for EVD there is nothing to pop this will just do nothing if now we just wait push capture and then return result enjoy yeah so we could just call this function against two input to check if they are the same right and they should be okay yeah cool so that's it so what's the time and space for time it is you two will actually look through all the characters so the cat ears will be so it's linear time suppose n count of the letters space we use a array to hold the letters the worst case is that there is no backspace and it will cost us just the same s and letters right so cool so that's it pretty easy hobby helps see | 2024-03-22 16:06:16 | 844 | LeetCode 844. Backspace String Compare| JSer - JavaScript & Algorithm |
|
jDsDGsRhZcg | welcome guys welcome to my lego summit section so today let's talk about this section so today let's talk about this 1837 sun of dj in base k 1837 sun of dj in base k okay so a given integer array and the okay so a given integer array and the base k return base k return sum of digits of and after converting sum of digits of and after converting and from and from 10 to base k so idea is that uh right so 10 to base k so idea is that uh right so for example only goes to 34 which is in for example only goes to 34 which is in base 10 if you change it to base 6 base 10 if you change it to base 6 then it becomes uh i think become what then it becomes uh i think become what it becomes 5 it becomes 5 and 5 4 right because 6 and 5 4 right because 6 plus five plus four plus five plus four that's 36 right and uh and 10 10 that's 36 right and uh and 10 10 if you 10 is 10 right if you use 10 in if you 10 is 10 right if you use 10 in 10 meters you get the same 10 meters you get the same okay so this problem is basically is okay so this problem is basically is basically the first basically the first uh to solve it easier is that once you uh to solve it easier is that once you understand how to write understand how to write uh how to write uh given an integer in uh how to write uh given an integer in base 10 to base k and base 10 to base k and finally you just sum of all digits okay finally you just sum of all digits okay so my algorithm is very easy so let's so my algorithm is very easy so let's quickly talk about how to get base quickly talk about how to get base base b so right suppose you have an base b so right suppose you have an integer n integer n and you want to get base b then for each and you want to get base b then for each digits right so the first digit is just digits right so the first digit is just you you already know it's just an uh the you you already know it's just an uh the remainder right and remainder of b remainder right and remainder of b so this is the first digits and the so this is the first digits and the remaining is remaining is and you just calculate the the the quotient right so then you put all your quotient into your n so the algorithm this should looks like a while should look like if your n is greater or equal to one then you should just define your own to be an uh remainder and you just take the digits so for each digit is this a modulo b so this is your digits right so you can create at least two a panelist digit but this is the the final digits right so you finally you need to reverse the digits so this is the standard base b algorithm i think so if only zero you return zero then d is to be empty if n is greater uh y only exists basically greater than zero then your djs append appended remainder right okay and also a appended remainder and then you unchange it to be quotient then finally you just uh reverse the list right because the first the first remainder your compute should be the right should be the right most okay so finally you define the answer to be number to basically to include and finally sum of answers right so answer is at least basically each element is a digits then finally you sum of them so that's it and these algorithms should be very fast because you just use the division okay so yeah that's it i'll see you guys in the | 2024-03-22 19:44:51 | 1,837 | Leetcode solving 1837 Sum of Digits in Base K |
|
By3z4QauGQA | 1777 maximum score from performing multiplication operations yeah let's multiplication operations yeah let's first try to understand the problem so first try to understand the problem so we are giving an array of nums and we are giving an array of nums and another array of multipliers and this another array of multipliers and this nums is the length of the nums is more nums is the length of the nums is more than equal to multipliers yeah so this than equal to multipliers yeah so this is also reasonable yeah because we're is also reasonable yeah because we're going to use the multipliers one by one going to use the multipliers one by one so for the first case for example we're so for the first case for example we're going to use a three and this three can going to use a three and this three can multiply by this three or this one multiply by this three or this one because it must be at the hand of the because it must be at the hand of the tail of the nums yeah and for the next tail of the nums yeah and for the next step we're going to choose the second step we're going to choose the second number and this number will choose the number and this number will choose the head or tail yeah so for the first head or tail yeah so for the first example this is three would times three example this is three would times three and then this is two would times two and and then this is two would times two and the last one would times one yeah and the last one would times one yeah and the final answer is 14 and the numbers the final answer is 14 and the numbers can be um positive or negative numbers can be um positive or negative numbers yeah uh we should understand that this yeah uh we should understand that this is not a gritty is not a gritty problem yeah yeah because uh maybe problem yeah yeah because uh maybe you're going to think we always going to you're going to think we always going to choose the um biggest number but there choose the um biggest number but there is also negative is also negative numbers it is a yeah it is not the case numbers it is a yeah it is not the case I I think it's really easy um to find I I think it's really easy um to find counter examples yeah and this is counter examples yeah and this is actually a DP problem I think for DP actually a DP problem I think for DP it's more safe to solve such kind of a it's more safe to solve such kind of a problem problem yeah so for each of the time we can yeah so for each of the time we can choose from the hand on the tail and choose from the hand on the tail and then for the next number we're going to then for the next number we're going to choose from hand on tail and finally we choose from hand on tail and finally we just needed to check the maximum number just needed to check the maximum number yeah so for me I'm prefer to yeah so for me I'm prefer to use uh the DFS plus memorization so for use uh the DFS plus memorization so for this C of DP because this is easy to this C of DP because this is easy to write for the multidimensional DP yeah write for the multidimensional DP yeah it's easy to analyze and easy to it's easy to analyze and easy to write yeah I'm going to prepare a left write yeah I'm going to prepare a left and right poter so this left and right and right poter so this left and right poter is for the nums and another I will poter is for the nums and another I will another one I'm going to prepare a Index another one I'm going to prepare a Index this is for this is for multipliers so I'm going to prepare a multipliers so I'm going to prepare a index at the same time I'm going to index at the same time I'm going to prepare the M should be equal to the prepare the M should be equal to the length of the length of the multipliers yeah now I can start the multipliers yeah now I can start the DFS uh finally for my return I'm going DFS uh finally for my return I'm going to return the DFS with zero to return the DFS with zero un less of nums minus one this is from un less of nums minus one this is from the right side and the index going to be the right side and the index going to be starting from zero yeah because this uh starting from zero yeah because this uh the length of the multipliers is always the length of the multipliers is always smaller or equal to length of nums so smaller or equal to length of nums so for the S cases I can directly use the for the S cases I can directly use the index if this index equal to m i going index if this index equal to m i going to return a zero it means there's to return a zero it means there's no uh it means it it has already no uh it means it it has already finished the multipliers there's nothing finished the multipliers there's nothing to do so I going to return return a zero to do so I going to return return a zero now I'm going to prepare a result it now I'm going to prepare a result it will be negative Infinity so here for will be negative Infinity so here for this result you cannot prepare for zero this result you cannot prepare for zero yeah because for the first calculation yeah because for the first calculation it might be a negative number but you it might be a negative number but you cannot update it to zero so this is why cannot update it to zero so this is why we're going to always choose the we're going to always choose the negative Infinity because there's negative Infinity because there's negative numbers if there's no negative negative numbers if there's no negative numbers yeah maybe you can try to yeah numbers yeah maybe you can try to yeah put a result as zero yeah now we're put a result as zero yeah now we're gonna um gonna um prepare yes we just needed to check prepare yes we just needed to check check the nums so the nums can go from check the nums so the nums can go from the left or right side so what it going the left or right side so what it going to be so would be maximum of result yeah to be so would be maximum of result yeah let's first try the left side because we let's first try the left side because we don't don't know so if we choose form left side what know so if we choose form left side what it going to be it going to be L times it going to be it going to be L times the multiplier yeah the multipliers the multiplier yeah the multipliers index yeah we get to the result and plus index yeah we get to the result and plus the DFS so the the BFS would the DFS so the the BFS would be uh because L has already been be uh because L has already been calculated and it should be removed yeah calculated and it should be removed yeah according to the question it should be according to the question it should be removed so it will be L + one and the r removed so it will be L + one and the r would be the same and inside the index would be the same and inside the index through plus one because it it need to through plus one because it it need to go to the next multiplier yeah now let's go to the next multiplier yeah now let's go go to uh let's continue to check go go to uh let's continue to check another side check the right side if if another side check the right side if if we choose the right side it going to be we choose the right side it going to be m r and the multipliers going to still m r and the multipliers going to still uh still be the same yeah and here going uh still be the same yeah and here going to be L and here going to be r + to be L and here going to be r + one yeah actually this is the entire one yeah actually this is the entire code as you can see that it it is not so code as you can see that it it is not so difficult because we just use DFS plus difficult because we just use DFS plus memorization memorization yeah now let me run it to T yeah now let me run it to T um yeah it is a non type yeah let me um yeah it is a non type yeah let me just check what is wrong with it unported types plus int and non type so this means my DFS there is a non type for for the DFS yeah because here I did something wrong it should be R minus one yeah because the right poter should be shifted to the left and not r+ one let me just run it again same else with plus one uh n l times DFS L + one r index + one and the index and uh index + one yeah this is the Str normally I um yeah this is the DFS l+ um yeah this is the DFS l+ one r index oh I don't yeah I get a int and non type definitely yeah I get a int and non type definitely this going to be a this going to be a int yeah if this index equal to M I'm int yeah if this index equal to M I'm going to going to return uh yeah let me just delete I don't know why yeah let me just delete I don't know why I make such a mistake let's let me just I make such a mistake let's let me just start again so start again so the yeah the result would be negative the yeah the result would be negative infinity and I will update my result it infinity and I will update my result it should be maximum of the result and with should be maximum of the result and with the left side it would be number the left side it would be number l u times the l u times the multipliers uh with the index zero and plus DFS it would be l so the plus one and R and inside uh it should be uh index plus one yeah so what going to happen if I don't write to the second line yeah it is still something H yeah normally I think if I write it H yeah normally I think if I write it for the first time for the second time I for the first time for the second time I should not make a mistake because For should not make a mistake because For the First Time I didn't make a the First Time I didn't make a mistake uh this is the mistake uh this is the strings R minus one uh yeah because I didn't uh return the result yeah so now I think it should be okay yeah because for each of the time I should uh return the result now at least yeah at least the program works but I got the wrong answer for the first time it is a 10 and this is yeah not right uh let me just check uh what is wrong with it so yeah because I going to choose the maximum number uh this is a negative infinity and and yeah this one I didn't change it I need to change it to R and now let's just check it yeah now as you can see it works now let me submit it to T if it can pass for all testing cases now as you can see it pass for all testing cases yeah I should be more careful about it so sometimes if I just use a copy and paste I I will forget about yeah something and for this time I for I even forgot about the return um the time complexity is o n * n although you can see here there are three indexes actually for this L and R it going to always be smaller and smaller this is just like a two pointer because L will always be shifted to the right R will always be shifted to the left so this is actually o n and for the index so this is o m so the time complexity is O M * n yeah because we use the pass we use the memorization so that is why it can pass and let's check the and M so the m is 300 and N is the num length is 10 to the^ of 5 so this means three * 10 to the power of seven can pass for this kind of a problem thank you for watching | 2024-03-22 12:52:01 | 1,770 | Leetcode 1770. Maximum Score from Performing Multiplication Operations (dp multi-dimention) |
|
jL3QcVLqjs0 | Loot Hi Everyone For Today We Are Going To Solve This Problem Point To Remove Problem Point To Remove Duplicates Dark Clean Problems The Duplicates Dark Clean Problems The Giver Shot Dead Cells Remove Duplicates In Giver Shot Dead Cells Remove Duplicates In Place Which Element Of Years Old And New Place Which Element Of Years Old And New Length Of The Space For Adv You Must Be Length Of The Space For Adv You Must Be Modified Into The River In Modified Into The River In Modified Into The River In So One Example That They Can See The Giver Is One To Two To The Number To The Number 109 That [ __ ] Pure Function Shoulder Return Request U Because Judge The First Two Elements Of Observing One Interactively 1600 Will Be Modified Something I Want To Elements of elements which contains all the elements in the number 12304 land acquisition the number 109 demise 16 subscribe so they can see the white jhalda example 100 suppose that being another 1.2 2134 ok khush sudhir wa morning us service center The Video then subscribe to the if you liked The Video then subscribe Number Three And Will Be Again Are Not To Worry About The Length Of The Problem No Problem Solved The Process Of Birth Date With Best Solar System Is Like Using Pointers So What Does It Is That Will Keep Under Under Under 10.25 Will Be Doing So Will Start From The Very 10.25 Will Be Doing So Will Start From The Very First Time And It's Something Like This First Time And It's Something Like This Point To Weiler Replay Element The Little Point To Weiler Replay Element The Little Bit More Attention Pimple Bit More Attention Pimple Text On Social Media Two And Two And Text On Social Media Two And Two And Three And 400 Ko Ka Point Now Here Three And 400 Ko Ka Point Now Here Point 12.21 More Extinct The Point 12.21 More Extinct The Point 12.21 More Extinct The not ignore this will be the first player of the year to the difference between the way will give one will dare attack you will happen impatient and that and will appear and 2nd three and 400 right now water condition is that we have to Rock Hair And Din Power To Do The Thing Rock Hair And Din Power To Do The Thing Rock Hair And Din Power To Do The Thing In Noida Will Check Plumber Se Different From Others In Noida Will Check Plumber Se Different From Others And Gives Pen Tool For The Third And And Gives Pen Tool For The Third And Third Soft Veervansh Will Update You Will Be The Fighter Man 2 And 321 Ki And Aakhri And 404 Dars And Any Person The Country Daily Point and Share and Point The Country Daily Point and Share and Point The Country Daily Point and Share and Point to Verses and You Can Go to the Which to Verses and You Can Go to the Which Reporter Say Good But Just So This Is Not Reporter Say Good But Just So This Is Not Win in To-Do Solt Record The Solution Soft Win in To-Do Solt Record The Solution Soft in To-Do List Two Wick Point So Let's in To-Do List Two Wick Point So Let's Start From The Start From The Start From The Yesterday Morning Expert Check Foreign Policy Yesterday Morning Expert Check Foreign Policy Director To Numbers And Different Different Director To Numbers And Different Different And This 2.5 Inch Exams Off Side Is Not And This 2.5 Inch Exams Off Side Is Not Equal To The Norms Of Ujjain In This Equal To The Norms Of Ujjain In This Condition Me To The Journey To The Value Condition Me To The Journey To The Value Condition Me To The Journey To The Value Speaker and MLA Ashwini Wig A Plus One Because To Intact Starter Sure Vinit To Return That Modern Literature Shiromani Plus One Components Soft Porn Image K Skirt Meet To Do A Juda Vikalp 047 Juda Vikalp 047 Juda Vikalp 047 Pass Pass So It's 10 Workshop Bay So Let's Raw Test So It's 10 Workshop Bay So Let's Raw Test Encephalitis Corrector Note Accept 100 Gram Tried This Problem Accept 100 Gram Tried This Problem With A Different Different Poses For With A Different Different Poses For This Is The First April 2012 Pointers This Is The First April 2012 Pointers Solid Thank You | 2024-03-19 18:20:22 | 26 | LeetCode 26: Remove Duplicates from Sorted Array | Python |
|
g7vAlCR-jno | Ajay Ko [Music] Hua [ Music] Hello Hello One And Welcome To New Video English Video Viewers Problem Number 90 From From The Problem 000 Have to here and That will be there at That will be there at That will be there at once and from the railway station duty reduce 2002 number of clans given till minus one ok example2 which is ours which is ours which is ours meaning and here 0 0share 0 0share If we click on top one If we click on top one If we click on top one then what will happen then our today's then what will happen then our today's head off if we check head off if we check which row for answer of one what will be the name which row for answer of one what will be the name clearly then here if we clearly then here if we put it in place of then put it in place of then submit and submit and 20 so see 20 so see here what we will do here soon be gone here name shop soon be gone here name shop names of three which instead of numbers of five don't names of three which instead of numbers of five don't threaten 12345 this This is so This is so This is so then for when we see here then then for when we see here then answer add so our what's this side and answer add so our what's this side and set our name fennel nfo how many set our name fennel nfo how many 1234 so here we 1234 so here we subscribe 12345 as as we like this this is the example given to us Hello this is the example given to us Hello We have been given 105 1234 Now we have to make ours, so first of all we have to answer the answer for here if we if ours answer the answer for here if we if ours which will remain ours then ours which is ours not threaten the sum of 9808005005 set the jhal zero work will have to be named Saturday or removed Naam se to to hamara hamara here for us subscribe to our channel subscribe to our channel if you subscribe for 10 minutes account statement hoga 2012 i.e. one ho's see this don't forget to subscribe If we are 1234, 3232 here, we need to subscribe for this, so for this, we were the we need to subscribe for this, so for this, we were the first to approach Amazon, Amazon subscribe, first of all, who will make the patient false, which is this, which will be our size of salt, And the time is right, like And the time is right, like And the time is right, like this is ours, then this is ours, then from where do we get our time, we have been appointed the president and now inside this we will fold it at number eight and as if the oil is finished here, then ours it time. it time. which will be clear if we talk about its space which will be clear if we talk about its space complexity, Space Congress complexity, Space Congress President is our code, first of all, I took it as per the order, we will enter it, we will appoint it, this is called subscribe. called subscribe. called subscribe. second is the laddu solution, what we have to do is to make it a loop, come as soon as possible [music] and someone inside it like we have finished the solution together and we will and What is the result What is the result What is the result and this has been our success, this is from the Faster Than convention and what from the Faster Than convention and what Meghnad 3000 Meghnad 3000 does, for this problem does, for this problem keep watching our channel subscribe time complexity notification and paste this we do we do we do this a new this a new this a new update the same as to what we have to do, here also we will make these changes, first of all we will take out our N which is because the size, subscribe our channel, after that we will give the value of change here. Something in the exam so that we can Something in the exam so that we can change this person in such a way change this person in such a way that first of all appointing him here and what can we do to finalize whatever will happen with him. appointing him here and what can we do to finalize whatever will happen with him. us assume in every position, if I for the first position, then we can do something like this: Name multiply the number multiply the number at I and multiply and at I and multiply and what we will do what we will do in this is in this is village or village or table and We will take this sentence, okay, we will take this and as we get this, we will cut it for the number * * * 1234 500 800 800 to 1000 times unity is 0, our first element is Namaskar, what will it become and ours will go In this way, if you In this way, if you In this way, if you calculate for some then what will we do, calculate for some then what will we do, now we see what will we do for them, now we see what will we do for them, Here we should have got Here we should have got that i means norms of number tie we should have got one comes from in times index in the answer we should have got should get so we like we do so we here do so we here can type 06 so can type 06 so if for then how much is this how much is our wake up here if from here we want what is the value here we don't want we will divide thirteen by them if we divide it like this education then But But But today's if we want the value of today's if we want the value of what was already here, here we will have the value. what was already here, here we will have the value. If we take this as percentage but If we take this as percentage but cent end then we will get the value meaning cent end then we will get the value meaning if we take this thirteenth of those people if we take this thirteenth of those people this is its original this is its original divide divide. divide divide. Set this measurement Subscribe to Subscribe to your special 5985 K0 12345 2014. If you your special 5985 K0 12345 2014. If you divide the education and get it then you will get divide the education and get it then you will get six * 4 plus original velvet six * 4 plus original velvet 20123 Now we will make it Now we will make it 20% of the original. 20% of the original. 20% of the original. get and which is our channel, now instead of our idli, divide which is our 0123, * * 40 subscribe will be five, this will be 5.5 at cent and what will be 3033. 3033. 3033. us out and do the original thirty percent, then we will soon, if we want it here, here we will talk, then click for us, subscribe to our Naan, our channel here into three plus plus our channel. and we will get its original vegetable 22% course and we will get its original vegetable 22% course that we will get four because the that we will get four because the map of 6042 map of 6042 is 1618 subordinate value and if we want it our is 1618 subordinate value and if we want it our which will finally divide by terrorism which will which will finally divide by terrorism which will be our channel this problem problem be our channel this problem problem problem problem here we are an actress. here we are an actress. here we look at the time and solution for this and see that solution for this and see that this is ours which is our today's two Jhal name set name from the shop number on the left side st and a plus this should be the first institute. a plus this should be the first institute. Amresh put inside this inside the parents Amresh put inside this inside the parents plus not for and after that we like plus not for and after that we like our complete is over time and and plus and we hate table and after that we will hate table and after that we will get the hello complete result so let's see if we are on our fearless then our old solution. are on our fearless then our old solution. we will take only one thing that intense cold not limit from here we will now turn on a potato here from where to where Chadana is equal to zero six Chadana is equal to zero six transaction size transaction size and we will and we will cut it cut it inside this we will inside this we will cut it cut it cut it take it and after that, like we will add it here, our our loop will be like this is finished, run it quietly, we will run loop will be like this is finished, run it quietly, we will run it till where from the village, we will run it it till where from the village, we will run it is equal to zero six. 06 this is done and that's going to last and inside that what we have to do is keep doing a sentiment and here equalize house add and our potatoes now after that we'll return this number of ours If you If you If you submit and subscribe the result, this is an example. We submit this particular chapter note this particular chapter note solution and if we have used less space than 498 A, then you will used less space than 498 A, then you will consider the solution a coward. If you like the solution society, then like consider the solution a coward. If you like the solution society, then like this video. this video. this video. with your friends and if you want to practice regular problems then you can join our telegram channel [Music] | 2024-03-25 13:07:48 | 1,920 | 1920. Build Array from Permutation | Zero to FAANG Kunal | Assignment Solution | Leetcode | Shapnesh |
|
5j9pLXr7xpM | [Music] with the lonely Dash and today we're going over lead code question 61 rotate list which says given the head of a linked list rotate the list to the right by K places okay so we know that k equals 2 and we have a linked list right here which we are going to rotate by two so what does that mean well if our linked list is in order one two three four five if we rotate it to the right one position or two positions each one of these is going to move so one will move to two two will move to three three will move to four four will move to five which means five will then have to move all the way down here to the one position and that gives us this rotate the rotate one position but since k equals two we have to do it again so 5 goes to one one goes to two two to three three to four four goes all the way down to where the five position is and that gives us this answer here rotates two times where the new head of our linked list is actually this four and the tail is this three so that's all the question is asking is taking all the nodes and moving them to the right K number of times now it sounds pretty simple but there's there it's kind of more complex and we're going to dive into how we're going to do that now so down here I have the exact same linked list one going all the way to five and K is equal to 2 here and we're going to solve this mathematically okay and I'm just going to go through each of the steps and it'll kind of fall into place of what we're doing so in order to solve this we're going to need a pointer and this is our current pointer and I'm going to stick it here at the head of our linked list and the first thing we're going to need to calculate is going to be the length of our linked list now we can't just ask like hey what is the length of linked list we actually need to count it so the first thing we're going to do is take our pointer and we're going to Traverse our linked list one two three four five to determine that the length is 5. okay so we have a length of five next thing we're going to do is after we know how long it is we're going to connect our last node to our first node like this so that we have a cycle it's cyclic so Five Points to one one points to two two points to three three points to four four points to five awesome okay one is still our head but we've created this cycle and that's really important um because without this cycle happening when we cut uh one of these connections then we're gonna have two separate linked lists and we just don't want that so we got to make sure that they're stuck together now here comes the mathematics we need to figure out which node is going to be the new head of our linked list and we already know that this 4 is going to be the head of our new linked list because we did it just above it's right up there we know the answer already but how do we make this determination well we got to use math we know the length is 5 and we know that K is 2. so in order to figure out where to move our current pointer in order to find our new head we're going to have to subtract K from our length so in this case 5 minus 2 is 3 1 2 and 3 therefore the node just passed our current pointer is our new head and we can cut here and then we're done because that'll be four points to five to one to two to three and again we already know that's our answer because it's up here so the simple mathematics is we're going to take our length we're going to subtract our K and we're going to move our current pointer that number of nodes forward now there is an issue okay and the issue is within our constraints okay so we're going to look at our constraints and it's simply that K is going to be any value that is more than Z or equal to zero but less than 2 times 10 to the ninth and it's possible that K could be greater than the length of our um that our linked list because it only goes up to you know five so what happens when K is greater well let's just say k is 12. all right and we're going to put our current pointer back here we counted that the length of our linked list is five if we come down here and we take 5 and we subtract 12 that you know gives us negative seven we have nowhere to move our current pointer I mean I guess we could go backwards one two three four five six seven and that does sort of work but that seems counter-intuitive because if it was I don't know a huge number such as this the current pointer would have to go back around and around and around and around and around and around and around and it just takes up too much time okay so instead we're going to do a little bit of mathematics and we're going to use the modulo symbol so that's down here okay so our new calculation is going to be K the value of K modulo the length okay so in this case we know that the modulo just provides us with the remainder after a division so 12 divided by 5 is 2 with 2 as the remainder so K modulo length is going to end up being 2. which as you can kind of guess was our original answer anyway once we have done that we can take our length and subtract K from it which is three so we're going to move our current pointer one two and three and what do you know that brings us to this position here and it solves our problem so this is a way of making the arithmetic work in our advantage it will make it go much faster so to sum everything up what we're doing in order to solve this problem is we're going to count the number of nodes that we're dealing with to find our length once we have our length we're going to determine if it is well if our length is greater or less than K if our length is greater than K we're just going to subtract K from our length and then move our current pointer those numbers of positions connect the last and first node and then cut to find our new head however if K is greater than our length here we're going to have to do this mathematics here in order to do the same thing to move our current pointer forward and find the new head so hopefully that makes sense let's go into a little bit more depth with our constraints to see if there's any other edge cases that we might have to consider [Music] so we've already looked at the constraints um and the number of nodes in the list is in the range of 0 to 500 and we've already talked about how what would happen if K was greater than the number of nodes and we solved that uh by using our modulo symbol down here now it would still work if we didn't use the modulo but we could run into some timing issues so that's why we're using the mathematics in order to solve this so we're golden outside of that we know that the values within our nodes are going to be between negative 100 and 100 inclusive so that's okay and K could equal zero so if k equals zero you might just want to say okay it's not rotated at all let's just return the head of what we're given but outside of that it could also be rotated an enormous number and again that's what we were talking about using this modulo mathematics to solve the problem so that's pretty much the only Edge case we'll have to consider it's not something we need to do right away we've kind of baked it in to our solution so let's move forward and start with some pseudo code [Music] so for our pseudo code I'm just typing into the python work area of the lead code website and I know we just went over a couple of Ed well sort of an edge case but something to mention one more time is basically if if there is no linked list provided remember because in our edge cases it said it could have zero nodes to 500 nodes meaning there is no head what can we do well we can just return nothing or null which are nothing null none whatever we need to do in order to take care of that edge case and while it's not necessarily an edge case it can shorten the amount of time um for our solution to process okay so once that's taken care of it's time to code something hooray for coding um the first thing we need to do is create a current pointer in order to uh you know first count the number of nodes in our linked list and that's going to be at the head um of the linked list so we're creating our current pointer and then we're going to need to create a counter create a counter uh to determine the length of the linked list and of course that's going to start at zero right because we're going to end up needing to actually you know what that's going to start at 1 because we are putting our pointer on the head of our linked list so that's why it is starting at one all right then we're going to use a while loop um use a while loop that will Traverse the linked list to determine the length of the list stopping the pointer at the end of the list right and so that's going to look like basically while the pointer.next exists that's how we're going to get this to stop at the end of our uh our linked list so once that's done um once the pointer stops we are going to then point the last node of the list to the head of the list this creates um our cycle or Circle right and this is a really important thing because again I've talked about the importance of connecting it so that half of our linked list doesn't float away when we cut that linked list with a new head then you using the calculated length of the list right because that's all we did we're using the calculated length and I don't think that's how we spell using using the calculated length of the list we need to determine how many nodes to the left we need to shift the new head of our linked list and again it's not really the number of nodes to the left it's a full on calculation of how many nodes we need to move our uh count or our pointer to the right so how many nodes to let's see move the current pointer uh to the right in order to find the new head of our olings list there that makes a little bit more sense to me um okay so then we'll do yeah that's basically all we need to do there then we need to move the current pointer through the cycle until we stop at the last node of the new list we need to create a variable or a pointer or something to hold the value of the new head of the link new linked list new linked list that way when we cut it we have something to return right then we're going to detach or cut the pointer of the new Final node and point it to nothing right because it needs to be the final node and it can't be pointing at anything it's the final node finally we can just return the new head of the new linked list and we're done so this is all of the pseudo code we are going to need in order to solve this problem uh let's take it copy and paste okay so we're working in the JavaScript okay so we're working in the JavaScript work area of elite code website and work area of elite code website and there's all my red squiggly lines for my there's all my red squiggly lines for my pseudo code and we're just going to kind pseudo code and we're just going to kind of follow along so the first thing we're of follow along so the first thing we're going to do is deal with this Edge case going to do is deal with this Edge case it's not really an edge case but it's it's not really an edge case but it's something I like to stick in at the very something I like to stick in at the very beginning which is basically saying if beginning which is basically saying if the head value provided is null or the head value provided is null or doesn't exist or has nothing we're just doesn't exist or has nothing we're just going to return null anyway so it kind going to return null anyway so it kind of gets rid of the case where if this of gets rid of the case where if this head has no value then obviously K head has no value then obviously K doesn't matter so we're just going to doesn't matter so we're just going to return what we have not really an edge return what we have not really an edge case but it uh might shorten the runtime case but it uh might shorten the runtime a little bit here a little bit here now we get to code real stuff so we need now we get to code real stuff so we need to create a current pointer at the head to create a current pointer at the head of our linked list so let's call it of our linked list so let's call it I don't know current let current equal I don't know current let current equal head and we're sticking it at the head head and we're sticking it at the head of our linked list and we also need to of our linked list and we also need to create a counter because we need to create a counter because we need to count the length of our length list or a count the length of our length list or a linked list so we're going to call that linked list so we're going to call that length uh you could call it counter length uh you could call it counter whatever you need to but we're going to whatever you need to but we're going to start it with a value of one and we're start it with a value of one and we're starting it with a value of one because starting it with a value of one because our pointer already should count the our pointer already should count the head it's on we're going to move our head it's on we're going to move our pointer and some people will start this pointer and some people will start this at zero which will be a big mistake so at zero which will be a big mistake so just remember we've already counted our just remember we've already counted our head that's why we're starting at one head that's why we're starting at one and we'll eliminate it that's pseudocode and we'll eliminate it that's pseudocode now we're going to do a while loop to now we're going to do a while loop to Traverse our counter or sorry our Traverse our counter or sorry our pointer through each one of our nodes to pointer through each one of our nodes to add to our length so we can calculate add to our length so we can calculate the length of our linked list so while the length of our linked list so while in this case in this case current.next is not null right so while current.next is not null right so while there is a value for our current pointer there is a value for our current pointer to move to what are we going to do well to move to what are we going to do well we're going to move we're going to move our pointer to it by making our our pointer to it by making our current pointer move to the current dot current pointer move to the current dot next value and we're going to add 1 to next value and we're going to add 1 to length so length plus plus okay now this length so length plus plus okay now this should stop our current pointer at the should stop our current pointer at the final node because as long as this 2 final node because as long as this 2 exists that moves forward 3 exists this exists that moves forward 3 exists this moves forward 4 exists this moves moves forward 4 exists this moves forward five exists this move forward forward five exists this move forward nothing else exists we break out of our nothing else exists we break out of our Loop and our current pointer sits on the Loop and our current pointer sits on the very last node that's what this while very last node that's what this while loop is doing so we're using our while loop is doing so we're using our while loop to Traverse it and stop the pointer loop to Traverse it and stop the pointer on the last node on the last node once the pointer stops we need to point once the pointer stops we need to point this last node of the list to the head this last node of the list to the head of the list this creates our cycle and a of the list this creates our cycle and a circle so we're breaking out of our circle so we're breaking out of our while loop and we're going to say that while loop and we're going to say that the current dot next value so wherever the current dot next value so wherever our current pointer is pointing needs to our current pointer is pointing needs to be the head this is the most important be the head this is the most important uh code script of the entire thing uh code script of the entire thing because without this our mathematics because without this our mathematics won't work so we have now pointed our won't work so we have now pointed our final node to the front of our linked final node to the front of our linked list and we go to the mathematics so list and we go to the mathematics so using the calculated length of the list using the calculated length of the list we need to determine how many nodes to we need to determine how many nodes to move the current pointer to the right in move the current pointer to the right in order to find the new head of our linked order to find the new head of our linked list and that goes back to our list and that goes back to our mathematics here now I originally mathematics here now I originally thought to myself oh I can just use a thought to myself oh I can just use a quick if statement if the length quick if statement if the length is greater than our K value then we can is greater than our K value then we can use this math here use this math here if otherwise if our K is greater then we if otherwise if our K is greater then we can use this math here but that's kind can use this math here but that's kind of unnecessary step because even if we of unnecessary step because even if we just go straight to this math it'll work just go straight to this math it'll work right so two modulo 5 is still two 12 right so two modulo 5 is still two 12 modulo 5 is still two a million and two modulo 5 is still two a million and two modulo 5 is still going to be two so modulo 5 is still going to be two so we're going to go straight to this we're going to go straight to this mathematics here which means when we're mathematics here which means when we're dealing with this math we're going to dealing with this math we're going to say that K is going to be equal to K say that K is going to be equal to K modulo length right our new uh modulo length right our new uh calculated length and then K is going to calculated length and then K is going to then equal length minus whatever K value then equal length minus whatever K value we just created we just created and we can simplify this mathematics as and we can simplify this mathematics as well by taking this value here well by taking this value here I'm going to copy it and we're going to I'm going to copy it and we're going to replace it here so we don't need this replace it here so we don't need this line at all so that's how we're going to line at all so that's how we're going to do this mathematics and create a new do this mathematics and create a new value of K that we're going to have to value of K that we're going to have to move our current pointer to the right move our current pointer to the right that's what this line is doing so that's what this line is doing so hopefully that math makes sense to you hopefully that math makes sense to you now we actually have to move this now we actually have to move this current pointer through the cycle and current pointer through the cycle and stop it at the last node of the new list stop it at the last node of the new list so how are we going to do that we need so how are we going to do that we need to move our current pointer K number of to move our current pointer K number of times so we're going to use a while loop times so we're going to use a while loop and we're going to continually subtract and we're going to continually subtract the value of K the value of K until it reaches zero so while K is until it reaches zero so while K is greater than zero what are we going to greater than zero what are we going to do well we're going to move our current do well we're going to move our current pointer pointer to to the next node and we're going to the next node and we're going to subtract 1 from K so let's say k equals subtract 1 from K so let's say k equals 3 which is in our example uh if k equals 3 which is in our example uh if k equals three we're going to move our current three we're going to move our current pointer 1 and then K now equals two if k pointer 1 and then K now equals two if k equals 2 we're moving our current point equals 2 we're moving our current point or one subtracting it to one if k equals or one subtracting it to one if k equals one then current pointer moves and then one then current pointer moves and then it equals zero when we break out of this it equals zero when we break out of this Loop so that's how we moved our current Loop so that's how we moved our current pointer three times pointer three times okay so that's our movement of our okay so that's our movement of our pointer now we need to create a variable pointer now we need to create a variable to hold the value of our new head so to hold the value of our new head so coming back here we moved our current coming back here we moved our current pointer one two three pointer one two three and Our intention is to cut this line if and Our intention is to cut this line if we don't hold this value and we cut this we don't hold this value and we cut this line or this pointer four and five are line or this pointer four and five are just going to float off into nothingness just going to float off into nothingness so we're going to have to hold it with a so we're going to have to hold it with a value so in order to do that we're just value so in order to do that we're just going to call it new head so let new going to call it new head so let new head equal the the node that is next to head equal the the node that is next to our current pointer so current dot next our current pointer so current dot next that's pretty simple all right so that that's pretty simple all right so that is now holding the new head of our is now holding the new head of our linked list now we need to detach our linked list now we need to detach our pointer pointer so that this 3 is detached and pointing so that this 3 is detached and pointing off into nothingness instead making it off into nothingness instead making it the end of our linked list so in order the end of our linked list so in order to do that we're just going to say that to do that we're just going to say that our current dot next is going to equal our current dot next is going to equal null nothing so our current pointer null nothing so our current pointer points to absolutely nothing and then points to absolutely nothing and then we're done we just have to return the we're done we just have to return the value of our new linked list which of value of our new linked list which of course is return course is return new head new head and we are done with all of our coding and we are done with all of our coding so hopefully I'm just kind of Squish it so hopefully I'm just kind of Squish it in here hopefully it will run without in here hopefully it will run without any issues I'll hit run see how we did any issues I'll hit run see how we did against the test cases against the test cases it does seem to work ooh 100 it does seem to work ooh 100 milliseconds seems pretty long but I'll milliseconds seems pretty long but I'll hit submit and see how we did against hit submit and see how we did against everybody else on the internet everybody else on the internet and we did just fine so it looks like 94 and we did just fine so it looks like 94 in run time and 84 in memory so that is in run time and 84 in memory so that is a simple and straightforward way of a simple and straightforward way of solving rotate list that isn't quite o solving rotate list that isn't quite o of n because we have to go through it at of n because we have to go through it at least once to calculate our length and least once to calculate our length and then move uh partially through it again then move uh partially through it again with our current pointer but it's pretty with our current pointer but it's pretty darn fast uh way of solving it using darn fast uh way of solving it using JavaScript JavaScript foreign foreign [Applause] | 2024-03-20 10:51:10 | 61 | 61. Rotate List - JavaScript LeetCode Solution |
|
5yCufhg9j_Y | do do do [Music] do [Music] | 2024-03-25 14:51:44 | 999 | 999. Available Captures for Rook || LEETCODE SOLUTION || IN C++ || DATA STRUCTURE AND ALGORITHM |
|
FAuXRJhTjzs | hello fellow YouTubers today we're going to look at YouTubers today we're going to look at balanced binary tree which is lead code balanced binary tree which is lead code problem 110 this problem states that given a binary tree determine if it is height balanced for this problem a height balanced binary tree is defined as a binary tree in which the left and right sub trees of every node differ in height by no more than one so if you look at example one here you see that the three has a left branch and it also has a right branch which is longer but if you take the right branch which is length two and subtract the left branch of length one you get one and so it can differ by at least one or at the most one so this is true but but barely and again to read this it's 3 9 20 and then the null null is because the nine has no left or right Branch then 15 and seven now example two is a nogo because even though each of these nodes is differ by no more than one the distance from here to the four is definitely more than one than the distance from the one to the two here false all right let's see how we're false all right let's see how we're going to do this I question whether some of the this is marked as easy and I question whether it's an easy one but anyway more binary tree fund with recursion so here is the method lead code gives us so basically if the root is null we're going to return true um there's no reason the left and right are both empty so as far as we're concerned it's balanced then we're going to return the height so we need to determine the height of the root and to do this we're going to compare the left to the right and if when we run this method and it returns a negative one then that will return a false otherwise anything that's not equal NE 1 will return true all right so let's define this method it's going to pass back an integer and we'll pass in the node the tree node node okay so if node is null we're going to return zero meaning that the node yeah if node yeah okay so yeah the node left or right we're going to end up assigning this to the left or right so if it if it doesn't have a left or right right it's going to return zero so int left equals we're going to call height again more recursion but this time we're going to pass the node. left and then we need to check the right value of the node to so we're going to right now we're going to determine the right now we're going to determine the distance between left and right so we're distance between left and right so we're do a math.abs which is short for do a math.abs which is short for absolute which basically means any absolute which basically means any number that's negative is just going to number that's negative is just going to be returned as positive so we're going be returned as positive so we're going to subtract left minus right in the case to subtract left minus right in the case where right is greater than left it where right is greater than left it doesn't matter because we're doing doesn't matter because we're doing absolute absolute value so if the distance is greater than value so if the distance is greater than one which was what leite code deemed one which was what leite code deemed as um balanced is if it's one or less or as um balanced is if it's one or less or if the left is equal to negative one or if the left is equal to negative one or the right is equal to negative one then the right is equal to negative one then we're going to return negative one which we're going to return negative one which will'll return will'll return false otherwise we're going to return false otherwise we're going to return one for the current node plus the max of one for the current node plus the max of the math Max of either the left or the the math Max of either the left or the right and that is it so let's run this right and that is it so let's run this through the debugger oh yeah I got my handy chart here too okay so we're going to take the first problem here basically I recreated this tree and now we're going to run through balanced balanced okay so the first thing we're going to okay so the first thing we're going to do is take the root now if you look here do is take the root now if you look here the root node is the root node is three it's not three it's not false so now we need to figure out the false so now we need to figure out the height so we come down here the node is height so we come down here the node is not null so now we need to determine the not null so now we need to determine the left left node so node left now we're back in node so node left now we're back in height but we're now using the value height but we're now using the value Nine and Nine does not have a left and Nine and Nine does not have a left and so we go to the right nine does not have so we go to the right nine does not have a right either so that returns a right either so that returns null now we're going to close out the null now we're going to close out the nine we're going to take the distance nine we're going to take the distance between the left and right which is just between the left and right which is just going to be zero because it doesn't have going to be zero because it doesn't have left or right and none of these are true left or right and none of these are true and so it's just going to return itself and so it's just going to return itself basically 1 basically 1 plus left and right plus left and right so that is what we got okay so now we so that is what we got okay so now we are on back to the three and we've done are on back to the three and we've done the left now we need to go on to the the left now we need to go on to the right okay so now we have the right okay so now we have the 20 20 has a node left so now we're into 20 20 has a node left so now we're into the the 15 it's not all but the 15 doesn't have 15 it's not all but the 15 doesn't have a left and it doesn't have a a left and it doesn't have a right so now we're going to right so now we're going to determine the distance between the left determine the distance between the left and the right which is zero none of and the right which is zero none of those are true and it returns those are true and it returns one so this is now the value of the 20 one so this is now the value of the 20 has one left and its distance is has one left and its distance is one so now we'll go on to the right one so now we'll go on to the right value or the right branch of the value or the right branch of the 20 and so here we are with the seven and 20 and so here we are with the seven and the Seven doesn't have a left doesn't the Seven doesn't have a left doesn't have a right so again have a right so again zero for left minus right absolute value zero for left minus right absolute value and distance is not greater than one and distance is not greater than one left and right are not equal to negative left and right are not equal to negative 1 so it will also pass 1 so it will also pass left okay so now we're back to the 20 left okay so now we're back to the 20 and the 20 has a left of one and a right and the 20 has a left of one and a right of of one so we took the absolute value of one so we took the absolute value of that and the distance is not greater that and the distance is not greater than than one distance is than than one distance is zero math so one plus left and zero math so one plus left and right all right so now we're back to the right all right so now we're back to the three and we're going to the right we three and we're going to the right we finished off the right so we have a finished off the right so we have a distance of two the right has a distance distance of two the right has a distance of two the you know 20 to the 15 to the of two the you know 20 to the 15 to the to the seven is two away from the three to the seven is two away from the three but the left is one because we have the but the left is one because we have the nine branch and so we're going to take 1 nine branch and so we're going to take 1 - 2 which is negative 1 but absolute - 2 which is negative 1 but absolute will make it one and so that is not will make it one and so that is not greater than one and left and right are greater than one and left and right are not equal to negative not equal to negative one and so we're going to one and so we're going to return this actually this really doesn't return this actually this really doesn't even matter we're take the max of left even matter we're take the max of left and right plus one so it'll be three but and right plus one so it'll be three but all we're looking for is the Boolean or all we're looking for is the Boolean or that that it I'm sorry it I'm sorry the yeah yeah the integer we're looking the yeah yeah the integer we're looking for the integer here so this um as long for the integer here so this um as long as it's not equal to negative 1 it's as it's not equal to negative 1 it's going to return true and that's exactly going to return true and that's exactly what it does so this tree is what it does so this tree is balanced all right let's put it through balanced all right let's put it through leak code here run it with that first example it is accepted and then we run the code oops run it twice just to be sure look submission all right so let's go through submission all right so let's go through the space and time complexity so time the space and time complexity so time complexity is O of complexity is O of n increase the number of nodes it's n increase the number of nodes it's going to increase the execution time go going to increase the execution time go through all those through all those nodes and then because I did the height nodes and then because I did the height balanced determine if a or make the tree balanced determine if a or make the tree height balanced in my last video and height balanced in my last video and that was log of n but because the tree that was log of n but because the tree doesn't have to be height balanced in doesn't have to be height balanced in this case we're checking for that it's this case we're checking for that it's just o of just o of N and that is N and that is it so as always let me know if you have it so as always let me know if you have questions thanks for watching and we'll questions thanks for watching and we'll see you next time | 2024-03-21 10:36:07 | 110 | [SOLVED!] Balanced Binary Tree - LeetCode 110 - Java |
|
Pd_N0MKdQtQ | hey guys let's paws Finnegan is chaser in this video I'm going to take a look in this video I'm going to take a look at 1 4 6 1 check away the string at 1 4 6 1 check away the string contains all binary codes of size k give contains all binary codes of size k give me the binary string s and integer K me the binary string s and integer K return true if all binary codes from return true if all binary codes from this K is a substring chops as otherwise this K is a substring chops as otherwise return false while the battery codes up return false while the battery codes up to R then to where 0 0 to 1 1 0 1 1 and to R then to where 0 0 to 1 1 0 1 1 and they can be all found in straps they can be all found in straps substrates substrates while the good for searching for this while the good for searching for this solution for this problem is very simple solution for this problem is very simple I think we find all the possible means I think we find all the possible means of the binary codes which will be 2 to of the binary codes which will be 2 to the power of K and for each we'll search the power of K and for each we'll search right service search or cost us s then right service search or cost us s then go to say n so this is the time this is go to say n so this is the time this is the time complexity I think well if we the time complexity I think well if we search on the string every time for any search on the string every time for any the binary form it will cost a lot of the binary form it will cost a lot of time rather we could do it in a reverse time rather we could do it in a reverse way we get all the strings and then we way we get all the strings and then we just check if if 0 0 exists in a just check if if 0 0 exists in a constant time right which say get all constant time right which say get all substrings substrings and then check existence by constant and then check existence by constant time so with that case we actually could time so with that case we actually could improve it to go 2 to the power of K no improve it to go 2 to the power of K no we don't need to actually track check we don't need to actually track check the park' because the input are all the park' because the input are all valid we can adjust to check the size valid we can adjust to check the size okay this will use a set and just to okay this will use a set and just to check this check to set size it is check this check to set size it is constant constant well we cool right well we cool right ok now we just need to traverse through ok now we just need to traverse through the string and get the two of the power the string and get the two of the power of K an end of cake right so we get of K an end of cake right so we get substrate substring of cake costume who substrate substring of cake costume who you just say substrains raise a set and you just say substrains raise a set and worry that I to 0 I plus K minus one if worry that I to 0 I plus K minus one if if distance is 1 then the meant is I if distance is 1 then the meant is I itself right class one management so itself right class one management so this is the ending the ban was plus so this is the ending the ban was plus so we we just add a suction to it right s slice cool and what we need we just returned we just check because the input is all valid binary string we just check the size staring the size 42 to the power K right it equals way then all by reforms are in its radical I think we're doing great yeah or accepted and let's try to unless the time typically time this will cost us as linear time and for the slice forecasters came so yeah okay inkay and space we were at those who've acosta step to spawn okay right okay that's all for this problem for the help I'll see you next time every time we first subject problem rather than we gets the substring and search maybe we can do the reverse way and find all the possible sub strings and just to check them tip the easy distance by one by constant time but in strict special case like this problem we just check the site so we need to do it in a flexible way I'll be out of | 2024-03-21 02:52:02 | 1,461 | LeetCode 1461. Check If a String Contains All Binary Codes of Size K | JSer - JavaScript & Algorithm |
|
qt2Ie--jAVI | welcome back for another video we are going to do another legal we are going to do another legal question question the question is the question is second largest digit in a string given an alphanumeric string s return the second largest numerical digi that appears in s or negative one if it does not exist a alphanumeric string is a string consisting of lowercase english letters and digits example 1 s is d f a 1 2 3 2 1 a f d the output is 2 the digits that appear in s the digits that appear in s are 1 2 3. are 1 2 3. the second largest digi the second largest digi is is 2 example 2 s is a b c 1 1 1 1 the output is explanation explanation the digits that appear in s the digits that appear in s are are 1. there is no second largest digit let's work for the code we can use hash set to solve the question we first iterate full characters of string if the character is a digit and not in a set finally finally if there are more than one elements in if there are more than one elements in the set the set return the second largest digi return the second largest digi in the string in the string else else return negative one time complexity is o n space complexity is the solution works thank you if this video is helpful please like this video and subscribe to the channel | 2024-03-22 14:52:12 | 1,796 | Second Largest Digit in a String - LeetCode 1796 - Java Solution |
|
eGFZc3SwcoE | hello and welcome back to the cracking Fang YouTube channel today we're solving Fang YouTube channel today we're solving lead code problem lead code problem 1,740 find distance in binary tree given 1,740 find distance in binary tree given the root of a binary tree and two the root of a binary tree and two integers p and Q return the distance integers p and Q return the distance between the nodes of p and value Q uh in between the nodes of p and value Q uh in the tree the distance between two nodes the tree the distance between two nodes is the number of edges on the path from is the number of edges on the path from one to the other so let's look at an one to the other so let's look at an example we have this binary tree here example we have this binary tree here and we want to find the distance between and we want to find the distance between the node p and the node uh sorry P equal the node p and the node uh sorry P equal 5 and Q equals 0 so that's this node and 5 and Q equals 0 so that's this node and this node uh we can pretty easily see this node uh we can pretty easily see that we go from 5 to three that's one that we go from 5 to three that's one from 3 to one that's two steps and then from 3 to one that's two steps and then from one to zero is three steps so from one to zero is three steps so that's how we get our solution of three that's how we get our solution of three here so this problem is pretty here so this problem is pretty straightforward if you're just looking straightforward if you're just looking at the graph like your brain can very at the graph like your brain can very easily solve it but how do we do this in easily solve it but how do we do this in code so there's two approaches here um code so there's two approaches here um and I'll kind of say both of them and and I'll kind of say both of them and we'll code one of them up uh the first we'll code one of them up uh the first one is the least common ancestor one is the least common ancestor approach so what we want to do is in the approach so what we want to do is in the graph we'll find each node and then we graph we'll find each node and then we will basically find the lowest kman will basically find the lowest kman ancestor of them uh and we'll keep the ancestor of them uh and we'll keep the distance to the lowest common ancestor distance to the lowest common ancestor so if you remember we solved the lowest so if you remember we solved the lowest common ancestor problem um on this common ancestor problem um on this channel but basically we would find it channel but basically we would find it which is three here and we're going to which is three here and we're going to keep track of the distance of each node keep track of the distance of each node to the least common ancestor so from to the least common ancestor so from this side it' be V1 from this side of V2 this side it' be V1 from this side of V2 and then simply add them together and we and then simply add them together and we get the solution now some people on leak get the solution now some people on leak code say that this is a one pass code say that this is a one pass solution but I don't think so because solution but I don't think so because they're calling their DFS function to they're calling their DFS function to find both nodes now if your tree looks find both nodes now if your tree looks like a linked list where it's like this like a linked list where it's like this and let's just say it's really long and and let's just say it's really long and Q is here and P is here you're going to Q is here and P is here you're going to do a search all the way to P to find p do a search all the way to P to find p and then you have to do the same search and then you have to do the same search to do Q so people who say that it's one to do Q so people who say that it's one pass this is not true because I think in pass this is not true because I think in this case you would have to do two this case you would have to do two passes because you're basically passes because you're basically traversing the entire tree um if they're traversing the entire tree um if they're just one node apart and Q is the last just one node apart and Q is the last node in this like linked list type tree node in this like linked list type tree um then you're actually going to do um then you're actually going to do basically two passes through the tree so basically two passes through the tree so anyone who says it's one pass I'm not anyone who says it's one pass I'm not too sure about that one anyway that's too sure about that one anyway that's the least common ancestor one I don't the least common ancestor one I don't really like that approach I would much really like that approach I would much prefer to do it as a graph and we've prefer to do it as a graph and we've done this question before it's just been done this question before it's just been in a different word so actually we're in a different word so actually we're going to build a graph um which Maps I going to build a graph um which Maps I guess like each node to all of its edges guess like each node to all of its edges uh node to its edges right so basically uh node to its edges right so basically where from each place we can go and in where from each place we can go and in this way we can basically just start our this way we can basically just start our search at either P or q and then with search at either P or q and then with the graph we're just going to Traverse the graph we're just going to Traverse it uh Traverse the graph and then it uh Traverse the graph and then basically just BFS until we get to um basically just BFS until we get to um either P or Q to find and then that is either P or Q to find and then that is going to be our distance and we simply going to be our distance and we simply return that so that solution obviously return that so that solution obviously to build the graph you have to daverse to build the graph you have to daverse the entire thing so it's going to be Big the entire thing so it's going to be Big O of n to do that and then potentially O of n to do that and then potentially in the worst case it's going to be also in the worst case it's going to be also a big O of n uh in the case that you a big O of n uh in the case that you have a graph that's like this or a tree have a graph that's like this or a tree that's like this where p is here and Q that's like this where p is here and Q is here you have to basically Traverse is here you have to basically Traverse all the way up this way and then all the all the way up this way and then all the way up the right side so that's why I way up the right side so that's why I could potentially have to visit all the could potentially have to visit all the nodes in the worst case but at the end nodes in the worst case but at the end of the the day the time complexity is of the the day the time complexity is still going to be Big O of n same with still going to be Big O of n same with the LCA uh and then also the space the LCA uh and then also the space complexity is also going to be Big O of complexity is also going to be Big O of n for the graph and then yeah for your n for the graph and then yeah for your BFS you're also going to need Big O of n BFS you're also going to need Big O of n so it's just big O of n plus Big O ofn so it's just big O of n plus Big O ofn but ASM totically it's also just Big O but ASM totically it's also just Big O of n so yeah you have two options here of n so yeah you have two options here again you can go with the least common again you can go with the least common ancestor approach or you can go with the ancestor approach or you can go with the graph approach personally I like the graph approach personally I like the graph approach the time complexities graph approach the time complexities will be the same space complexity are will be the same space complexity are the same I think explaining the graph is the same I think explaining the graph is a bit easier um but this is just a good a bit easier um but this is just a good example that for one question there are example that for one question there are potentially multiple Solutions and in an potentially multiple Solutions and in an interview it's actually good to list interview it's actually good to list them out um and then you can just go them out um and then you can just go with whichever one you want obviously if with whichever one you want obviously if one was more efficient than other than one was more efficient than other than the other then you should do the more the other then you should do the more efficient one but in the case here where efficient one but in the case here where they're the same time and space they're the same time and space complexity I'm just going to go with the complexity I'm just going to go with the graph solution because I like that one graph solution because I like that one better and it's easier for me to explain better and it's easier for me to explain so again we're going to build the graph so again we're going to build the graph um of basically all the nodes we can um of basically all the nodes we can reach from a given node and then we're reach from a given node and then we're just going to start our BFS from let's just going to start our BFS from let's just say p and we're going to BFS until just say p and we're going to BFS until we get to q and then however many steps we get to q and then however many steps it takes that's how long it is um it takes that's how long it is um between them so that's how we want to between them so that's how we want to solve it let's go to the code editor and solve it let's go to the code editor and type this up okay so we went over the type this up okay so we went over the intuition we went over two possible intuition we went over two possible solutions and now we're going to code solutions and now we're going to code one of them up first thing we want to do one of them up first thing we want to do is let's just clear away all this kind is let's just clear away all this kind of boiler plate and just have a clean of boiler plate and just have a clean working environment working environment so first thing we need to check is so first thing we need to check is actually if P equals Q we don't need to actually if P equals Q we don't need to do anything obviously the distance do anything obviously the distance between two nodes which are the same are between two nodes which are the same are going to be um zero right and one thing going to be um zero right and one thing that we need to actually realize if we that we need to actually realize if we look at the constraints of the problem I look at the constraints of the problem I probably should have said this before is probably should have said this before is that all the values are uh unique and that all the values are uh unique and that P and Q exist in the tree so if P that P and Q exist in the tree so if P equals Q oops how do I get rid of this equals Q oops how do I get rid of this okay fold um then we're done so if P okay fold um then we're done so if P equals to Q then we return Zer because equals to Q then we return Zer because of the same node okay so we want to of the same node okay so we want to build our graph and remember we're going build our graph and remember we're going to be mapping for each node basically to be mapping for each node basically all the other nodes that you can reach all the other nodes that you can reach um in that tree so we're going to say um in that tree so we're going to say the graph is going to be collections. the graph is going to be collections. default dict and this is going to be a default dict and this is going to be a list now to do this we're going to have list now to do this we're going to have to BFS over archery and basically build to BFS over archery and basically build the graph uh node by node so we're going the graph uh node by node so we're going to say uh we need a q here to basically to say uh we need a q here to basically process everything so so we're going to process everything so so we're going to say Q equals say Q equals collections. default dict oh sorry not collections. default dict oh sorry not default dict um uh deck we want to use a default dict um uh deck we want to use a q uh and we're going to pass in the root q uh and we're going to pass in the root now we're going to say while we have now we're going to say while we have something to process and if I could just something to process and if I could just type today that'd be great we're going type today that'd be great we're going to say the current node is going to be to say the current node is going to be q.p left and now what we want to do is q.p left and now what we want to do is if the left node exists then we want to if the left node exists then we want to populate um that relationship in the populate um that relationship in the graph and also if the right node exists graph and also if the right node exists we want to populate that relationship in we want to populate that relationship in the graph so we're going to say if node. the graph so we're going to say if node. left we're going to say graph of node. left we're going to say graph of node. Val and the reason that we're storing Val and the reason that we're storing the values here is because they're all the values here is because they're all unique um we actually AR we don't need unique um we actually AR we don't need to actually store the nodes themselves to actually store the nodes themselves we can just store the values because we can just store the values because they're guaranteed to be unique we don't they're guaranteed to be unique we don't have to worry about any sort of have to worry about any sort of duplicates or anything um so we can just duplicates or anything um so we can just store the values directly so we're going store the values directly so we're going to say there's going to be an edge which to say there's going to be an edge which goes from node. Val to um append node. goes from node. Val to um append node. left. Val and conversely we need to do left. Val and conversely we need to do the opposite because it's bidirectional the opposite because it's bidirectional um so we're going to say graph of node. um so we're going to say graph of node. left. valal um we're going to pend node. left. valal um we're going to pend node. Val and then we just need to append uh Val and then we just need to append uh that left node so it can be processed that left node so it can be processed further so we're going to say q. pend further so we're going to say q. pend node. left same thing for the right node node. left same thing for the right node we're going to say if node. right exists we're going to say if node. right exists we're going to say graph of node. Val we're going to say graph of node. Val we're going to to append node. WR doval we're going to to append node. WR doval and we're going to do the same thing for and we're going to do the same thing for node. write doval we're going to append node. write doval we're going to append um node um node doval okay so and then the last thing we doval okay so and then the last thing we need to do is we need to make sure we do need to do is we need to make sure we do q. pend node. write so it also can get q. pend node. write so it also can get processed so doing all of this will processed so doing all of this will build our graph now obviously we need to build our graph now obviously we need to process that graph so we're going to do process that graph so we're going to do a BFS we're going to start at node p and a BFS we're going to start at node p and we're going to search for node Q so what we're going to search for node Q so what we're going to do is we're going to say we're going to do is we're going to say a q is going to be collections. deck and a q is going to be collections. deck and we're going to populate Our Deck with we're going to populate Our Deck with what we're going to use a tuple and what we're going to use a tuple and we're going to start our node at p and we're going to start our node at p and obviously we've done zero steps so far obviously we've done zero steps so far so we're going to store that um we've so we're going to store that um we've done zero steps now whenever we do a BFS done zero steps now whenever we do a BFS we want to make sure that we actually we want to make sure that we actually don't get caught into a cycle obviously don't get caught into a cycle obviously our graph has bir directional edges and our graph has bir directional edges and we could actually go in a cycle if we we could actually go in a cycle if we didn't keep track of where we visited so didn't keep track of where we visited so we're going to say a visited set is we're going to say a visited set is going to equal to set and we're going to going to equal to set and we're going to put p in there because that's where we put p in there because that's where we start our search now all we need to do start our search now all we need to do is just kick off our BFS go from p and is just kick off our BFS go from p and then as soon as we hit Q we can stop and then as soon as we hit Q we can stop and then just return the number of steps we then just return the number of steps we took so we're going to say um while Q took so we're going to say um while Q we're going to say the current node that we're going to say the current node that we're processing and the number of steps we're processing and the number of steps we've taken is going to be q.p left and we've taken is going to be q.p left and we're going to say if the current node we're going to say if the current node it actually equals q and remember that it actually equals q and remember that um the current node we actually put the um the current node we actually put the value in there so we can just compare it value in there so we can just compare it to Q directly because p and Q are to Q directly because p and Q are actually integers uh they're not given actually integers uh they're not given to us as nodes so if the current node to us as nodes so if the current node equals Q we're done we found Q we can equals Q we're done we found Q we can simply return the number of steps it simply return the number of steps it took otherwise we need to consider uh took otherwise we need to consider uh continue our BFS so we're going to say continue our BFS so we're going to say for Edge in graph of whatever the for Edge in graph of whatever the current node is we're going to say if we current node is we're going to say if we haven't visited that edge obviously we haven't visited that edge obviously we don't want to get caught in a cycle here don't want to get caught in a cycle here so we're going to say if uh Edge not in so we're going to say if uh Edge not in visited then we want to visit that edge visited then we want to visit that edge so we're going to say visited. add. Edge so we're going to say visited. add. Edge and we're going to say q. append um what and we're going to say q. append um what the edge and then steps plus one because the edge and then steps plus one because now we need to go uh one step further now we need to go uh one step further and that's actually it we're done so as and that's actually it we're done so as soon as um this return trips up we will soon as um this return trips up we will be done there's nothing more we need to be done there's nothing more we need to do let me just make sure I didn't make do let me just make sure I didn't make any syntax mistakes and looks accepted any syntax mistakes and looks accepted submit this thing and it is accepted submit this thing and it is accepted cool so let us go over the time and cool so let us go over the time and space complexity uh we talked about this space complexity uh we talked about this earlier but basically to build the graph earlier but basically to build the graph is going to take Big O of end time and is going to take Big O of end time and then to BFS over it is going to take Big then to BFS over it is going to take Big O of end time so let's just do that so O of end time so let's just do that so we have the time complexity so this is we have the time complexity so this is Big O of n Big O of n um to build graph and then we need B AO um to build graph and then we need B AO of n to BFS graph so this means that of n to BFS graph so this means that it's Big O of n plus Big O of n which is it's Big O of n plus Big O of n which is Big O of 2 N but we know that ASM Big O of 2 N but we know that ASM totically this is the same as Big O of n totically this is the same as Big O of n space complexity it's the same thing space complexity it's the same thing it's going to take Big O of n um it's going to take Big O of n um to build the graph uh plus Big O of n to to build the graph uh plus Big O of n to BFS over it because we need to maintain BFS over it because we need to maintain the Q so again this is Big O of 2N which the Q so again this is Big O of 2N which ASM totically is just Big O of n which ASM totically is just Big O of n which is actually the same runtime complexity is actually the same runtime complexity of the least common ancestor solution so of the least common ancestor solution so both of them are the both of them are the same um but yeah okay so that is how you same um but yeah okay so that is how you solve fine distance in a binary tree I solve fine distance in a binary tree I quite like doing problems like this quite like doing problems like this where you basically take a binary tree where you basically take a binary tree transform it into a graph and then transform it into a graph and then Traverse that graph to get your answer I Traverse that graph to get your answer I really like that solution pattern I really like that solution pattern I don't know maybe it's just years of don't know maybe it's just years of working at Facebook and traversing working at Facebook and traversing graphs and nodes and all that I just graphs and nodes and all that I just like graph problems anyway that's how like graph problems anyway that's how you solve it if you enjoy the video why you solve it if you enjoy the video why not leave a like and a comment uh And not leave a like and a comment uh And subscribe to the channel really helps me subscribe to the channel really helps me grow otherwise thank you so much for grow otherwise thank you so much for watching and I will see you in the next watching and I will see you in the next one bye | 2024-03-20 18:01:13 | 1,740 | FIND DISTANCE IN BINARY TREE | LEETCODE 1740 | PYTHON GRAPH BFS SOLUTION |
|
GshuF1a9_Uc | [Music] tree iterator problem number 173 on leak tree iterator problem number 173 on leak code and you are to implement the bst code and you are to implement the bst iterator class so you have to implement the constructor for this class and then two methods one called next and the one next is called has next so um you're given uh the root of the tree in your constructor and then you're supposed to keep track of a pointer and just say return for this one you can just say what's the next one and this boolean is going to return true or false whether or not there is a next one given the route that was passed in the so so um um it says you may assume that the next it says you may assume that the next calls will always be valid you mean that calls will always be valid you mean that you don't have to check whether or not you don't have to check whether or not there is a has next before you return there is a has next before you return this next so for instance you're given this next so for instance you're given this tree here this tree here um um you would be past you would be past this route this route and then it would just tell you and then it would just tell you um um net when you're calling next you would net when you're calling next you would return three return three then seven then seven um then whether or not it has next you um then whether or not it has next you would say true because you're not at the would say true because you're not at the end of the tree um then you would return 9 if you're checking if it still has another one you will return true then 15 and then 20 and then you're going to return false because you don't have any more nodes left so um you can see clearly that um in this constructor we need to and and um instead of um instead of iterating through the entire tree we can iterating through the entire tree we can just keep a list too so just keep a list too so um we need an index um to keep track of the current position and that would say the next would increment the index from that node from that node has next would check has next would check to see to see if if you add one to the index um so probably the best thing to do is um so probably the best thing to do is to just take this route and we can just to just take this route and we can just make make a list from it so what we would do is a list from it so what we would do is first just traverse through the entire first just traverse through the entire list the entire list the entire tree tree add the values add the values to a list to a list and then we'll just keep track of an and then we'll just keep track of an index and just go through that index and just go through that so so um um when we call our constructor you can when we call our constructor you can even you can add these objects here in even you can add these objects here in this this public constructor method but i can even public constructor method but i can even just initialize them just initialize them um right at the top so um right at the top so we're just going to make an array list we're just going to make an array list of integers of integers i'm just going to call it l i'm going to i'm just going to call it l i'm going to initialize it right here and i'm also going to have a new index and i'm going to initialize it here too i'm going to start the index off at because i can always increment it before because i can always increment it before i call it so i call it so let's just let's just i can come back to that but let's just i can come back to that but let's just see how this works out so see how this works out so um um the first thing we're going to do is the first thing we're going to do is just make a list just make a list from this root we can even make this a void because we we can even make this a void because we have access to this list right here so have access to this list right here so we're just going to say we're just going to say void void make this list make this list and it's going to be this tree node root and it's going to be this tree node root that we pass through um we're going to just call this recursively so for our base case we'll say if root is null and we can just first we're going to go left then we're going to add it we're going to add this root value so that is um so that is um we're just traversing it we're first going left and then we're taking the center and then we're going right that's an in order traversal so this will be adding all of our root as soon as the constructor is called as soon as the constructor is called so so um um we are going to say we are going to say um start off with has next first so we're just checking to see if from our if we add one to it is that going to be less than if that is true it'll return true if it is false then it's going to return false and then to get the next value list and we are going to get the index list and we are going to get the index but before we get the index if we do the but before we get the index if we do the plus plus plus plus before that is going to increment it before that is going to increment it before we access the index so the first before we access the index so the first time the index is accessed it's going to time the index is accessed it's going to be a zero be a zero the next time it's accessed it's going the next time it's accessed it's going to be a one so if we do this plus plus to be a one so if we do this plus plus beforehand then we can always access the right index we want and then also we can use the index plus one here in case has next has been called first that is going to start off at zero so we're never going to access it as negative one but in this way we're not changing the value of the index here we're just checking to see if we have this index and we add one to it is it going to be less than the size we are going to actually change the value of the index here as we move to and so and so that is as simple as that again if you that is as simple as that again if you have there's different ways to have there's different ways to um um initialize objects you can just initialize objects you can just initialize them here you can also initialize them here you can also initialize them within the constructor initialize them within the constructor um just initializing them here and so um just initializing them here and so there's going to be access to them there's going to be access to them when we do this traversal through the tree and it's also going to be accessed here and here so that we're not passing it as a parameter we're just all accessing the same index and so that should work and so that should work okay okay um let me just put this here um let me just put this here okay thank you | 2024-03-21 14:08:29 | 173 | Binary Search Tree Iterator - Leetcode Java |
|
tzTi0itKCb8 | welcome to tim's leco challenge this problem is called search and rotated problem is called search and rotated sorted array 2. sorted array 2. there is an android num sorted in there is an android num sorted in non-decreasing order but not necessarily non-decreasing order but not necessarily with distinct values with distinct values before being passed to your function before being passed to your function nums is rotated at an unknown pivot nums is rotated at an unknown pivot index index such that the resulting index is such that the resulting index is basically rotated so if we had basically rotated so if we had this array here we're going to pick a this array here we're going to pick a pivot index pivot index take everything from that point on take everything from that point on this subarray and prepend it to the this subarray and prepend it to the beginning of our original array so it beginning of our original array so it looks like this at the end looks like this at the end now given this array after the rotation now given this array after the rotation and an integer target and an integer target return true if target is in nums return true if target is in nums or false if it is not in gnomes or false if it is not in gnomes so essentially so essentially uh uh this problem is definitely a binary this problem is definitely a binary binary search problem right and binary search problem right and originally this was going to be part of originally this was going to be part of a larger video with binary search a larger video with binary search problems but problems but i found this problem to be particularly i found this problem to be particularly difficult and it's very deceptive difficult and it's very deceptive because because really the only difference from the really the only difference from the rotated sorted array one is this rotated sorted array one is this distinct values allowed or disallowed so distinct values allowed or disallowed so with this question here with this question here duplicates are allowed duplicates are allowed but that changes a lot of edge cases but that changes a lot of edge cases here because what we want to do is find here because what we want to do is find that pivot index right that pivot index right but if we had duplicates allowed this but if we had duplicates allowed this becomes becomes much more difficult to do in log n in much more difficult to do in log n in fact it might even be impossible fact it might even be impossible so so for now let's just assume that for now let's just assume that everything is distinct everything is distinct if that was the case then what we would if that was the case then what we would do is find the pivot point and then we do is find the pivot point and then we would do a binary search would do a binary search using that pivot point to using that pivot point to adjust where our midpoint is adjust where our midpoint is everything else would be the same everything else would be the same so so say that we want to find our pivot how say that we want to find our pivot how do we do that well let's first start by do we do that well let's first start by getting our length getting our length of nums of nums and one edge case is if n equals to 1 we and one edge case is if n equals to 1 we just want to return just want to return whether whether the single number here is equal to the single number here is equal to target right and this will avoid some target right and this will avoid some edge case edge cases edge case edge cases next we want to calculate our l and r next we want to calculate our l and r pointer our left and right pointer which pointer our left and right pointer which would be zero and n minus one would be zero and n minus one finally let's do our binary search to finally let's do our binary search to find the pivot so find the pivot so while l is less than r while l is less than r let's calculate the midpoint to be l let's calculate the midpoint to be l plus r divided by two plus r divided by two how are we going to find this pivot well how are we going to find this pivot well if you remember from the original rotate if you remember from the original rotate distorted array problem what we want to distorted array problem what we want to do is check the mid and one of the ends do is check the mid and one of the ends say say the right and we want to see is say say the right and we want to see is the mid smaller than the right because the mid smaller than the right because if it is if it is that means everything's sorted properly that means everything's sorted properly here here there'll never be a case assuming that there'll never be a case assuming that there's no duplicates allowed where the there's no duplicates allowed where the mid is going to be larger mid is going to be larger than the than the index on the right index on the right and everything's stored properly that and everything's stored properly that doesn't make any sense right so the doesn't make any sense right so the pivot point has to be on the left side pivot point has to be on the left side so if nums not mid so if nums not mid if we find that this is smaller than if we find that this is smaller than nums dot r nums dot r that means everything from the right mid that means everything from the right mid to the right side is sorted properly so to the right side is sorted properly so the pivot has to be on the left side so the pivot has to be on the left side so that would mean let's make r equal to that would mean let's make r equal to mid mid now otherwise we're gonna make l equal now otherwise we're gonna make l equal to mid plus one to mid plus one and the reason i did it like this rather and the reason i did it like this rather than having minus one here is there's than having minus one here is there's some weird cases that happen when we some weird cases that happen when we have like have like let's say just there's two numbers left let's say just there's two numbers left and we're going to calculate the mid and we're going to calculate the mid right well technically the mid is going right well technically the mid is going to be the same as the left to be the same as the left and we want the right to just go to the and we want the right to just go to the mid we don't want to overshoot and go mid we don't want to overshoot and go like like uh before that right this is the pivot uh before that right this is the pivot not not the thing that comes before so not not the thing that comes before so that's why we did like this that's why we did like this um and um and that would be it really all that comes that would be it really all that comes after this would be to find our after this would be to find our actual target so this would be zero n actual target so this would be zero n minus one minus one let's do a normal binary search let's do a normal binary search and we would calculate the mid and we would calculate the mid to equal to equal well first i'm going to save the pivot well first i'm going to save the pivot point here point here call that pivot call that pivot and the mid is going to be equal to and the mid is going to be equal to again l plus r divided by two but let's again l plus r divided by two but let's calculate the actual mid call that a mid calculate the actual mid call that a mid can be equal to mid plus the pivot point can be equal to mid plus the pivot point and let's do a modular n in case we have and let's do a modular n in case we have to wrap around the array to wrap around the array now everything else is the same we say now everything else is the same we say if if the same as any binary search we'll say the same as any binary search we'll say if if nums nums actual mid is equal to target then actual mid is equal to target then return true return true else if nums else if nums actual mid is let's say less than target actual mid is let's say less than target well that means well that means um um the midpoint is less than the target so the midpoint is less than the target so we have to search the right side so make we have to search the right side so make l equal to mid plus one otherwise make r l equal to mid plus one otherwise make r equal to mid minus one equal to mid minus one and finally if we can't find anything and finally if we can't find anything then we just return plus then we just return plus and this would work fine if everything and this would work fine if everything was always distinct so let's like this was always distinct so let's like this example example this should work fine this should work fine and but once we have duplicates things get very wonky so if i were to like submit this i already know um it will not pass like so for example this case here what happens is we first check to see where the pivot point is we check uh left right middle right and we see okay everything's sorted properly here so must be on this side so now we check here and we don't know what to do like well looks like left is the same as mid we know technically we want to move we want to move all the way to the we want to move all the way to the beginning here but for this algorithm beginning here but for this algorithm there's no way for them to really know there's no way for them to really know which way to go so which way to go so if i was to do something like if i was to do something like well all right like else if let's say well all right like else if let's say numbs on mid uh say that numbs on mid uh say that it turns out to be greater than numbers it turns out to be greater than numbers that are then we want this otherwise that are then we want this otherwise let's just say let's just say l minus one so like this l minus one so like this okay and this would be kind of like okay and this would be kind of like we're doing binary search but if we we're doing binary search but if we don't know what to do we'll just don't know what to do we'll just decrease our decrease our our left pointer or right pointer or our left pointer or right pointer or whatever this would be right pointer whatever this would be right pointer right right yeah but yeah but technically this works for a lot of a technically this works for a lot of a lot of the problems but this won't work lot of the problems but this won't work for some certain cases like if we had for some certain cases like if we had say one uh let's say you won't say one uh let's say you won't uh uh we'll be good example one one one maybe we'll be good example one one one maybe like zero one something like this like like zero one something like this like say we had something like this say we had something like this well we don't know where to go right so technically we would move our right pointer back like this but but ultimately what's going to happen is like we've kind of lost our so okay sorry this isn't the best so okay sorry this isn't the best example actually but example actually but basically what happens is there's going basically what happens is there's going to be a lot of cases where we're going to be a lot of cases where we're going to lose the index point that we want so to lose the index point that we want so like like um if we just we don't know which way to um if we just we don't know which way to move should we make our right pointer move should we make our right pointer left left uh decrease just one or should make the uh decrease just one or should make the left pointer increase by one left pointer increase by one because there's certain edge cases where because there's certain edge cases where it's not going to fly um if we want to it's not going to fly um if we want to get that index point get that index point certain things will uh fall out certain things will uh fall out uh yeah so uh yeah so basically that's just a long way of basically that's just a long way of saying it's kind of impossible to find a saying it's kind of impossible to find a pivot point pivot point unless we have a while loop to just unless we have a while loop to just ignore the duplicates altogether so what ignore the duplicates altogether so what we might do here is say all right we might do here is say all right instead of all this we'll say while l is instead of all this we'll say while l is less than r less than r let's say look if um numbers are r minus let's say look if um numbers are r minus one if it equals nums that are one if it equals nums that are all right we're just going to completely all right we're just going to completely ignore it okay and we'll just say ignore it okay and we'll just say r my square one i will do the same thing r my square one i will do the same thing here let's say num l plus one this is here let's say num l plus one this is both l both l we're going to increase our l here we're going to increase our l here and and we can do this to kind of avoid a lot of we can do this to kind of avoid a lot of the edge cases so let's just like take the edge cases so let's just like take this for example this for example um um and this should work and it looks like it so let's go ahead and submit that so yeah this technically works um although it's kind of not very good right because worst case scenario is going to be an o of n um but really because of those duplicates it becomes unavoidable um to find this worst case scenario now one other way we can go about this is actually not even worry about the pivot there's technically you could kind of reframe this problem because i kind of got led astray by trying to follow the very first problems approach a better way to kind of think about this is rather than having all finding the pivot point instead we can think of all the different cases that occur knowing what we know so rather than having this pivot point and then doing a binary search what we might try to do is say okay while l is less than or equal to r let's calculate the midpoint right and first thing let's first get rid of our duplicates okay so we can say get rid of our duplicates then calculate our midpoint then calculate our midpoint and what we'll do is again try to check and what we'll do is again try to check to see to see if it's sorted correctly on the right if it's sorted correctly on the right side side because one of the things we can figure because one of the things we can figure out pretty quickly is all right look if out pretty quickly is all right look if everything's sorted on the right side everything's sorted on the right side here here then all we need to do is check all then all we need to do is check all right right is the target is the target between between nums.mid and numbs r because if it is nums.mid and numbs r because if it is then we know okay we gotta move to the then we know okay we gotta move to the left left side here right left left side here right so if we find this is the case what we so if we find this is the case what we can do is say all right check to see if can do is say all right check to see if nums.mid nums.mid is it less than equal to target and is is it less than equal to target and is nums dot nums dot r is it r is it greater or equal to target greater or equal to target and if that's the case we know that we and if that's the case we know that we want to move to the right side of our want to move to the right side of our array so array so l will equal mid plus one l will equal mid plus one right yeah otherwise it's got to be on right yeah otherwise it's got to be on the other side so r equals mid minus 1. now otherwise wondering if i need to do just else or wondering if i need to do just else or do it like this but well let's let's see if this works we'll say else this i forgot sorry i will first check the i forgot sorry i will first check the very first thing is nums mid if this very first thing is nums mid if this equals target equals target then return true right then return true right else if this then this if case else else if this then this if case else the only other case that means the only other case that means um um the pivot has to be on the left side the pivot has to be on the left side so what we want to check is so what we want to check is if num nums.mid is wait it's going to be on the left side i'm sorry no pivot's on the right side i'm sorry no pivot's on the right side because otherwise pivot's on the right because otherwise pivot's on the right side so then we want to check okay side so then we want to check okay everything's stored on the left side so everything's stored on the left side so it's nums dot mid it's nums dot mid is it is it greater or equal to target and it's greater or equal to target and it's numbers.l numbers.l less less or equal to target or equal to target okay that means it's got to be on okay that means it's got to be on the left side so r the left side so r equals equals minus one minus one l plus one finally if none of these fly then return to and let's see if this works i may have messed something up and there we go and there we go so i might have made this sound a lot so i might have made this sound a lot easier easier but believe me this is pretty but believe me this is pretty complicated and it complicated and it took me a really long time to get to took me a really long time to get to this solution um in fact i didn't even this solution um in fact i didn't even come up with this one this one i had to come up with this one this one i had to i had to look up some of the solutions i had to look up some of the solutions but my original solution that took but my original solution that took a really long time for me to figure out a really long time for me to figure out and it was very deceptive because i felt and it was very deceptive because i felt like this was an easy problem um like this was an easy problem um but you know sometimes but you know sometimes sometimes you get humble because you sometimes you get humble because you think you know it and then start coding think you know it and then start coding it out and turns out it's way more it out and turns out it's way more complicated than you thought complicated than you thought so i hope this helps a little bit um so i hope this helps a little bit um don't feel bad if you don't get it don't feel bad if you don't get it because because i think yeah it takes some practice to i think yeah it takes some practice to kind of understand what's going on here kind of understand what's going on here so so all right thanks for watching my channel all right thanks for watching my channel remember do not trust me i know nothing | 2024-03-20 12:16:17 | 81 | Leetcode - Search in Rotated Sorted Array II (Python) |
|
6M7QoVTRgSE | hey everyone today we are going to solve the readable question number of Music the readable question number of Music playlist so your music player contains playlist so your music player contains any different songs so you want to any different songs so you want to listen to your gold songs not listen to your gold songs not necessarily different during your trip necessarily different during your trip to avoid your boredom you will create a to avoid your boredom you will create a playlist so that every song is played at playlist so that every song is played at least once a song can only be played least once a song can only be played again only if okay other songs has have again only if okay other songs has have been played so you are given any goal been played so you are given any goal and K return the number of possible and K return the number of possible playlists that you can create since the playlists that you can create since the answer can be very large return is a answer can be very large return is a module 10 to the power of 9 plus 7 okay module 10 to the power of 9 plus 7 okay so let me explain a main point to solve so let me explain a main point to solve this question to solve discussion I use this question to solve discussion I use a 3D dynamic programming and we access a 3D dynamic programming and we access like a DPI and J so dbij represents the like a DPI and J so dbij represents the number of positive credits of length I number of positive credits of length I containing exact J unique sum so in the containing exact J unique sum so in the end our goal is to return the like a end our goal is to return the like a playlist of lengths go playlist of lengths go and using a exact n unixon and using a exact n unixon okay at first let's consider the okay at first let's consider the scenario where we are the new song that scenario where we are the new song that hasn't been played yet to to the hasn't been played yet to to the playlist as the playlist links increase playlist as the playlist links increase by one like from I minus 1 to I by one like from I minus 1 to I uh the number of unique song also uh the number of unique song also increased by one right from J minus 1 to increased by one right from J minus 1 to J J so that's why for each playlist of so that's why for each playlist of lengths I minus 1 with J minus one lengths I minus 1 with J minus one unique song we can add a new song to unique song we can add a new song to make the playlist length I and the make the playlist length I and the number of unique song J number of unique song J so in this scenario so how many new so in this scenario so how many new songs are available for us to choose songs are available for us to choose from from so at this point so at this point so the playlist contains J minus 1 right so the playlist contains J minus 1 right and since there are and since there are total of any unique song the number of total of any unique song the number of new song we can add to playlist is n new song we can add to playlist is n minus minus J minus J minus one right one right so so more precisely so n more precisely so n minus J Plus minus J Plus one right one right so now we are talking about the this so now we are talking about the this part and then with n minus J plus one choice for a new song so the number of new playlists we can create by adding a new song is so DP I minus 1 and J minus 1 is our previous result multiply so number of new song right so that's why we keep this result to current new um like a DPI and J position okay so let's think about when we deployed all the song We already added to playlist so the playlist length increased by one from I I minus 1 to I right but the number of unique songs remain the same J right so as a result for each grade list of links I minus one we stay unique songs we can increase the playlist length to I by depending The Horizon while streaming and maintaining the number of unique songs as J so in this scenario so how many previous prayer song can we choose from at this point the playlist contains the J unique songs so we can choose from these jsons however uh due to the constraint that we cannot we cannot pray a song Until other song have been prayed so we cannot choose from the song played in the last case Lots so that's why if J is greater than k so in this case the number of all the song we can replay is J minus K right so given the opportunity to select from J minus K the number of new playlists we can create by replaying the old song is DPI and J unique song multiply J minus K song so that's why if this condition is true so we added this value to um DPI and J position okay so let's write Circle first of all um in size mode equals 10 to the power of 9 plus 7. and create a DP dpra so this is a 2d array so zero so inside zero and for underscore in range and the n plus one and uh for underscore in length and the ball first one and the first of all initialized zero zero position so zero zero position with one because uh so this is a empty playlist so definitely one right so after that so this is a main point I explained in the previous section so for I in range and then from I uh from 1 to go plus one and then we use one more folder for J in French and then from one to mean and the I or and plus one so this mean I N is solved to constrain the calculation within the range where the playlist length I does not exceed the total number of songs n so this expression ensures that the greatest length I is controlled and not to go beyond n and so on for example so when attempting to create a list with larger goal so potentially exceeding the value of n so it's not feasible to include more unique songs in the playlist than the total available n songs so that's why using your mean Ming i n becomes a crucial to limit the play list length I and then so after that so as I explained and then so after that so as I explained here so DP here so DP d p I and the J equal so DB I minus 1 and [Music] J minus 1 so previous result multiply so in this case as I explained earlier so n minus J plus one and then and then next we think about the uh we and then next we think about the uh we declared all the song We already added declared all the song We already added to playlist to playlist but there is a condition so if but there is a condition so if J is greater than k J is greater than k in the case so DB I and J in the case so DB I and J equal equal so DP I and J Plus TP I minus 1 and the minus k so after that return DP so after that return DP and a goal and a handsome and a goal and a handsome yeah that's it so let me submitted yeah yeah that's it so let me submitted yeah looks good and the time complexity of looks good and the time complexity of this solution should be order of gold this solution should be order of gold multiply n so we need to iterate over multiply n so we need to iterate over two dimensional DP table size like a two dimensional DP table size like a goal plus one by n plus one goal plus one by n plus one in each cell we perform constant time in each cell we perform constant time operation so that's why and the space operation so that's why and the space complexity is also order of gold complexity is also order of gold multiply n so we create a 2d array so multiply n so we create a 2d array so goal multiply n so that's why goal multiply n so that's why yeah so that's all I have for you today yeah so that's all I have for you today if you like it please subscribe the if you like it please subscribe the channel hit the like button or leave a channel hit the like button or leave a comment I'll see you in the next comment I'll see you in the next question | 2024-03-25 11:02:34 | 920 | Number of Music Playlists - LeetCode #920 | Python, JavaScript, Java and C++ |
|
IFHgIS8laE0 | hi guys today let's discuss the lead code question 46 permutations given an code question 46 permutations given an array nums of distinct integers return array nums of distinct integers return all possible permutations you can return all possible permutations you can return the answer in any order so permutations the answer in any order so permutations is the arrangement of the given is the arrangement of the given numbers so let's go to the example one numbers so let's go to the example one so the example one nums is equal to 1A so the example one nums is equal to 1A 2A 3 since the length of this nums is 2A 3 since the length of this nums is three we'll be getting three factorial three we'll be getting three factorial arrangements so which is six arrangements so which is six so the output is 1A 2A 3 1A 3A 2 2A 1A 3 so the output is 1A 2A 3 1A 3A 2 2A 1A 3 2A 3A 1 and 3A 1A 2 and 3A 2A 1 so let's 2A 3A 1 and 3A 1A 2 and 3A 2A 1 so let's go to the example two so the input nums go to the example two so the input nums is 0a 1 so there will be two factorial is 0a 1 so there will be two factorial arrangements so which is two so the arrangements so which is two so the output is 0a 1 and 1A 0 and the example output is 0a 1 and 1A 0 and the example three is num is 1 and output is also one three is num is 1 and output is also one so there is only one factorial which is so there is only one factorial which is one Arrangement possible let's go to the one Arrangement possible let's go to the constraint section as constraint section as well so the constraints is nums do well so the constraints is nums do length uh ranges from 1 to 6 and nums of length uh ranges from 1 to 6 and nums of I the values can be from Min - 10 to 10 I the values can be from Min - 10 to 10 and all the integers of nums are unique and all the integers of nums are unique so there are no Corner cases to this so so there are no Corner cases to this so there exists at least uh nums do length there exists at least uh nums do length will be at least one and it is less than will be at least one and it is less than 6 less than or equal to 6 and nums is 6 less than or equal to 6 and nums is from - 10 to 10 and they're all unique from - 10 to 10 and they're all unique so we need not handle any of the corner so we need not handle any of the corner cases I hope it is very clear from this cases I hope it is very clear from this question description let's go into the question description let's go into the explanation part of it for the purpose explanation part of it for the purpose of explanation let's consider the nums of explanation let's consider the nums to be 1A 2A to be 1A 2A 3 so with this 1 comma 2 comma 3 let's 3 so with this 1 comma 2 comma 3 let's look at the recursion tree and how we look at the recursion tree and how we are going to arrive at all the are going to arrive at all the permutations so from this we'll be permutations so from this we'll be getting three branches out of which the getting three branches out of which the first branch is going to first branch is going to be 1 and 2 comma 3 so so here 1 be 1 and 2 comma 3 so so here 1 represents let's assume this one as a represents let's assume this one as a permutation and 2A 3 as a remainder of permutation and 2A 3 as a remainder of the nums so which means that all the the nums so which means that all the nums are not utilized and the first one nums are not utilized and the first one is going to be the permutation and the is going to be the permutation and the second branch is going to be 2 and 1A 3 second branch is going to be 2 and 1A 3 and the third branch is going to be 3 and the third branch is going to be 3 and 1A 2 now let's look at the recursion and 1A 2 now let's look at the recursion tree for the next level so where we are tree for the next level so where we are going to pass uh we are going to split 2 going to pass uh we are going to split 2 comma 3 further and we are going to comma 3 further and we are going to arrive at two more arrive at two more branches and the two branches that we branches and the two branches that we that we arrive at are 1A 2 and 3 and 1A that we arrive at are 1A 2 and 3 and 1A 3 and 2 so these two represents the 3 and 2 so these two represents the first one 1A 2 and 1A 3 represents the first one 1A 2 and 1A 3 represents the permutation and the remainder of nums is permutation and the remainder of nums is 3 and two let's look at the different 3 and two let's look at the different branches that we are going to arrive branches that we are going to arrive from 2 and 1A from 2 and 1A 3 so we are going to arrive at 2 comma 1 3 so we are going to arrive at 2 comma 1 and 3 and 2 comma 3 and 1 let's look at and 3 and 2 comma 3 and 1 let's look at the BR uh third branch that is 3 and 1 the BR uh third branch that is 3 and 1 comma comma 2 so we are going to arrive at 3A 1 and 2 so we are going to arrive at 3A 1 and 2 and 3A 2 and 1 so from this level we 2 and 3A 2 and 1 so from this level we can see the remainder of nums is just can see the remainder of nums is just the length of it is just one so which the length of it is just one so which means that we are reaching the end of means that we are reaching the end of this recursion tree so the last step is this recursion tree so the last step is going to going to be the first one we are going to get a be the first one we are going to get a combination 1A 2 comma 3 and for the combination 1A 2 comma 3 and for the next one we are going to get a combin we next one we are going to get a combin we are going to get a permutation of 1A 3A are going to get a permutation of 1A 3A 2 and for the next one we are going to 2 and for the next one we are going to get a permutation of 2A 1A get a permutation of 2A 1A 3 and for the next one we are going to 3 and for the next one we are going to get a permutation of 2 comma 3A 1 and get a permutation of 2 comma 3A 1 and for the next one we are going to get a for the next one we are going to get a permutation of 3A 1A 2 and for the last permutation of 3A 1A 2 and for the last one we are going to get a permutation of one we are going to get a permutation of 3 comma 2 comma 3 comma 2 comma 1 finally we are going to store all of 1 finally we are going to store all of these these things yeah and finally we'll be things yeah and finally we'll be arriving at the uh required output I arriving at the uh required output I hope it is very clear from this hope it is very clear from this explanation let's go into the code explanation let's go into the code coding part of coding part of it let's start by creating an empty it let's start by creating an empty permutations list that is going to store permutations list that is going to store the results it is going to be an empty list then we are going to create a helper function in order to uh Aid with this permutations so we are going to store two arguments inside this so the first argument is going to be the permutation and the next argument is nums if if the length of permutation equal to equal to length of nums so which means that we have used all the numbers or integers that are provided in the nums in the permutation so which means that we have formed a permutation and we can store it in the permutations list so we are going to append permutations do append we are going to to append this permutation that we that we have computed else if the length is not equal which means that there is the remainder underscore nums list is uh not empty and which means that there are further elements that needs to be added to this permutation so in that case we are going to Loop through this remainder nums for of length of of length of remainder uncore remainder uncore nums and we are going to call this nums and we are going to call this helper function helper function on the plus remainder underscore nums of I we plus remainder underscore nums of I we are going to add this particular uh I are going to add this particular uh I index value of the remainder nums to index value of the remainder nums to this permutation and then we are going this permutation and then we are going to to uh uh we are going to just uh reduce the uh uh we are going to just uh reduce the size of this remainder underscore nums size of this remainder underscore nums so that is going to be remainder so that is going to be remainder underscore underscore nums of we are going to just exclude nums of we are going to just exclude this I value from this I value from it so it is going to be remainder it so it is going to be remainder underscore underscore nums here it will be I + 1 okay yeah I think it that's it we are going to call this helper function initially the permutation is going to be an empty list and uh remainder nums is going to be nums and finally we are going to permutations yeah I hope we are done permutations yeah I hope we are done let's quickly run the code yeah can only concatenate uh list not into to list yeah yeah I made a mistake so here this is going to be an integer value so we are going to add this one also in the form of a list now let's quickly run the well yeah it is accepted hope you like well yeah it is accepted hope you like the explanation for more such videos the explanation for more such videos please subscribe to my channel thank you | 2024-03-20 09:33:20 | 46 | Permutations | Backtracking | Python | LeetCode 46 | Top Interview 150 |
|
yYucAtqor40 | hello uh hello to all and welcome to my uh hello to all and welcome to my youtube channel youtube channel today we will be going to solve uh today we will be going to solve uh another lead code problem another lead code problem for problem number 18 16 the problem for problem number 18 16 the problem name is truncate sentence so name is truncate sentence so let's just read the problem sentence is let's just read the problem sentence is a list of words that is separated by a list of words that is separated by single space with no leading single space with no leading or training spaces each of the words or training spaces each of the words consists of only uppercase and lowercase consists of only uppercase and lowercase english letter english letter no punctuation basically here they are no punctuation basically here they are defining what is sentence for example defining what is sentence for example this hello world a sentence uh is a list this hello world a sentence uh is a list of what that contains a space or it can of what that contains a space or it can be lowercase or uppercase be lowercase or uppercase with no no punctuation mark so basically with no no punctuation mark so basically we are given a sentence and an integer k we are given a sentence and an integer k we want to create a truncate as such we want to create a truncate as such that it only contains first k that it only contains first k words written s after truncating it words written s after truncating it so there is the example so the sentence so there is the example so the sentence is hello how is hello how are you contestant so k equals to four are you contestant so k equals to four so it means that so it means that after uh we have to uh con after uh we have to uh con we have to return this hello our how are we have to return this hello our how are you string you string because uh the first four words are because uh the first four words are hello how are you hello how are you so similarly the ks4 and what is the so similarly the ks4 and what is the solution to this problem so what is the solution to this problem so what is the solution solution to is the uh output of this to is the uh output of this input okay so uh and this is another input okay so uh and this is another example that chopper is example that chopper is not a key so k equals to five so one two not a key so k equals to five so one two three four five so three four five so the whole sentence the first five words the whole sentence the first five words of the sentence of the sentence is already there so we return this edge is already there so we return this edge okay so i think the problem is very okay so i think the problem is very clear to you clear to you so let's just dive into four before so let's just dive into four before driving into code i will driving into code i will give you what was the logic behind this give you what was the logic behind this problem so problem so what we do we first traverse the whole what we do we first traverse the whole string string okay and we are given k so okay and we are given k so we decrementing uh k uh from we decrementing uh k uh from if uh suppose if we find a space so if uh suppose if we find a space so decrement our k decrement our k okay and then second space then third okay and then second space then third space and then fourth space space and then fourth space after we hit our fourth space and then k after we hit our fourth space and then k we decrementing our k then if k becomes we decrementing our k then if k becomes to zero to zero we return that substring of s okay we return that substring of s okay so i think the logic is clear to you if so i think the logic is clear to you if not not uh in code it will be very clear to you uh in code it will be very clear to you let's just type into code let's just type into code so i less than s dot [Music] a plus plus plus so first we travel through the string so if plus i first equals to a space and and minus minus k equals to zero so we're decrementing k we are pre-decrementing our key because if we did not do this so the space uh will gonna go here like in in this case um suppose suppose suppose that just k s equals to 1 so our answer would be only hello so the k we are pre decrementing so k equals to 0 and the condition will be true and so we written that substitution so ok so we return uh s dot sub str so it is inbuilt function that is returned in subreddit r in c plus plus written from 0 to i that is including 0 and excluding i okay and after that we return our s okay let's just submit our code yeah you could see that the test case is accepted our output matches let us submit our code okay so now it is run time is zero okay so now it is run time is zero million millisecond faster energy million millisecond faster energy solution solution let's just try and code uh uh let's just try and code uh uh this code so first time uh this code so first time uh when we traverse to this si does not when we traverse to this si does not equal to space aside equal to space aside s i equal to space here then k decrement s i equal to space here then k decrement it's pre-decremented ka value is four so it's pre-decremented ka value is four so three three doesn't equal to zero so three three doesn't equal to zero so redundant written here then k equal goes redundant written here then k equal goes to this to this then this index would be then k equals then this index would be then k equals to 2 to 2 and here k equals to 1 and here k equals and here k equals to 1 and here k equals to 0 to 0 so uh we saw we return the sub so uh we saw we return the sub we return the substring from 0 index to we return the substring from 0 index to this index like after you touch this this index like after you touch this space space so written that substring i hope this is so written that substring i hope this is clear for you clear for you and if you any doubt you can comment i and if you any doubt you can comment i would love to help you would love to help you thank you very much | 2024-03-22 17:13:29 | 1,816 | Truncate Sentence | Leetcode 1816 | C++Solution |
|
Tf69tOpE4GE | hey everyone today we are going to solve the reduction operations to make the the reduction operations to make the array elements equal okay so first of array elements equal okay so first of all look at this so I always think about all look at this so I always think about the solutions with a small and simple the solutions with a small and simple input so let's focus on one two in this input so let's focus on one two in this case if we uh reduce one from two so we case if we uh reduce one from two so we will get the output right in this case will get the output right in this case one one time and how about one to three so one time and how about one to three so one time 4 two and two * 4 three right in time 4 two and two * 4 three right in this case this case three and how about 1 2 3 four so one three and how about 1 2 3 four so one time for two two * 4 three and three time for two two * 4 three and three times 4 four so total should be 1 2 times 4 four so total should be 1 2 three and three and six so how about the 1 2 3 four five one six so how about the 1 2 3 four five one time for two two times for three three time for two two times for three three times 4 four and the four times four times 4 four and the four times four five right so 1 2 3 4 5 and the total 10 five right so 1 2 3 4 5 and the total 10 10 10 operation so did you notice something operation so did you notice something so seems like we have a solution pattern so seems like we have a solution pattern so let's focus on 1 2 3 4 5 and let me so let's focus on 1 2 3 4 5 and let me put index number so 0 1 2 3 put index number so 0 1 2 3 4 so output is 10 right so if we uh add 4 so output is 10 right so if we uh add all index number so we will get so one 2 all index number so we will get so one 2 3 four so total 10 right so it's equal 3 four so total 10 right so it's equal to to Output so point is the number of Output so point is the number of operations is equal to cumulative index operations is equal to cumulative index numbers and it seems like a sorting the numbers and it seems like a sorting the input array makes problem easy so more input array makes problem easy so more precisely sorting allows us to compare precisely sorting allows us to compare numbers that are cross in magnitude with numbers that are cross in magnitude with each other okay so next case is what if each other okay so next case is what if we have the same numbers in input array we have the same numbers in input array so like one two two three so in this so like one two two three so in this case reduce one time one time and two case reduce one time one time and two times right so total four times right so total four times and as I explained earlier so we times and as I explained earlier so we just add index number so one two three just add index number so one two three so total so total six so seems like we need to calculate six so seems like we need to calculate number of operations in this case right number of operations in this case right so how can you simplify it so let's go so how can you simplify it so let's go back to the like one two 3 four five and back to the like one two 3 four five and break the problem into small parts and break the problem into small parts and uh this question is reduction operations uh this question is reduction operations so let's think about the output from so let's think about the output from large two small number so we reverse large two small number so we reverse input array so that's why 5 4 3 2 1 input array so that's why 5 4 3 2 1 okay so first of all let's focus on this okay so first of all let's focus on this part and try to make all numbers four in part and try to make all numbers four in this case just uh we need one only one this case just uh we need one only one operation right operation right so make this five four and one operation so make this five four and one operation and let's focus on this part and try to and let's focus on this part and try to make all numbers three so in this case make all numbers three so in this case uh we need two operations right so this uh we need two operations right so this four will be three and this four um will four will be three and this four um will be three and the total operation is now be three and the total operation is now three and then next let's focus on this three and then next let's focus on this part and I try to make all numbers two part and I try to make all numbers two so in this case we need three times so in this case we need three times right right so this two this three will be two three so this two this three will be two three will be two and three will be two and will be two and three will be two and now total operation is six and then so now total operation is six and then so let's focus on let's focus on everything and I try to make all numbers everything and I try to make all numbers one so in that case we need to we need one so in that case we need to we need four operations right so this one this four operations right so this one this this two will be one two will be one two this two will be one two will be one two will be one two will be will be one two will be one and then total operation is now one and then total operation is now 10 now all numbers are one then finish 10 now all numbers are one then finish so now we sort and the reverse input so now we sort and the reverse input array but but we still have the same array but but we still have the same output so we just add all index numbers output so we just add all index numbers like 1 2 3 4 so total 10 right it's like 1 2 3 4 so total 10 right it's equal to Output okay so let's sort and equal to Output okay so let's sort and reverse this input array like 3 two two reverse this input array like 3 two two one but output still four right and one but output still four right and let's it one by one and basically we let's it one by one and basically we compare current number and the previous compare current number and the previous number so that's why we start from index number so that's why we start from index one to prevent out of bounds so we start one to prevent out of bounds so we start from index one and at first we compare from index one and at first we compare index zero and index one so in this case index zero and index one so in this case we need a one operation right so because we need a one operation right so because this is a index one so that's why add this is a index one so that's why add one to our total operation and I move one to our total operation and I move next so now index zero is next so now index zero is two and the current number is two and two and the current number is two and the previous number also two so they are the previous number also two so they are same in that case we don't do anything same in that case we don't do anything and then move and then move next so we find the next so we find the one and the previous number is two so um one and the previous number is two so um in this case we need to add three right in this case we need to add three right and the total and the total four so somebody wondering are you sure four so somebody wondering are you sure this is correct yeah actually it's this is correct yeah actually it's correct so for this for this three time correct so for this for this three time should be so we reduce um one here and should be so we reduce um one here and one here and one here three times right one here and one here three times right and now all are one so looks good that's and now all are one so looks good that's why output is four it's same as this why output is four it's same as this four right so why this happen that's four right so why this happen that's because between any two numbers we because between any two numbers we reduce large number once at most even if reduce large number once at most even if we skip reduction when we find the same we skip reduction when we find the same numbers uh index number will be numbers uh index number will be increased by one if we move next so that increased by one if we move next so that is total number of rest of large same is total number of rest of large same number so that's why when we find a number so that's why when we find a small number in later part we can add small number in later part we can add index number including number of index number including number of reduction of the same numbers okay so reduction of the same numbers okay so let's check this example quickly so we let's check this example quickly so we have four five and one and we start from have four five and one and we start from index one so first of all we skip right index one so first of all we skip right because the current number and previous because the current number and previous numbers are same and then move next so numbers are same and then move next so we skip because uh same reason five and we skip because uh same reason five and five and then move next also skip right five and then move next also skip right so same reason five and five and then we so same reason five and five and then we is the last index and uh so look at this is the last index and uh so look at this skip part so even if we skip reduction skip part so even if we skip reduction index number is increased by one right index number is increased by one right so when we find a small number in data so when we find a small number in data part so last last index index number part so last last index index number current index number is four is equal to current index number is four is equal to number of reduction of the same number number of reduction of the same number so which is five so now index number is so which is five so now index number is four and the number of five is also four four and the number of five is also four so that's why uh we can add current so that's why uh we can add current index number to Output so that's why in index number to Output so that's why in this case output is four so add four for this case output is four so add four for index Z One 2 3 so that we can make all index Z One 2 3 so that we can make all numbers numbers one yeah that is a basic idea to solve one yeah that is a basic idea to solve this question so with being said let's this question so with being said let's get into the code okay so let's WR a get into the code okay so let's WR a code first of all we sort and reverse code first of all we sort and reverse input array so nums and sort input array so nums and sort and reverse equal and reverse equal two and then um so let's say operations two and then um so let's say operations so this is a return value initial be so this is a return value initial be zero and uh we need to like a PR uh zero and uh we need to like a PR uh unique so start with uh index zero unique so start with uh index zero number and then uh for I in range we number and then uh for I in range we start from index one and uh until RS of start from index one and uh until RS of nums and if current nums and if current number equal So Pro number equal So Pro unique in that case um we just uh unique in that case um we just uh continue if not the case if nums and I continue if not the case if nums and I so current number is less than PR so current number is less than PR unique so it's time to add operation unique so it's time to add operation so just very simple so so just very simple so operations plus equal index operations plus equal index number and then after that update PR um number and then after that update PR um unique equal current number yeah that's it after that just return return operations yeah so let me submit it yeah let's get and the time complexity of this soltion should be order of n n because of Sal algorithm and the space complexity is I think a order of log n or o n so depends on language you use because sort algorithm needs some extra space so that's why yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next | 2024-03-25 11:57:46 | 1,887 | Reduction Operations to Make the Array Elements Equal - LeetCode #1887 - Python, JavaScript, Java |
|
3riyY1rrq90 | hello coders today we are going to solve another lead for daily challenge and the another lead for daily challenge and the question name is time and time and 5 so the numbers that comes out to base 5 so the numbers that comes out to base 495 right 495 right a girl is [Music] and we have to calculate the overall sum so the first number is 495 second number is 4 9 and well right this is the second part from root to sleep node so it is 490 1. and third part is 4 and 0 which is 40. so which is 1 0 and 2 X2 this is the overall sum so basic and we will calculate the overall spring and we will calculate the overall spring value value commit to sum it up to our ultimate sum commit to sum it up to our ultimate sum so let's put this so let's put this I have already folded it I'll hold it I have already folded it I'll hold it again again for you guys so many happy and five two initially then what we have to do then what we have to do T left again number into number into 10 plus them look at every step what we have to do like agarham again again 40. we have to multiply it by 10 right 49 we have to multiply it by 10 right 49 into into 10 right 10 right and then what we have to do we have to and then what we have to do we have to add our current value current value is we have to multiply the above number with 10 and add our current and we have to and we have to edit our ultimate sum which is our sum edit our ultimate sum which is our sum so we will add this one and this is our so we will add this one and this is our final step we will return so this was final step we will return so this was our base condition our base condition let's write this project part because let's write this project part because the part is very simple other natural evaluate the left to is F and our somewhat what will be our sum this is what we have to pass on this is what we have to pass on and and this is for the left we will do the same this is for the left we will do the same thing for me thing for me type type if it is not null if it is not null then what we will do we will then what we will do we will simply call for root dot right and simply call for root dot right and you will do the same thing number 10 you will do the same thing number 10 plus plus to install to install okay to the test cases are working fine let's to the test cases are working fine let's give it a submit it is also working fine so thanks for watching I hope you guys find this problem and thank you for watching | 2024-03-21 11:39:25 | 129 | Sum Root to Leaf Numbers | Leetcode | Question number 129 | Daily Challenge |
|
sMRq8TjMOko | Hello Hello Everyone Suggest This Solving Number Of But Maximum And Used As A Valid Which Of But Maximum And Used As A Valid Which Change To Question And Give Positive Enters Change To Question And Give Positive Enters Into Positive Winters Left And Right The Into Positive Winters Left And Right The Number Of Class Ninth Subscribe Maximum Number Of Class Ninth Subscribe Maximum Element In This Loot Mein Strike Enters Element In This Loot Mein Strike Enters Into All The The Into All The The Into All The The Chandra Equal Her Ones 300 Flats Chandra Equal Her Ones 300 Flats Considered The First Servants l22 Is Equal Considered The First Servants l22 Is Equal To Left And Electronics Students To Left And Electronics Students And Lose Nickel To Right Tubelight And Lose Nickel To Right Tubelight Subscribe Now To 151 Th Maximum Subscribe Now To 151 Th Maximum Elements To And Again Its Prey Condition Elements To And Again Its Prey Condition Does All Subscribe Now To Does All Subscribe Now To Does All Subscribe Now To Is 4 4 Greater Than There Right Right When You Will Not Be Part Of The Solution In Fact All The Best Suvichar Best Food 10000 Solution Subscribe Maximum Element 3D Song Serial Element Which Is The First Indian According Remake According Remake According Remake Electric Schezwan Sauce 309 Points Review Simple And The First Visit To A Solution Is Amazing That You Will Find Some Subscribe Button Solution Is Not Accepted Subscribe Button Solution Is Not Accepted And Very Time Consuming Solution Subscribe To And Very Time Consuming Solution Subscribe To Images from Lord of Images from Lord of Images from Lord of Hadf Thank You Too of Annually Suresh Yadav Hadf Thank You Too of Annually Suresh Yadav Candidate Candidate 116 Considering Example and Being Given This 116 Considering Example and Being Given This Disorganized Are Left Left Samsung Disorganized Are Left Left Samsung Galaxy S8 Android Apps Something Say 600 800 What Will You Find Galaxy S8 Android Apps Something Say 600 800 What Will You Find Out What Are the Out What Are the Possible subscribe and subscribe and subscribe and subscribe the Channel subscribe and Problem Disagreement Will Not Be Responsible For Maxim Element 123 Body For The Amazing Brightness Element Should Discard 137 Kinds Of Break Point Lost Let's Get Unlike Most Elements Of Break Point A Lawless Moot 504 505 Alone In This Line Between Android needle to shift valid start for Android needle to shift valid start for Android needle to shift valid start for information and in fact reach solution information and in fact reach solution subscribe and left and right vijay subscribe and left and right vijay phase solution element ko subscribe and subscribe phase solution element ko subscribe and subscribe the [ music] newly appointed subscribe this Video subscribe our 1625 So let's 1625 So let's 1625 So let's check the element which loot and element 3636 check the element which loot and element 3636 Individual for the individual will Individual for the individual will contribute to and subscribe the Channel starting position for 6th starting position for 6th that this holiday 786 that this holiday 786 That there sure can more solution That there sure can more solution solution for this channel subscribe Which loop is certain to be Which loop is certain to be Which loop is certain to be defeated 2868 Earlier tomorrow defeated 2868 Earlier tomorrow morning Mirchi will define hidden talents of her morning Mirchi will define hidden talents of her elements of elements which lies between left elements of elements which lies between left and right talents of the elements which is smaller than their and right talents of the elements which is smaller than their life in these letter head life in these letter head elements and position for its And Values And Values And Values subscribe to the Page if you liked The subscribe to the Page if you liked The Video then subscribe to the Page if you Video then subscribe to the Page if you liked The Video then subscribe to the Page Question 2015 Solution Please Subscribe And Solution Counter This is the Value subscribe The Channel subscribe button se withdrawal And And And subscribe sweater delivery starved for do and on your friend ips so no isi encounter per element which number five subscribe is name white is greater than enough power to love but is lesson equal to a phone number 10 10v stabilizer radiant Plus 2 And Nor Will Also Avoid Plus 2 And Nor Will Also Avoid Plus 2 And Nor Will Also Avoid Taxes Witch Tales Us Taxes Witch Tales Us Jhaloo Film Not A Love Story Vikram 0n Jhaloo Film Not A Love Story Vikram 0n Earth Total Account Fifty Plus Plus Two Hai Earth Total Account Fifty Plus Plus Two Hai A Sudden Is The Best One Ad Hit Super A Sudden Is The Best One Ad Hit Super Difficult All Subscribe 3651 Content Will Be Difficult All Subscribe 3651 Content Will Be Id Don't Forget To To main abhi left his To main abhi left his To main abhi left his last time name safai danveer vipin last time name safai danveer vipin short tricks painter know what do short tricks painter know what do subscribe video subscribe subscribe to that a nice and knowledge elements of button right because a nice and knowledge elements of button right because dhawan condition is in that case and head dhawan condition is in that case and head 2009 daughters will all the bases 2009 daughters will all the bases 2009 daughters will all the bases Again' which is Lips Returns Song is ' Chief Manch Hai Hua Hai that a download speed when scooter do and loot online according to and love has been looted that this is only the primary education received, You Have Destroyed A Number Of You Have Destroyed A Number Of You Have Destroyed A Number Of Forever Mehboob Maximum Hai | 2024-03-21 17:12:06 | 795 | LeetCode 795 || Number of Subarrays with Bounded Maximum || Solution |
|
W9SIlE2jhBQ | Hello hello guys welcome back to tech division in this video you will see politicians in this video you will see politicians sequence problem specific from list to sequence problem specific from list to date 24th june challenge so let's not look at the date 24th june challenge so let's not look at the problem statement in this problem where given problem statement in this problem where given interview k when is the number interview k when is the number of units and want to of units and want to of units and want to me the information subscribe to the subscribe to the detention Dissolve in subscribe to the detention Dissolve in ascending order descending order to this ascending order descending order to this permission to find the subscription permission to find the subscription 110 is inter problem no very simple approach to 110 is inter problem no very simple approach to solve this problem is by solve this problem is by using using using jquery function but using recjan you will have to create all possible permissions starting from the earth is very costly library functions will be doing the same thing you will be computing every politician and you will be selected candid total time complexity of Which will not be time Which will not be time Which will not be time complexity and you to the time complexity complexity and you to the time complexity of mathematics in solving problems will of mathematics in solving problems will be solved by using be solved by using pattern letters in the door and values to pattern letters in the door and values to form agenda and person 125 Show form agenda and person 125 Show viewers welcome to three way can create a viewers welcome to three way can create a total of respect to total of respect to total of respect to The Fifth Edition To This Competition Will Not Rise In This Video You Can See The Question Three Idiots Should Be Possible That We Can Just Feel to the Video then subscribe to the Page if you liked the who the who the who is the second two values of having two is the second two values of having two during post graduate and last values are during post graduate and last values are having three fatty acids and divided into having three fatty acids and divided into subscribe fennel 125 what will be the uses subscribe fennel 125 what will be the uses of the question is valid only you can be of the question is valid only you can be divided into five plus one which will be very divided into five plus one which will be very simple Fifteen Days Third Box Will Take Place At North Block Number Three To 10 The Video then subscribe to the Page if you liked The Video then subscribe to the Is Now To Receive New Now To Receive New Elements from Thursday Subscribe Elements from Thursday Subscribe That Saumya Total number of deductions will be That Saumya Total number of deductions will be 400 Value of vaginas will be equal to one 400 Value of vaginas will be equal to one 90 Only request to accept this You can Seervi Seervi and the temple Seervi and the temple Seervi and the temple Now You Can See That This Looking and Disposed Digit Purpose Will Be Divided Into Four Boxes 04096 Servy Boxes Were Due to Be a Mother and Father Video subscribe and subscribe the Channel Please subscribe and subscribe the Channel in Order to Find No Place Which Will Not Be Amazed At Will Robber The Factorial Of That Would Request You To Give Effect To Real Value Message The Black Eyes Will Be Stopped To Real Look Soft And Packing The Digit Tweet - 151 - 24 - 2nd I Am I Divided The Amazing You can find out what The Amazing You can find out what The Amazing You can find out what is the Veer Veer Veer 102 subscribe to the Main work in digits are will be keeping track of all districts which you want to include in order to form and number in this case and request for that they already know the Best All The Digit Subha Unique And Request For The Number From 124 Ok 100 Grams Digit Swapping Is Channel Number And Will Be Removed From Which Are The Number You Will Not And You Want To Do The Current Answer Answer Which Will Be Removed From This Is It Will update you should not solved example and subscribe question because were required to front four digit number ok so will start feeling sad significant digit so what will be the result according to the calculations you can see the subscribe The Amazing - 1the subscribe to the subscribe to the subscribe to the Page if you liked The Video then subscribe to the Page if you liked The Video then subscribe 102 Avelu Index Renu Indicator and Number will be present in the second Box Office 12345 which will consider what is the 12345 which will consider what is the 12345 which will consider what is the Birth York Position Subscribe Rafiq But Will Be Removed From Doing This Is To Updates And Subscribe Elements Of Elements Is Dead So How Many Elements Do We Need To Skip Actually Need To Skip The Number Of Balram Kumar Multiplied By The Which of this is the Which of this is the Which of this is the number of boxes and elements in What is the number of boxes and elements in What is the meaning of this is the number of side meaning of this is the number of side effects to the app and minus one which is nothing effects to the app and minus one which is nothing but the soul from which is the value of but the soul from which is the value of subscribe to the Page if you liked The subscribe to the Page if you liked The Video then Video then Video then * Size of two numbers should be found actually known before * Size of two numbers should be found actually known before making the call OK will be making the call OK will be implemented properly or you can avoid implemented properly or you can avoid making person indicating number digit already making person indicating number digit already have already The Video then have already The Video then subscribe to the Page if you liked The Video subscribe to the Page if you liked The Video Video then subscribe to the Page Kids Value Dowry Nothing But Dhal Minus One Factorial Soayenge Us Person 210 More Okay So After Finding And What Will You Need To Withdraw Its True Value 2025 Video then you liked The you liked The you liked The Video then subscribe to The Amazing - Video then subscribe to The Amazing - 142 142 That Your Convenience Will Be Equal To So That Your Convenience Will Be Equal To So Actually Be Appointed As Most Actually Be Appointed As Most Significant Tips Dene 2012 6021 So When You Get This Significant Tips Dene 2012 6021 So When You Get This To The You Will Consider That Will Be To The You Will Consider That Will Be Block Number 2 And Sons Were Taking This Block Number 2 And Sons Were Taking This Blog from 0210 Free The Significance Did Blog from 0210 Free The Significance Did n't Do So This Is The Richest Man Ever n't Do So This Is The Richest Man Ever You Are Facing In The Element Which Will Be I Am You Are Facing In The Element Which Will Be I Am If You If You Will Be Able To Understand That You Are Not Will Be Able To Understand That You Are Not Doing So Doing So Hello Friends Values 080 Value Wave Raw Hello Friends Values 080 Value Wave Raw One Will Remind You Will Update And Will Be One Will Remind You Will Update And Will Be Updated Daily With Appointed - 21806 Coming From Updated Daily With Appointed - 21806 Coming From This Channel Subscribe Next Time This Channel Subscribe Next Time When You To Two To Two To Check Airtel - 101 Ways To Reduce It's Worse Tell Move to the next Move to the next Move to the next index in the call will be left with only index in the call will be left with only one digit and will by the way update and K one digit and will by the way update and K values Gourmet - Factorial Nuvve Nuvve values Gourmet - Factorial Nuvve Nuvve Nuvve Nuvve This Process Will Just Avoid Number One Can See You But You Can Read and Write Clear Veer Veer Veer Veer Veer Veer Veer Veer Veer Veer Veer Veer Quarter Kuching All the digits in and all the digits will call you solve function will be storing result in directions Answer and will return the answer Sudhir Vashistha and Yash Veervar subscribe and subscribe the two and Veervar subscribe and subscribe the two and Answer Will Answer Will Answer Will CAN BE USED ONLY AFTER DOING THIS WILL UPDATE YOU WILL GO ON RECORD 110 DAYS TO DETAIL LITTLE BIT MATHEMATICAL DUTY TO LORD SHIVA AND ONLY YOU WILL BE ABLE TO UNDERSTAND ONLY SO IFIN Can Can Can Benefit From Like Share And Subscribe Benefit From Like Share And Subscribe Our Channel Like This Video | 2024-03-20 10:46:48 | 60 | Permutation Sequence | Leetcode #60 |
|
QAUyCOUtSHM | Hello friends today let's solve number of music playlists um so we are given integer and it means we have a different sums and we want to listen to Go songs we must make sure some can only be we must make sure some can only be played again played again after chaos songs have been played after chaos songs have been played if you look at this example you will if you look at this example you will wonder why we don't have a playlist as wonder why we don't have a playlist as one two one because we can play one one two one because we can play one again after again after K sums K sums but the issue is that we must but the issue is that we must make sure every song is played at least make sure every song is played at least once once so in this case since the lens of this so in this case since the lens of this goal list is three so we must play older goal list is three so we must play older and songs once so there is no duplicate and songs once so there is no duplicate songs in one playlist in this example we can play the Samsung just continuously because the case zero so we will have one one two um um if you notice it says the answer can be if you notice it says the answer can be very large we can return it a module very large we can return it a module this number so it indicates we can solve this number so it indicates we can solve it via dynamic programming it via dynamic programming and the how to solve Dynamic program and the how to solve Dynamic program question we need the initial dilation question we need the initial dilation and the and the state transition function how to Transit um to current state via the price dates that's what we need to figure out so in this question what do we want to return is like we want to play goal songs and we have in different zones how many playlists so we can just easily represent it as an integer array right so it means the it means the total waste to oh or a playlist we have we either to play Go songs and we have a different songs so in the end we just so why I write go before and it's so why I write go before and it's because we need to Transit Transit the because we need to Transit Transit the states right so in that case states right so in that case I mean I can understand it either it's I mean I can understand it either it's like like the Outer Loop the Outer Loop is the is the number of songs we want to number of songs we want to contain in the list contain in the list let's record them go let's record them go and then I and then I increment the four into J equal to increment the four into J equal to one J less or equal than and J plus plus one J less or equal than and J plus plus so basically it's the same order as this so basically it's the same order as this array array we can understand it either it's like we can understand it either it's like uh no matter how many different songs we uh no matter how many different songs we have we can usually return DP I have we can usually return DP I something but when we have more something but when we have more different songs uh we just different songs uh we just uh uh like like DP go if we have one different song we DP go if we have one different song we can have some ways and if we have can have some ways and if we have two different so we can have more ways two different so we can have more ways so I think this order makes sense so I think this order makes sense so how do you trans Transit states there so how do you trans Transit states there will be will be dpij like currently we will have some dpij like currently we will have some just increment it well what is the current ways if the is we are currently J right we have J different songs if the current additive sum is different from all the songs we already included then it would be elements one J minus one right because it's like current AJ is a new song total new song so it would times a minus J plus one so how to understand it is like if J equals to 2 while we have three different zones so in the ply wrong prior round we played one song from one out of three songs right a lot of three songs so now I have two ways to I mean I have two options right two options but things for the prior round I already chose one song so it's a three right and for either one I have two options now so it's times not a plus and another way is like um the current The Chosen sum is the one I already chose so it would have the same J because this current zone is not a new song so what I should at times well it depends on whether I can choose the Samsung once it's like I cannot choose then zero but why I would say I can choose I can choose it means J minus K should be greater than zero like here if k equal to 2. like I need to play a song after another two songs then now it's zero I cannot actually have more options here but if K is one then I can actually play a new song right since 2 minus one equal to one so I can play and um yeah I can already play an um um if J equal to 2 k equal to one I can if J equal to 2 k equal to one I can play a new song after one song oh so actually I just have the of like the opportunity I minus one thing but if I can play it the same so after three I can play it the same so after three other songs but since J is less than K I other songs but since J is less than K I certainly cannot play so it's zero so certainly cannot play so it's zero so this means the current song is a totally this means the current song is a totally new song new song from other songs so we from other songs so we no matter what Germans want in the pride no matter what Germans want in the pride rounds rounds we should adjust we should adjust add up the options but if the song add up the options but if the song already played before we need to choose already played before we need to choose to check the to check the weather is after okay other songs weather is after okay other songs and then we need a d p i j um module mode so we needed the mold um um and the things either can and the things either can make larger than Inked so we just write make larger than Inked so we just write long long in the end we convert it to unit in the end we convert it to unit and also the initialization the dp0 and also the initialization the dp0 equal to one it means if we have a equal to one it means if we have a difference of zero difference of and we difference of zero difference of and we want to make at least have zero want to make at least have zero something we have one option and we'll find that things we only use are minus one the prime row so we don't necessarily need to save this information so we just so we just remove it so we just remove it well since now this DP well since now this DP J can represent other rows so we just J can represent other rows so we just use the same information not increment use the same information not increment okay so now okay so now Mojo Mojo so but actually we just remove this row so but actually we just remove this row okay the only issue is like the the only issue is like the initialization it means if we have a initialization it means if we have a different sums different sums we have one way to make a list right we have one way to make a list right since we we don't have any real songs since we we don't have any real songs but if but if here here our goal is more than one song then if our goal is more than one song then if we only have one different song it means we only have one different song it means we actually only have one zero weight we actually only have one zero weight right because previously it means uh right because previously it means uh like we have zero different song but if like we have zero different song but if our goal is also zero then we have one our goal is also zero then we have one way but here way but here here it means we have more goals but here it means we have more goals but still if we have zero different songs still if we have zero different songs then we only have zero ways not one way then we only have zero ways not one way I think that would be thank you uh uh oh sorry sorry one one important mistake like because if we remove that row we actually need to reverse the direction of the inner loop if you are familiar with knapsack you should know this yeah just don't need to remove reverse okay thank you for watching see you next okay thank you for watching see you next time | 2024-03-25 11:02:30 | 920 | [English] LeetCode 920. Number of Music Playlists |
|
uQ1hbAB8PPk | hello and welcome so today we'll be discussing one of the very important discussing one of the very important problem of uh lead code which is a problem of uh lead code which is a problem number one six zero five and the problem number one six zero five and the problem is find valid matrix given row problem is find valid matrix given row and column sum so what you have given and column sum so what you have given row sum and column sum and you have to row sum and column sum and you have to find the valid matrix so what what this find the valid matrix so what what this problem is all about so let me read this problem is all about so let me read this problem for you so you are given a two problem for you so you are given a two arrays you have given a two errors one arrays you have given a two errors one is known as row sum and another is known is known as row sum and another is known as columns i'm fine of a non-negative as columns i'm fine of a non-negative integers fine these are actually a integers fine these are actually a positive integers fine of a non-negative positive integers fine of a non-negative integers where non-negative integers integers where non-negative integers means where 0 is included means where 0 is included 0 is included so you have to keep this 0 is included so you have to keep this in my non-negative means zero and in my non-negative means zero and positive fine okay so where a row sum i positive fine okay so where a row sum i is the sum of element of i-th row that is the sum of element of i-th row that is a row sum i if i say about any row is a row sum i if i say about any row then row sum i is containing the sum of then row sum i is containing the sum of element of ith row similarly column sum element of ith row similarly column sum j is the sum of the element of jth j is the sum of the element of jth column of a 2d matrix so what it is all column of a 2d matrix so what it is all about i'll be explaining by taking an about i'll be explaining by taking an example that will become easy for you to example that will become easy for you to understand okay fine in other words you understand okay fine in other words you do not know the element of the matrix do not know the element of the matrix but you do know the sum of each row and but you do know the sum of each row and column that is you don't know what our column that is you don't know what our element of a matter if i say this is a 2 element of a matter if i say this is a 2 cross this is a matrix 2d matrix so what cross this is a matrix 2d matrix so what actually you know you know the sum of actually you know you know the sum of rows you know the sum of columns but you rows you know the sum of columns but you don't know what this elements are you don't know what this elements are you actually don't know what this element actually don't know what this element are suppose if this is a 3 cross 3 are suppose if this is a 3 cross 3 matrix so you know what is the sum of matrix so you know what is the sum of this this what is the sum of this what is the sum what is the sum of this what is the sum of this row you know the sum of this of this row you know the sum of this column some of these columns some of column some of these columns some of this column but you actually don't know this column but you actually don't know what comes here what comes here what what comes here what comes here what comes here and here fine so this is what comes here and here fine so this is what actually the problem is let me read actually the problem is let me read further for you now comes the question further for you now comes the question that find any matrix non-negative that find any matrix non-negative integer size row sum in length into integer size row sum in length into column sum length that is suppose row column sum length that is suppose row sum length is uh sum length is uh 3 column sum length is 3 fine that you 3 column sum length is 3 fine that you have to find 3 cross 3 matrix your job have to find 3 cross 3 matrix your job is to find three cross three matrix then is to find three cross three matrix then matrix should have an element fine matrix should have an element fine that's satisfied which actually that's satisfied which actually satisfied roof sum and column sum that satisfied roof sum and column sum that is you have to written a 2d array is you have to written a 2d array representing any matrix that fulfills representing any matrix that fulfills the requirement it is guaranteed very the requirement it is guaranteed very important at least one matrix that important at least one matrix that fulfills that so there will be existing fulfills that so there will be existing one metric it it will not be like one metric it it will not be like something like that where no such something like that where no such metrics exist metrics exist so before no if i will not take the so before no if i will not take the example it will become tough for you to example it will become tough for you to understand so let me take one example understand so let me take one example from this question itself so that it from this question itself so that it becomes easy for you to understand what becomes easy for you to understand what i'm talking about so let's let's take i'm talking about so let's let's take one example now i'm taking this example one example now i'm taking this example so let me explain you about using this so let me explain you about using this example so fine okay yes example so fine okay yes so here you have given row sum that is so here you have given row sum that is row sum is 5 7 and 10 and then column row sum is 5 7 and 10 and then column sum is 8 6 8. so let me make one matrix sum is 8 6 8. so let me make one matrix for you okay fine but it is given row for you okay fine but it is given row sum row sum is given 5 sum row sum is given 5 then seven and then ten fine okay and then seven and then ten fine okay and then column sum is given eight six and then column sum is given eight six and eight now your job is to find this eight now your job is to find this element this this this this element this this this this fine so your job is to find these fine so your job is to find these elements let me change the color of my elements let me change the color of my fan so that it becomes easy for you to fan so that it becomes easy for you to understand understand now how will i able to judge i know the now how will i able to judge i know the sum of these sum of these all element is 5 all element is 5 i know that sum of all these element of i know that sum of all these element of a column is eight but what this element a column is eight but what this element will have so the method there could be n will have so the method there could be n number of methods fine so the the method number of methods fine so the the method which i'm just going to discuss with you which i'm just going to discuss with you right now is is one of the easiest right now is is one of the easiest method fine so what how to do how to method fine so what how to do how to solve this question is that first solve this question is that first initialize the entire matrix with zero initialize the entire matrix with zero element so let me rub all these things element so let me rub all these things fine so let's initialize all the matrix fine so let's initialize all the matrix with zero element so i have initialized with zero element so i have initialized the entire matrix with 0th the entire matrix with 0th value fine with 0 value fine with 0 okay now okay now now you have to start the matrix now you have to start the matrix suppose i is representing the row and j suppose i is representing the row and j is representing the column the length of is representing the column the length of row sum is 3 the length of column sum is row sum is 3 the length of column sum is 3 that is you have to build a 3 cross 3 3 that is you have to build a 3 cross 3 matrix fine okay now what to do from the matrix fine okay now what to do from the pointer i to the pointer j find the pointer i to the pointer j find the minimum value among 2 so out of five okay so there are two pointers i and j fine so there are two pointers i and j find the minimum among two so out of five and eight which is minimum five so change here make it five now reduce the selected element from both i and j so if you reduce five from five it will become zero five and if you reduce five from eight it will become 3 fine okay now the parameter which becomes 0 will no will will will be will be increased since i since i is a what you can say is a pointer which whose value becomes zero so it will increase so it will increase from this position to this position fine so where i am right now i'm at this position fine because j is at this position i is at this position now find minimum between the two that is seven and three so seven which is minimum seven and three three is minimum so finally three we will replace this with three now reduce the selected value so if you reduce the selected value it will become zero and it will become what four if you reduce reduce three from seven it will become four now which becomes zero i or j j becomes zero so i'll increment j j will come here so finally i would at which position here so among four and six which is minimum four so i'll replace it with four fine okay now i'll replace and reduce four from both i and j so i when i reduce this four will become zero and the six will become two so the which pointer has become zero i so i'll increment i i will point here j will remain at its own position now where i am right now here fine so among 10 and 2 which is minimum 2 is minimum so i'll replace it with 2 i'll reduce 2 from both i and j it will become 8 and it will become 0 since j has become zero it will get incremented fine it will come here now where i'm actually pointing i'm pointing here so out of i and j which is minimum both are eight it could be a ticket it can be any any eight fine so i'll replace it with eight now both become zero now only to do that something fine so the both become zero so finally what you have no got the matrix so uh have you actually achieved the correct matrix now let me remove all those things five eight six and eight fine okay then eight six and eight let me remove this okay okay okay okay okay then fine so this is five fine okay okay okay so now see have you got the answer so the sum of this row is 5 very right fine the sum of this row is 5 very correct the sum of this column is 5 3 8 correct the sum of this column is 6 very correct the sum of this row is 7 very correct fine so actually you have got the answer so this is actually the method this is the method which you have to apply for solving this question which is find the valid matrix now you might be thinking that your answer is your answer is is 5 0 0 3 4 0 and then 0 2 8 list of list i'm talking of python fine it's a list of lists so you have got this matrix you might be thinking that oh i'm not getting the same answer this answer is 0 5 0 my answer is 5 double 0 so there could be a number of ways to solve this question i gave you one way so i'll be also discussing how they have solved how they have given you this input and output so let let us build first code that will become easy for you to understand so let's build the code so that you can understand what what this problem is all about fine so okay let's start with the code uh so i'm i'm taking python so i'm building my code in python itself so let's have two variable one is rows fine and let's say another is columns c o l s columns you can take any rows and column whatever you want you can take fine and let this be equal to when length of you have what you have given you have given row sum if i'm not talking you have given a row sum yes and you have given column sum let me show you let me show you okay see this so you have given one row sum and then column sum and this length is the length of this so length of row sum row sum fine and then it comes calls length of call some c o l you have to use the same variable name as it is given see you can see row sum and column sum you cannot change you cannot change you are not allowed to change anything like that fine so you have initialized both the variable rho sum and column sum with value of length of row sum and length of columns of fine then comes next thing uh then next part is okay you have to let's take one matrix mat and now what i'll do i'll be initializing this matrix with all element having zero elements so how list comprehension is used for okay for j n for j in where j is representing suppose calls cols calls calls cols calls fine for jane calls then after that fine for jane calls then after that it comes it comes for i in the range i in range rows r over w s i i i wonder why this okay fine yeah i got the point because okay fine yeah i got the point because of indentation problem of indentation problem so uh so uh what what what is the meaning of this what what what is the meaning of this line this is actually a uh line this is actually a uh list comprehension in python so what list comprehension in python so what what am i doing is that you know what what am i doing is that you know what you actually do for suppose i'm taking you actually do for suppose i'm taking an example of c language what for for an example of c language what for for rows and column what do you do for i rows and column what do you do for i uh you one you runs the loop of i for no uh you one you runs the loop of i for no for number of rows then you run for j in for number of rows then you run for j in the neurons for columns and then view the neurons for columns and then view what you do matrix suppose r matrix is what you do matrix suppose r matrix is uh uh then you initialize this with zero so then you initialize this with zero so this is what you do in c language so this is what you do in c language so what you all can do in number of lines what you all can do in number of lines you can do by list comprehension in a you can do by list comprehension in a single line so what what am i doing over single line so what what am i doing over here is that i'm using a here is that i'm using a j loop for columns i'm using loop i for j loop for columns i'm using loop i for a number of rows and for all those a number of rows and for all those values i'm initializing it with 0 fine values i'm initializing it with 0 fine so nothing is so nothing is something very different which i'm doing something very different which i'm doing over here it's all very common thing over here it's all very common thing fine so let let me proceed further to fine so let let me proceed further to build the code then okay then let's so build the code then okay then let's so what we did right now we have created what we did right now we have created two rows and columns and initialized two rows and columns and initialized with the length of rows and column and i with the length of rows and column and i have initialized on matrix by the name have initialized on matrix by the name of mat and the value is now having zero of mat and the value is now having zero all the element now i have two variables all the element now i have two variables i and j you can take any variable and i and j you can take any variable and let's initialize it again with zero so let's initialize it again with zero so i'm having two variable i and j and i'm i'm having two variable i and j and i'm initializing it value zero now am i initializing it value zero now am i taking a loop while why taking a loop while why while while while i is less than rows r o w s and while i is less than rows r o w s and very important and g is less than very important and g is less than column c o l s columns fine so what am i column c o l s columns fine so what am i doing is here is that doing is here is that my till when i have to move till my i my till when i have to move till my i and j are less than rows and columns and j are less than rows and columns this is a common sense very common sense this is a common sense very common sense what what next thing then we have to what what next thing then we have to find what matrix find what matrix i i and and j matrix i and j is what is actually a j matrix i and j is what is actually a minimum of minimum of is actually a minimum of is actually a minimum of rows very important you might be thinking that so when we have taken one matrix let me let me let me so let me make one matrix for you then what was that i don't know i i don't exactly remember what was the 5 16 i if i'm not wrong yes yes it was 5 6 10 and it was 8 uh 8 6 10 or something something like that i don't know do not exactly remember so what what actually you was doing so you was taking minimum from these no fine so this element matrix i say this is 0 0 will be what minimum of 2 so this matrix 0 0 will be minimum of row of i that is this and this fine okay so uh let me move again further fine okay so i'm sorry for this where i was actually yes i was here okay then then what i have to do is that then i have to reduce that element fine reduce that number those sum of i what it will become minus equal to what you have it will become mat of i comma j the element which you have selected for that matrix reduce that element from what row sum and reduce that same element from columnism also this is what we did we are doing now is that reduce same thing from column c o l s u m called somewhat called sum for calls and we are using value of j and that you have to reduce that is minus is equal to matrix or that you of i and then you have to reduce that from j also fine so this is what you are actually doing now now then comes fine so on reducing on reducing you have to check that which pointer needs to be moved that which value has become zero either i have to move i or i have to move j fine okay so in that case what you're doing if if what if row sum r o w s u m if rho sum of i is equal to equal to zero then in that case what you have to do you have to increment i find this is what i already told you that this is plus equal to one then in that case you have to increment i else not else if only if not else if called some c-o-l-s-u-m called some j called some j has what become zero then you have to move that also fine else means what you have to check only one but here using f in both the cases that you have to check both the statement fine then you have to increment j that you have to increment j by one fine on doing all such thing what you do you just return what the matrix you created you have created what matrix mit find so you have to return fine you have to written that matrix fine so what you are actually doing let me explain you now so let me love all these things fine so let's now let's take the example same example by which i will be explaining you uh very clearly why okay so okay so you let's take example the rowsum is 577 it's 5 7 and 10 and column sum is 8 6 and 8 fine what you did you took rows and column from length of row 7 column so length of row sum is three and column sum is so rows is now three calls is a variable is three you what you did you made one matrix and by using what this list comprehension that is for i is equal to zero uh from from range of rows for j in range of column you are initializing each element with zeros what you are actually doing is you are initializing each and every element of the matrix with value zero fine now you have again created two variable i and j and you have initialized those value with values zero point so till three these three lines has become very clear now now what you are doing is you are using a while loop while i is less than rows and while j is less than column it's currently true so what you did you are finding what minimum of row sum i in column so what you are actually doing you are finding minimum because your i is here your j is here you are finding minimum of these two and you are replacing that value here so mat zero zero matrix zero zero element will be a minimum of both so minimum of both is five so this has become five now what i told you that you have to reduce these five selected five from both this both the rows and columns so row sum i will have what subtraction of this matte i say so it will become 0 and this column sum will become 3 on reducing this value 5. now what you have to check which pointer you need to move i or j is row sum i equal to 0 yes row sum i is now 0 increment i i will get incremented is column sum j equal to 0 no this will not get incremented so keep on when you keep on doing the same procedure what you will get you will get the answer and after getting answer you will return this matrix fine bus only this much so let's run the code so that uh let's run this code fine okay so let me run this code now for you okay fine so the code is actually running accepted you have put 3 8 and 4 7 and this is clear cut it's running now let me submit the code okay fine it's accepted so let's come to okay fine it's accepted so let's come to the description part once again and you the description part once again and you might be wondering why i haven't might be wondering why i haven't know shown you the method which they are know shown you the method which they are using how my answer is differ from their using how my answer is differ from their answer so i'll be discussing those also answer so i'll be discussing those also this thing also so oh oh oh okay let's this thing also so oh oh oh okay let's let's let's use the spam fan okay fine let's let's use the spam fan okay fine so let me explain what what day people so let me explain what what day people are using how they are solving this are using how they are solving this question question fine so okay so what they are they are fine so okay so what they are they are doing they are doing the same job fine doing they are doing the same job fine five seven ten eight six eight how they five seven ten eight six eight how they are getting zero five zero is like this are getting zero five zero is like this so what yeah they are doing is that they so what yeah they are doing is that they are finding what what they are finding are finding what what they are finding minimum of the entire row is this minimum of the entire row is this minimum of the entire column sum is this minimum of the entire column sum is this now among these two they are selecting now among these two they are selecting minimum so what is minimum minimum so what is minimum it's five and it's it's five and it's uh it's five and six from five and six uh it's five and six from five and six they are getting five so it will become they are getting five so it will become one fine and it will become 0. now again one fine and it will become 0. now again they'll find minimum so minimum from they'll find minimum so minimum from this and minimum from this excluding 0 this and minimum from this excluding 0 so a minimum of this is what this is a 7 so a minimum of this is what this is a 7 fine and then minimum of this is 1 so fine and then minimum of this is 1 so this will become this will become this will become yes exactly so this this will become yes exactly so this will become 1 so 7 and 1 will give you will become 1 so 7 and 1 will give you what 1 fine so this will become 0 fine what 1 fine so this will become 0 fine this will become 0 this will become 0 now they again they are and this will now they again they are and this will become 6 so again from 8 and 6 it will become 6 so again from 8 and 6 it will become 6 because of this they are become 6 because of this they are getting 0 5 0 6 1 0 so this is their own getting 0 5 0 6 1 0 so this is their own method of solving the question so till method of solving the question so till then then uh i thought uh i thought i have explained you uh in a best and i have explained you uh in a best and possible manner what this uh how this uh possible manner what this uh how this uh problem can be solved so thank you so problem can be solved so thank you so much for watching thank you thank you so much for watching thank you thank you so much thank you very much | 2024-03-19 15:31:35 | 1,605 | LeetCode : 1605 Find Valid Matrix Given Row and Column Sums |
|
N2Dw2uFjDeo | hey guys welcome back today we're taking a look at product of array except self a look at product of array except self which is a pretty tricky array question which is a pretty tricky array question that requires a bit of a creative twist that requires a bit of a creative twist on what we know so given an integer on what we know so given an integer array nums return an array answer such array nums return an array answer such that answer at index i is equal to the that answer at index i is equal to the product of all elements of nums except product of all elements of nums except nums of i it's guaranteed to fit a nums of i it's guaranteed to fit a 32-bit integer uh you might write you 32-bit integer uh you might write you must write an algorithm that runs in must write an algorithm that runs in linear time without using the division linear time without using the division operation this is pretty key uh pretty operation this is pretty key uh pretty um intuitively if you try if you wanted um intuitively if you try if you wanted to use the division operation then you to use the division operation then you could kind of just tell that uh in in could kind of just tell that uh in in the case of this then you could just the case of this then you could just kind of get the product of all of these kind of get the product of all of these and then divide them by each index or and then divide them by each index or each element at index i um you'd have a each element at index i um you'd have a few edge cases with zeros but for the few edge cases with zeros but for the most part this would be a pretty simple most part this would be a pretty simple question so you can't do this uh so question so you can't do this uh so let's take a look at what we actually let's take a look at what we actually are given and what we have to do then are given and what we have to do then so we have the so we have the array array one two three four one two three four and our output array is 24 24 being the and our output array is 24 24 being the product 234 product 234 12 being the product of one three and 12 being the product of one three and four eight being the product of uh four eight being the product of uh everything except three so one two four everything except three so one two four and six being the product of everything and six being the product of everything except for so three two one so that's except for so three two one so that's what we have um let's figure out how what we have um let's figure out how we're actually going to do this then we're actually going to do this then without using the uh without using the uh division operator so if we're not using division operator so if we're not using the division operator then somehow we're the division operator then somehow we're going to need to get all going to need to get all using just the multiplication operator using just the multiplication operator we're going to need to return an array we're going to need to return an array such that this array is one or sorry um such that this array is one or sorry um everything except one so it'd be two everything except one so it'd be two times three times four times three times four um this array is going uh the the index um this array is going uh the the index here is going to be one times three here is going to be one times three times four times four you next at uh you next at uh this second index is going to be this second index is going to be 1 times 2 times 4 1 times 2 times 4 and this last index is going to be 1 and this last index is going to be 1 times 2 times 3. times 2 times 3. and this might not seem obvious at first and this might not seem obvious at first but something we're actually doing is but something we're actually doing is taking taking um everything before um everything before multiplied by everything after so at multiplied by everything after so at this zero index we're taking everything this zero index we're taking everything before and we can just assume that if before and we can just assume that if there's nothing there then we can assume there's nothing there then we can assume that it's one and we're multiplying that that it's one and we're multiplying that by everything after which is two times 3 by everything after which is two times 3 times 4. then at index 2 what we're times 4. then at index 2 what we're doing is we're taking this 2 and we're doing is we're taking this 2 and we're multiplying everything that comes before multiplying everything that comes before by everything that comes after by everything that comes after multiplying 1 by 3 times 4 and then for multiplying 1 by 3 times 4 and then for this next index at index 2 element 3 this next index at index 2 element 3 we're multiplying everything that comes we're multiplying everything that comes before one times two and we're before one times two and we're multiplying that by everything that multiplying that by everything that comes after four and then for this last comes after four and then for this last one we're doing the same thing which is one we're doing the same thing which is multiplying everything that comes before multiplying everything that comes before uh one times two times three times uh one times two times three times everything that comes after and there's everything that comes after and there's nothing here so we can assume that nothing here so we can assume that that's a plus one that's a times one so that's a plus one that's a times one so what what could we do first we could uh what what could we do first we could uh create uh two arrays we could call these create uh two arrays we could call these pre and call this post pre and call this post and for this pre-array this pre-array and for this pre-array this pre-array could have everything that comes after could have everything that comes after so excluding one so excluding one so starting at index one so starting at index one starting at index zero it would be one starting at index zero it would be one and then we could essentially start the and then we could essentially start the actual calculations here where we keep a actual calculations here where we keep a running total of one running total of one and then it's one times whatever was and then it's one times whatever was here and then it's uh here and then it's uh two times whatever comes before that so two times whatever comes before that so two times um the element multiplied by two times um the element multiplied by everything that came before and then for everything that came before and then for this last one we would have this element this last one we would have this element you know the element at the index right you know the element at the index right before because this is index three before because this is index three zero one two three then for this last zero one two three then for this last element what we get is the index from element what we get is the index from the original array the original array at position at index position two at position at index position two multiplied by what was in this array at multiplied by what was in this array at index position two and then we'd get six index position two and then we'd get six like this and then for this post we like this and then for this post we could do a very similar thing except could do a very similar thing except working the other way around where we'd working the other way around where we'd start at one and then sorry zero one two start at one and then sorry zero one two three three three two one zero and then at this three two one zero and then at this index we would get index we would get this index or sorry the index above that this index or sorry the index above that would get this index four multiplied by would get this index four multiplied by whatever came over here so four and then whatever came over here so four and then uh continuing onwards um at this index uh continuing onwards um at this index one we would take the index above that i one we would take the index above that i didn't next two we would take three and didn't next two we would take three and multiply that by whatever was in the multiply that by whatever was in the index before and this would be um four index before and this would be um four times three it would be twelve and then times three it would be twelve and then finally we could do the same thing right finally we could do the same thing right here uh two the index two which is the here uh two the index two which is the index above uh one above index zero so index above uh one above index zero so two multiplied by whatever came before two multiplied by whatever came before so that was this would be 24. then you so that was this would be 24. then you have these two arrays and what you can have these two arrays and what you can actually do is you can just multiply actually do is you can just multiply them directly to get your product your them directly to get your product your product array product array which is going to be 24 which is going to be 24 12 12 um eight and six um eight and six and if you scroll up in the example 24 and if you scroll up in the example 24 12 8 and 6 this is actually 12 8 and 6 this is actually exactly what we want in our output array exactly what we want in our output array um is this a linear time yes you only um is this a linear time yes you only well yeah you're going through this once well yeah you're going through this once to get our prefix array and then you're to get our prefix array and then you're going through it once backwards to get going through it once backwards to get our our uh post array and then you're iterating uh post array and then you're iterating through all of them again so this is through all of them again so this is going to be of three and time complexity going to be of three and time complexity um which just simplifies to o n um which just simplifies to o n and as for space complexity it takes the and as for space complexity it takes the pre the post pre the post and the final which is of three of n and the final which is of three of n which is again simplified to o of n and which is again simplified to o of n and we can actually optimize this a bit by we can actually optimize this a bit by converting this 3n to just o of n uh we converting this 3n to just o of n uh we we would skip this 3m by skipping the we would skip this 3m by skipping the fact that we have a pre post and product fact that we have a pre post and product what we could do is get rid of this pre what we could do is get rid of this pre and post get rid of these two arrays and and post get rid of these two arrays and then just directly work with product how then just directly work with product how would we do that uh let's take a look would we do that uh let's take a look right so we have this array that we're right so we have this array that we're working with and what we want to do is working with and what we want to do is get it all into this product array get it all into this product array of the same length and we want to get of the same length and we want to get everything multiplied together so everything multiplied together so we're kind of doing the same thing as we we're kind of doing the same thing as we did in the pre and post but instead did in the pre and post but instead we're just going to keep track of we're just going to keep track of everything in here so uh we'll do this everything in here so uh we'll do this first iteration so as we iterate through first iteration so as we iterate through we'll keep track of product as um one we'll keep track of product as um one we'll start we'll start with one and we'll start we'll start with one and then we'll we'll do the exact exact same then we'll we'll do the exact exact same thing that we did with keeping track of thing that we did with keeping track of the pre-element so this is index zero the pre-element so this is index zero one two three it's index one so we'll one two three it's index one so we'll take the index before one multiply it by take the index before one multiply it by this we have one again here and then for this we have one again here and then for this two we have two times one and then this two we have two times one and then for this last one we have three times for this last one we have three times two six and then we can actually iterate two six and then we can actually iterate through this product of backwards through this product of backwards backwards one time and instead just do backwards one time and instead just do the same thing so we would do six times the same thing so we would do six times one and then instead we would just one and then instead we would just multiply it by whatever we would have multiply it by whatever we would have initially had in the product array and initially had in the product array and then you would have this times one um then you would have this times one um and then we would do times four so times and then we would do times four so times four four and then over here backwards continue and then over here backwards continue onwards we would do times 12 onwards we would do times 12 and then lastly we do times 24 and then and then lastly we do times 24 and then in that way we can get our product right in that way we can get our product right so let's see how this actually looks so let's see how this actually looks like in the code and hopefully it'll like in the code and hopefully it'll make a little bit more sense make a little bit more sense so the very first thing we're going to so the very first thing we're going to want to do is instantiate a want to do is instantiate a solution array which is just going to be solution array which is just going to be an empty array that we're going to an empty array that we're going to slowly start to fill in um then our slowly start to fill in um then our we're going to do this uh i guess pre we're going to do this uh i guess pre multiply multiplication and then this is multiply multiplication and then this is going to be going to be let product equal one because remember let product equal one because remember we're always starting at one and we want we're always starting at one and we want to create the array so we're given one to create the array so we're given one two three four and we want to turn this two three four and we want to turn this into one one uh into one one uh i believe yeah one one two six i believe yeah one one two six and then so the way we're going to do and then so the way we're going to do that is by doing an iteration for let i that is by doing an iteration for let i equal zero i is less than numbers.length equal zero i is less than numbers.length so we're going to iterate through the so we're going to iterate through the entire nums array and we're going to say entire nums array and we're going to say the result at index i is equal to the result at index i is equal to product which we set to be one initially product which we set to be one initially so at the zeroth array is going to be so at the zeroth array is going to be product and then we're going to multiply product and then we're going to multiply product times equals num's i so as we product times equals num's i so as we continue through this loop this product continue through this loop this product is going to continuously be updated by is going to continuously be updated by whatever the nums element is at that whatever the nums element is at that index so index so um we have this product after res i uh um we have this product after res i uh which is how we can get the update to be which is how we can get the update to be an index before is what it seems like an index before is what it seems like right and then at this point our right and then at this point our solutions our solution array looks like solutions our solution array looks like 1 1 2 6. this is exactly what we want 1 1 2 6. this is exactly what we want now we can just iterate backwards so now we can just iterate backwards so we'll let product equal one again we'll let product equal one again and we can iterate backwards for let i and we can iterate backwards for let i equals number length minus one equals number length minus one greater than or equal to zero and minus greater than or equal to zero and minus minus we can it when we're iterating minus we can it when we're iterating backwards we'll do pretty much the same backwards we'll do pretty much the same thing except kind of flipped uh result thing except kind of flipped uh result times equals product so in this case we times equals product so in this case we don't want to set it equal to the don't want to set it equal to the product we want to multiply it by this product we want to multiply it by this new backwards product that we're keeping new backwards product that we're keeping track of and again we do the same thing track of and again we do the same thing here with product times equals nun's i here with product times equals nun's i so we're just updating product again if so we're just updating product again if we return res or sorry if you return we return res or sorry if you return saul saul um not sure why i've been doing results um not sure why i've been doing results instead of solution instead of solution uh then we should get the correct answer uh then we should get the correct answer here so here so yep that works | 2024-03-22 11:34:19 | 238 | Product of Array Except Self - Leetcode 238 - Javascript |
|
fQHqeGoD234 | hi everyone in today challenge we are going to solve this problem the problem going to solve this problem the problem name is path in a binary Matrix and the name is path in a binary Matrix and the problem is one zero nine one all right problem is one zero nine one all right guys so first of all we are going to guys so first of all we are going to clearly understand this problem clearly understand this problem statement after that we are going to statement after that we are going to move to the logic part we are going to move to the logic part we are going to see how we can solve this problem and see how we can solve this problem and after that we are going to move to the after that we are going to move to the implementation path we are going to implementation path we are going to implement our load you can see plus plus implement our load you can see plus plus Java and Python programming language Java and Python programming language fine guys now let's see what this fine guys now let's see what this problem say right so let's understand problem say right so let's understand this problem statement so problems is this problem statement so problems is given n cruise and binary Matrix grade given n cruise and binary Matrix grade written the length of short scalar path written the length of short scalar path in The Matrix if there is no credit path in The Matrix if there is no credit path later minus one so guys simple line it later minus one so guys simple line it says that we are given first of all grid says that we are given first of all grid a matrix binary Matrix that means we a matrix binary Matrix that means we will have only zero one value in Matrix will have only zero one value in Matrix and the size is nothing but n close and and the size is nothing but n close and that means it is a square Matrix right that means it is a square Matrix right all right and now what we have to do we all right and now what we have to do we have to find a clear path in this Matrix have to find a clear path in this Matrix right so we have to find clear path and right so we have to find clear path and if there are exists more than one killer if there are exists more than one killer bar so we have to find the shortest path bar so we have to find the shortest path so one thing is clear that if there are so one thing is clear that if there are more more than one path axis we have to more more than one path axis we have to find shortest one and second thing if find shortest one and second thing if there is no path exists so we have to there is no path exists so we have to get a minus one I hope this makes sense get a minus one I hope this makes sense right so this is basically the meaning right so this is basically the meaning of this line of this line so that let's understand this what is so that let's understand this what is clear path right clear path right from the top left cell to the bottom from the top left cell to the bottom right side right side such that they are too condition right such that they are too condition right so basically a clear path is nothing but so basically a clear path is nothing but in simple what we can say if we are able in simple what we can say if we are able to move from zero comma zero cell to the to move from zero comma zero cell to the last bottom right cell that means n last bottom right cell that means n minus 1 to n minus one if we are able to minus 1 to n minus one if we are able to reach from this cell to this cell if we reach from this cell to this cell if we are able to meet these from this cell to are able to meet these from this cell to the cell that means the uh the that path the cell that means the uh the that path is nothing but a killer path right and is nothing but a killer path right and there is some condition between this there is some condition between this particular thing if you are starting particular thing if you are starting from this cell and you want to use the from this cell and you want to use the cell so there are some condition the cell so there are some condition the first condition is nothing but all the first condition is nothing but all the basic cell of the path are zero so let's basic cell of the path are zero so let's understand this with example so guys understand this with example so guys here if you are here right zero comma here if you are here right zero comma zero right this is the initial starting zero right this is the initial starting we can sell and you want to reach this we can sell and you want to reach this one common one right so you can't take one common one right so you can't take all other parts which have valuable you all other parts which have valuable you can take only those path or we can see can take only those path or we can see those cells which have a value zero those cells which have a value zero right they have clearly mentioned all right they have clearly mentioned all the wizard cell of the path r0 means the the wizard cell of the path r0 means the visited cell should we have a value zero visited cell should we have a value zero right so here from 0 comma zero you right so here from 0 comma zero you can't take this path that you can't move can't take this path that you can't move to this cell why because this is a value to this cell why because this is a value one you can't move to this one because one you can't move to this one because this also available so you can take only this also available so you can take only this one which is nothing but have a this one which is nothing but have a value 0 right so it's the second value 0 right so it's the second condition is nothing but all the condition is nothing but all the adjacent cell of path are it actually adjacent cell of path are it actually connected now let's understand this connected now let's understand this so guys let's assume you are standing so guys let's assume you are standing here right so this network one comma one here right so this network one comma one we can say Index right so that you can we can say Index right so that you can go to a direction from there how go to a direction from there how you can move to this one so you can move you can move to this one so you can move to the left you can move to the right to the left you can move to the right you can move to bottom right now you can you can move to bottom right now you can move to this diagonal as well you can move to this diagonal as well you can move to this one diagonal you can move move to this one diagonal you can move to this title you can move to this tag to this title you can move to this tag as well so you have eight possibilities as well so you have eight possibilities from this particular cell where you want from this particular cell where you want to move I hope this making a sense right to move I hope this making a sense right so you can move to a directionally at a so you can move to a directionally at a particular cell so these were the two particular cell so these were the two conditions uh from moving zero comma conditions uh from moving zero comma zero to n minus one command minus 1 that zero to n minus one command minus 1 that you can take only those cell which have you can take only those cell which have value 0 and you can move to a value 0 and you can move to a directionally at a time I hope guys now directionally at a time I hope guys now you understood the problem if I some you understood the problem if I some want to summarize it so let's summarize want to summarize it so let's summarize this particular line so basically you this particular line so basically you are given one Matrix grid Matrix will are given one Matrix grid Matrix will have a square Matrix and a binary Matrix have a square Matrix and a binary Matrix means having a valid Zero from one the means having a valid Zero from one the second thing we have to find a clear second thing we have to find a clear path in this Matrix which means we have path in this Matrix which means we have to start from zero comma 0 which n minus to start from zero comma 0 which n minus one command minus one such that the sun one command minus one such that the sun we are taking between uh that particular we are taking between uh that particular path should not have a value one and we path should not have a value one and we can move to a direction right and if can move to a direction right and if there is exist a one killer path that uh there is exist a one killer path that uh more than one kilo pass so we have to more than one kilo pass so we have to return the shortest path means the short return the shortest path means the short uh less number of cell we have listed uh less number of cell we have listed and if they not exit any single path and if they not exit any single path clear path so we have to return minus clear path so we have to return minus one so this is what the basically uh one so this is what the basically uh summarize of this particular problem summarize of this particular problem statement now let's see the example statement now let's see the example these two example how the answer 2 came these two example how the answer 2 came for this example and how answer fourth for this example and how answer fourth in this next example in this next example so here guys you I hope you understood so here guys you I hope you understood this from this cell we want to reach this from this cell we want to reach this so we are taking only this path so this so we are taking only this path so this is giving answer to how because this is giving answer to how because they have no tell that we are starting they have no tell that we are starting from here we have to reach the cell as from here we have to reach the cell as well right so we have visited this one well right so we have visited this one first cell now we can't take this one we first cell now we can't take this one we can't take this one but we can take this can't take this one but we can take this one so we jump to this particular cell one so we jump to this particular cell from the cell and we have visited this from the cell and we have visited this one also so total cell we have listed one also so total cell we have listed nothing but two so we are going to nothing but two so we are going to written two but in the next sum this written two but in the next sum this particular example you will understand particular example you will understand better how this particular answer this better how this particular answer this particular plate have a four answer so particular plate have a four answer so if you are here right if you are here right let's see I jump to this particular let's see I jump to this particular initi 0.0 initi 0.0 register this one right so every register this one right so every one cell one cell I move to this one because I can't move I move to this one because I can't move bottom it has valuable I can't move to bottom it has valuable I can't move to this one because it also have valuable this one because it also have valuable so I move to this one and I have visited so I move to this one and I have visited now those two cell right but I am here now those two cell right but I am here right now I can move to this one I have right now I can move to this one I have listed three cell this is a clear path right but this is not a shortest one so we have to find shortest one so the shortest one will be nothing but uh if we don't take this path right if we don't move to this one cell if we directly move to here then we are gonna uh we can see we can uh minimize our cost we can minimize our length right so we can say now we just need to visit only four cell one two three and four so total we can say optimal way or total the shortest clear path is nothing but four because we have visited only four cell to reach this particular Target set I hope this makes sense right so now check the path uh check the value of the cell we also need to check which one is the optimal one right so we could take this particular cell as well but this is not going to give optimal right we have taken this particular question which is giving optimal so the main logic in this problem is nothing but this only we have to find the optimal one so so that where we can move which can give us the optimal or which is the shortest path right so how we can do this let's see the logic part right so this is Commander logic how we can solve this problem so let me write a logic only and here let's understand this how we can solve this problem so guys just want to ask one thing uh just tell me whenever we need to find the shortest path in a graph which algorithm you get in your mind personal algorithm right I hope guys you are getting a BFS right BF is the only best algorithm we can say which help us to find a shortest path right now so here also we are going to use a BFS only and we are going to see how we can use a BFS to get the shortest foreign so that means we could not even start to find a path right they have not given a guarantee that you are always heading to this particular cell they have told that we have to start from here and reach to the right so that means this particular cell can also have a value one so we can make one condition that if the initial cell is having a value one that means you have to get a minus one directly if this is a value zero then you have to if this is a value zero then you have to use a BFS so here we are going to say we use a BFS so here we are going to say we are going to use a BFS and how BF is are going to use a BFS and how BF is going to work let's see that as well going to work let's see that as well right right so I'm going to make a first of all Q so I'm going to make a first of all Q and here guys I have uh initially I have and here guys I have uh initially I have only zero comma zeros and Light I'm at only zero comma zeros and Light I'm at this particular position and I have 0.0 this particular position and I have 0.0 and I have taken one step and I have taken one step I hope this makes sense right now we are I hope this makes sense right now we are going to move to the next we are going going to move to the next we are going to take this particular cell and we are to take this particular cell and we are going to see where else we can move from going to see where else we can move from this particular cell so once I hope this this particular cell so once I hope this particular 0 comma 0 I can see I can particular 0 comma 0 I can see I can move only to the right side right I move only to the right side right I can't move bottom I can't move this can't move bottom I can't move this particular diagonal I can't move particular diagonal I can't move anywhere except this right cell so I can anywhere except this right cell so I can say from zero comma zero I can move to say from zero comma zero I can move to 0.1 only fine 0.1 only fine so now but moving to this one I took a so now but moving to this one I took a second step right so total step is second step right so total step is nothing but two now I can say from 0 nothing but two now I can say from 0 comma one let's poke this one as well so comma one let's poke this one as well so I pop this particular cell and before I pop this particular cell and before popping I'm making it one right popping I'm making it one right so this CR7 the CR7 right so whenever we so this CR7 the CR7 right so whenever we are inserting this particular cell we are inserting this particular cell we are making it one fine so now once we are making it one fine so now once we can say pop this particular zero comma 1 can say pop this particular zero comma 1 so once I pop this I wanna check it so once I pop this I wanna check it where I can I can move this direction I where I can I can move this direction I can move to this direction but I can't can move to this direction but I can't move there there I can't move back as move there there I can't move back as well because this is already one if I well because this is already one if I move to this direction rights Direction move to this direction rights Direction so I have to insert 0 comma 2 in my so I have to insert 0 comma 2 in my queue if I move to this diagonal so I queue if I move to this diagonal so I have to insert one comma two in my have to insert one comma two in my right so I have by this I have taken right so I have by this I have taken third step which is nothing but I can third step which is nothing but I can move to this one or this one sir I hope move to this one or this one sir I hope this makes sense right now uh once I this makes sense right now uh once I inserted this two cell I am gonna make inserted this two cell I am gonna make this one as well right so these are one this one as well right so these are one now because we have visited this now because we have visited this particular thing particular thing now uh let's pop out this zero comma two now uh let's pop out this zero comma two so once I put this 0 comma 2 cell so so once I put this 0 comma 2 cell so this cell so I'm gonna say uh just see this cell so I'm gonna say uh just see where we can move from zero comma two so where we can move from zero comma two so from zero comma 2 we can't move this one from zero comma 2 we can't move this one right this is one we can't move bottom right this is one we can't move bottom this is one we can't move diagonal this this is one we can't move diagonal this is also one and we can't move the right is also one and we can't move the right side which is out of bound so we can see side which is out of bound so we can see we can't move anywhere from zero comma we can't move anywhere from zero comma two right so this is gonna give nothing two right so this is gonna give nothing to us right now let's pop this one comma to us right now let's pop this one comma two from one comma two you can move two from one comma two you can move bottom only so between nothing but two bottom only so between nothing but two comma 2 right and if you move into this comma 2 right and if you move into this particular version you are taking a particular version you are taking a fourth step so as you can see we reached fourth step so as you can see we reached to the last cell right whenever we are to the last cell right whenever we are opening up this particular cell we are opening up this particular cell we are going to check it if it if it is the going to check it if it if it is the bottom right cell or no if it is here so bottom right cell or no if it is here so return this particular step number of return this particular step number of steps right so here you can see once we steps right so here you can see once we are going to pop this particular cell so are going to pop this particular cell so we are going to check it this is this we are going to check it this is this the large self yes this is the last cell the large self yes this is the last cell of a grid means uh bottom line cell so of a grid means uh bottom line cell so you can see directly return step you can see directly return step so here we are going rate in four so so here we are going rate in four so this is how our algorithm work right so this is how our algorithm work right so you can see the BFS how this PF is going you can see the BFS how this PF is going to help in this particular problem now to help in this particular problem now let's move to the implementation part let's move to the implementation part let's implement this logic in Python let's implement this logic in Python simpler plus enter all right so here let simpler plus enter all right so here let me move to this one me move to this one so here guys in Python first of all uh so here guys in Python first of all uh let me tell you first of all we have let me tell you first of all we have already solved this one this is my already solved this one this is my second retake of this video so first of second retake of this video so first of all what we are going to do we are going all what we are going to do we are going to first of all check one condition read to first of all check one condition read of zero comma zero we could say if this of zero comma zero we could say if this is a one so this is basically is a one so this is basically determination directly if it is not say determination directly if it is not say node so we are going to calculate the node so we are going to calculate the length first so length of grid length first so length of grid collections here we can see DQ and here we can pass our zero comma zero cell right initially we are here zero comma zero fine once this is now we are going to say while Q we are going to find a size which is going to be talking about length of Q and here we can say for I in the of let me write Prime range of size here we can say uh take out the pope or the first element first of all so that is what we can say we're gonna give us row and column so we can secure dot Pope left right and here uh once we spoke about the slope element of Q we are going to move to a dash but before that we have to check this row row is equal to n minus 1 let me add n minus 1 and this column also equal to n minus that means this is the bottom right cell so we can see written our step right and we haven't declare a step so let's declare a step right step is going to be nothing but one initially right because we have taken a zero comma zero cell as well once this is done um if this condition two then we are going to return answer but if it is node two so what we are going to do we are going to move eight directions for eight directions we can say direction is nothing but equal to uh zero comma one this is uh one comma because Zero from minus one so this is nothing but we can say right and left and one comma zero bottom zero minus one comma zero down minus 1 minus 1 and we can say minus 1 comma 1 and we can say minus 1 comma 1 and the last one is nothing but minus and the last one is nothing but minus one comma one right so this is another one comma one right so this is another eight direction we have right once we eight direction we have right once we have got this direction we are going to have got this direction we are going to Traverse over all these directions one Traverse over all these directions one by one for a comma B in directions rho plus a current column is p once this is done we are going to check first of all this right so is greater than or equal to n right so is greater than or equal to n or current column is greater than equal or current column is greater than equal to n or we can say last thing is nothing to n or we can say last thing is nothing but if grid of current row and current but if grid of current row and current correct colon is equal to 1 that means correct colon is equal to 1 that means we can't take that we can't take that but itself right if any of this but itself right if any of this condition true we are gonna simply say condition true we are gonna simply say continue you don't we can't take this continue you don't we can't take this particular direction particular direction right if it is not the case that means right if it is not the case that means we can take it right so we can see first we can take it right so we can see first of all make this grid current row and of all make this grid current row and current column is equal to 1 which we current column is equal to 1 which we are marking them visited as well as we are marking them visited as well as we can't we don't want to move this can't we don't want to move this particular cell okay right and we are particular cell okay right and we are inserting this particular question in inserting this particular question in our queue so we can say Q dot append our queue so we can say Q dot append this particular set so you can say this particular set so you can say current row current column current row current column what's this done so once this Loop is what's this done so once this Loop is over we are going to implement our step over we are going to implement our step as well right so we are going to take as well right so we are going to take new Step again so we can calculate new Step again so we can calculate return minus 1 here and why it is so why return minus 1 here and why it is so why we are not returning here step see guys we are not returning here step see guys if there will be a path axis so it will if there will be a path axis so it will come in this particular condition right come in this particular condition right but if it node path actually so it's but if it node path actually so it's going to come out this particular while going to come out this particular while loop and we are going to return minus 1. loop and we are going to return minus 1. now let's see whether it's working final now let's see whether it's working final node let's try to run this code node let's try to run this code and I hope it should work right now it's and I hope it should work right now it's not working why syntax error invalid not working why syntax error invalid syntax all right so we haven't passed syntax all right so we haven't passed here uh minus one light now let's run here uh minus one light now let's run this code this code I hope now it should work right I hope now it should work right and you're taking a time again still and you're taking a time again still saying invalid syntax too we have done saying invalid syntax too we have done something wrong let's see that's so if you will focus here we have done any mistake or not let's check it so Direction it is a total is So we are it's fine right okay so we have used it's fine right okay so we have used common line here common line here now let's send this code it is some now let's send this code it is some syntax mistake I don't want that one as syntax mistake I don't want that one as well now you can see all the desk is well now you can see all the desk is password selected to submit this code password selected to submit this code and I hope it will also get submitted and I hope it will also get submitted right right and you can see guys it's successfully and you can see guys it's successfully submitted now let's move to the next submitted now let's move to the next programming language that is nothing but programming language that is nothing but C plus plus C plus plus and here first of all we are going to and here first of all we are going to check first condition that is great of 0 check first condition that is great of 0 comma 0 is nothing but we can say uh one comma 0 is nothing but we can say uh one so we can directly data minus 1. but if so we can directly data minus 1. but if it is not the case to find land which it is not the case to find land which network gives it or size network gives it or size right and after that you can say uh make right and after that you can say uh make a queue a queue which is clear of integer which is clear of integer and this Q's name is Lexi q and we can and this Q's name is Lexi q and we can see Q dot uh push this particular see Q dot uh push this particular we can say uh one uh we can see Zero we can say uh one uh we can see Zero comma zero right in this system and once comma zero right in this system and once you push it you can say step is going to you push it you can say step is going to be equal to one now you can stop uh be equal to one now you can stop uh start our while loop which is another y start our while loop which is another y uh Q is empty right Q is empty you can uh Q is empty right Q is empty you can move it so here you can say uh find out move it so here you can say uh find out the size because s I plus plus I plus plus here what you can do you can say uh pop here what you can do you can say uh pop out the first element right so we can out the first element right so we can say uh say uh which is right and you can see print also right once you have done this friend you can secure right and here data we are going to check if data DOT first is equal to n minus 1 and data dot second is equal to n minus 1 so you can simply return this particular step right but if it's not the case so you are going to move to a Direction so you are going to again make an array or you can right so uh instead of this if we could right so uh instead of this if we could make an array it will be easy right so make an array it will be easy right so we can say integer our directions array we can say integer our directions array and this direction I will have uh these and this direction I will have uh these directions let's make it first we have 0 directions let's make it first we have 0 comma 0 0 1 then we have zero comma comma 0 0 1 then we have zero comma minus 1. and we have um one comma 0 then minus 1. and we have um one comma 0 then we have minus one comma 0 then we have we have minus one comma 0 then we have one comma 1 and we have a minus 1 comma one comma 1 and we have a minus 1 comma one one uh let me write against the same mistake uh let me write against the same mistake I was going to do a minus 1 comma minus I was going to do a minus 1 comma minus 1 then we have minus one comma 1 then we 1 then we have minus one comma 1 then we have one comma minus one right have one comma minus one right once this is done we are going to move once this is done we are going to move to this particular direction set it for to this particular direction set it for INT INT is equal to zero I less than eight I is equal to zero I less than eight I plus plus plus plus thank you thank you all right and because there are eight all right and because there are eight elements after that we are going to say elements after that we are going to say uh take the correct Row in current row uh take the correct Row in current row is nothing but gonna be is nothing but gonna be current row is current row is note row here data DOT first plus this note row here data DOT first plus this directions right direction of I comma 0. directions right direction of I comma 0. hey hey and after that we are considering and after that we are considering current columns network data dot second current columns network data dot second Plus directions Plus directions of ie of ie and here we can pass one now we are and here we can pass one now we are going to check if it's Automotive so if going to check if it's Automotive so if current row is less than 0 over current current row is less than 0 over current column is less than zero or we can say column is less than zero or we can say let me have a zero so if it is so let me let me have a zero so if it is so let me just make it here just make it here and here current uh row is greater than and here current uh row is greater than or equal to n current row current column is equal to one so we can't take this right so let's continue There but if it is not the case so we are going to mark it first of all visit current period control current column is equal to one and here we can say let's insert in our queue so Q dot push you can push this particular thing Uh current row and current role in this while loop you can say uh step plus equal to 1. right after that if this you are coming out of this while loop that means you could not able to find a clear path so you are going to write a minus one so I hope this makes sense right so let's run this code and see with X working if I uh it should work right but it's a uh it should work right but it's a semicolon error right semicolon error right let's see do we have any more error oh let's see do we have any more error oh no right no right I don't think we should get an error I don't think we should get an error right right so let's see you can see all the desk is so let's see you can see all the desk is passworded to submit this code as well passworded to submit this code as well and by this we have successfully and by this we have successfully submitted with C plus plus submitted with C plus plus and here we go X successfully submitted and here we go X successfully submitted now let's move to the next programming now let's move to the next programming languages Java languages Java and here in Java what we are going to do and here in Java what we are going to do first of all we are going to calculate first of all we are going to calculate the length but before that we are going the length but before that we are going to check is create of 0 and 0 is nothing to check is create of 0 and 0 is nothing but equal to we can say here one so but equal to we can say here one so directly at minus one but if it's not directly at minus one but if it's not the case we'll find a length which the case we'll find a length which network length once you have done this network length once you have done this you are going to make a q so Q is you are going to make a q so Q is nothing but going to be a pair and pair nothing but going to be a pair and pair size and here you can see Q is going to size and here you can see Q is going to be earn Its Right Here Q only Q is equal be earn Its Right Here Q only Q is equal to New Link list to New Link list so guys let me Define a clear class here so guys let me Define a clear class here because we want to insert 2T row and because we want to insert 2T row and column so we can see class column so we can see class here and here we can say int first here and here we can say int first and in second let's make a new line and and in second let's make a new line and here pair and gonna take a into B and here pair and gonna take a into B and here we can see first is equal to a here we can see first is equal to a let me make it a better syntax let me make it a better syntax and first note first now second is going and first note first now second is going to network equal to B right to network equal to B right right once this is done we are going to right once this is done we are going to come here we are going to say this is a come here we are going to say this is a new queue we have created and and here new queue we have created and and here initially you have to insert Q dot you initially you have to insert Q dot you can say uh what you can do you can say can say uh what you can do you can say add this new pair add this new pair of 0 comma 0 right and you can make a of 0 comma 0 right and you can make a step is equal to one here we can say step is equal to one here we can say while skew while skew in a while in a while this node equal to Q dot is empty this node equal to Q dot is empty so you can say about nothing but uh you so you can say about nothing but uh you can find the first of all size so which can find the first of all size so which is next one as let's say and Q load size is next one as let's say and Q load size right right four four Theta is equal to 0 and less than s i Theta is equal to 0 and less than s i plus plus plus plus so you can do nothing but you can say uh so you can do nothing but you can say uh you're gonna take out the front element you're gonna take out the front element right right what you can do you can say uh queue what you can do you can say uh queue you can make it like pair only right you can make it like pair only right here that is nothing but a q dot remove here that is nothing but a q dot remove after that you can say if data DOT first after that you can say if data DOT first is equal to n minus 1 and data dot is equal to n minus 1 and data dot second is equal to n minus 1 so you can second is equal to n minus 1 so you can directly return directly return step but if it is not the case so you're step but if it is not the case so you're gonna move to eight directions so we can gonna move to eight directions so we can say Let's Get direction first so we can say Let's Get direction first so we can say integer directions say integer directions and here that made it here here only and here that made it here here only directions which is nothing but we can directions which is nothing but we can say uh zero comma one first of all then say uh zero comma one first of all then one zero comma minus one one zero comma minus one then again minus 1 comma 0 then again minus 1 comma 0 let me write here let me write here 1 comma zero let me get one only 1 comma zero let me get one only okay and here we can now move the okay and here we can now move the diagonal one so one comma one minus 1 diagonal one so one comma one minus 1 comma minus 1 and 1 comma minus 1 comma minus 1 and 1 comma minus 1 1 comma minus 1 and the last is nothing 1 comma minus 1 and the last is nothing but let me make it above minus one comma but let me make it above minus one comma right so we have make a direction eight right so we have make a direction eight directions we are going to move on this directions we are going to move on this for inter and we can say uh ARR of this for inter and we can say uh ARR of this directions directions here we can say uh here we can say uh that row is nothing but control is that row is nothing but control is nothing but rho plus this error of zero nothing but rho plus this error of zero the column is nothing but row Plus the column is nothing but row Plus error of one error of one right once we make this current term and right once we make this current term and column we are going to check it if this column we are going to check it if this current row is less than zero or current current row is less than zero or current column uh note this one current column is less than zero and one more condition that is Network current row is greater than n or equal to n and current column is greater than or equal to n or grid of current row current column is equal to one right so if this is the case come so we have to directly return we can say continue move to the next style we can't take this type uh particular step right now if it is not the true right if at all these conditions are false so we are going to come to this particular thing and we are going to first of all make this paste it so create current row current column mark this one that means we don't want to move here and next time and after that we are going to insert this particular thing in our queue so we can secure dot add new pair and here we can pass control current right after that we are going to increase this step and here we can return minus one because this will only come when we don't able to find a single clear path let's run this currency but let's work if I don't know or do we have any mistake here yeah there's a lot of mistake ideas so this is row row is not there right we have to use data DOT first and data dot second it's taking a time that means you can it's taking a time that means you can see all that is passed so let's try to see all that is passed so let's try to submit this code as well and by this we submit this code as well and by this we have successfully submitted with C plus have successfully submitted with C plus plus Java and python right and this was plus Java and python right and this was the easy problem isn't it I have the easy problem isn't it I have questions you understood the logic part questions you understood the logic part problem understanding part and problem understanding part and implementation part in the three implementation part in the three programming language if you still have programming language if you still have any kind of doubt we can write in the any kind of doubt we can write in the comment section I'm always there to help comment section I'm always there to help you and if you learn something new in you and if you learn something new in this video don't forget to hit the like this video don't forget to hit the like button subscribe my channel between the button subscribe my channel between the next video | 2024-03-25 17:12:10 | 1,091 | Shortest Path in Binary Matrix | Leetcode Q.1091 | Python | C++ | Java | LeetCode Daily Challenges |
|
skEofEGj46Y | Hello everyone welcome to my channel quote sir with me so today we are going to watch the video number of our t pointer technique with me so today we are going to watch the video number of our t pointer technique playlist playlist ok and the lead code is marked medium but ok and the lead code is marked medium but actually it is a very easy question actually it is a very easy question a lead code number is 1750 the name of the question is a lead code number is 1750 the name of the question is Minimum length of string after delete Similar Minimum length of string after delete Similar ends Okay, so what is being said in this is ends Okay, so what is being said in this is that you will be given a string that you will be given a string which will have only three characters a b and which will have only three characters a b and c you are asked to apply the following c you are asked to apply the following algorithm on the string any number of algorithm on the string any number of times this algorithm will give you times this algorithm will give you times this algorithm will give you point to be applied is that what is the algorithm that choose a non-MT prefix in that string whose all characters should be equal and choose a non-MT suffix in the same string whose all characters should be equal, okay and the prefix and safe suffix should It should not be It should not be It should not be that AB is CD, then whatever that AB is CD, then whatever prefix you chose, you chose ABC and suffix prefix you chose, you chose ABC and suffix CD, you cannot choose like this, no, yes, the CD, you cannot choose like this, no, yes, the character should be equal, let's character should be equal, let's assume that here it would be A, there would be A here also, assume that here it would be A, there would be A here also, you cannot choose like this. you cannot choose like this. you cannot choose like this. selected and there should not be an intersection from here, right? What is the last point? This is an important point. The character from the prefix and suffix must be the same, so the character must be the same. The length must be the same. It is Have A A A A A Have Have A A A A A Have Have A A A A A Have Y So then here B Let's say see you let's Y So then here B Let's say see you let's say Prefix You chose this Why did you say Prefix You chose this Why did you choose because all the characters are the same You choose because all the characters are the same You chose this suffix right all the characters are the same Its a is so chose this suffix right all the characters are the same Its a is so look the length of both look the length of both is equal but both is equal but both is equal but both should be the same, right? Delete both the prefix and 's', so you can delete both of them. So, the most important point is this fourth one, rest everything is very easy, so if you pay attention, what is he saying? When you delete, a little bit of string will be left in the end, its minimum length has to be found, that means you have to delete maximum from maximum, okay, performing the above operation any number of times, okay, like look at this example, try to choose the prefix, let's assume. You chose C and from here you chose A but the first character of both is unequal so you cannot select or delete anything, from here let's say you chose C as prefix and from here suffix you chose A If it is not equal, If it is not equal, If it is not equal, then you cannot delete it. Right, then you cannot delete it. Right, look at point number four, it will become invalid. Prefix look at point number four, it will become invalid. Prefix and suffix should have the same character, and suffix should have the same character, it has become invalid, that is why you could not delete anything. So, it has become invalid, that is why you could not delete anything. So, what is its length left? Only two of what is its length left? Only two of two is left. two is left. two is left. see here you have chosen the prefix 'C' and the suffix 'C'. Here you cannot choose 'C' because there are different characters in 'C', you have to choose the prefix and suffix with the same character. Look in both the prefixes There is only There is only There is only C in this also there is only C so you C in this also there is only C so you can delete both of them so you deleted both of them, can delete both of them so you deleted both of them, after that prefix you after that prefix you chose a, here you chose a, chose a, here you chose a, character is same in both, you can delete character is same in both, you can delete here here here can be deleted here A Chosen here A Chosen can be deleted Everything is deleted Length is zero left Okay look here this is a good example Look here first see the first character should match right Otherwise, if the first character is not matched, then why go ahead now, I mean, if there is A in the prefix here and there was a root here, then there would be no point, you could not have deleted it, right, then the first Should A Should A Should A and A match, let's see how many A's can be taken here. You and A match, let's see how many A's can be taken here. You can take two A's here because both have the same can take two A's here because both have the same character. Here you can take only one A. character. Here you can take only one A. Neither is the prefix. You Neither is the prefix. You chose the one in which all the characters are A chose the one in which all the characters are A in the suffix. in the suffix. in the suffix. are A, then only with the same character in prefix and suffix, you can delete both of them, so what you did is this and deleted it, after that look at the prefix, you chose this B, here you have I chose BB here because the I chose BB here because the I chose BB here because the character is same in both of them, so this is this and this is B, character is same in both of them, so this is this and this is B, you have blown it, after that look, this is C, this you have blown it, after that look, this is C, this is A, so both of them have been different, they are is A, so both of them have been different, they are different characters, so you will not be able to do anything right by deleting them. different characters, so you will not be able to do anything right by deleting them. So stop here, So stop here, you cannot move ahead, how much of this you cannot move ahead, how much of this string is left, what is its length, is it three? If you string is left, what is its length, is it three? If you see, this is a very easy problem, that is, it should see, this is a very easy problem, that is, it should not have been medium, but it is fine, it is very good for practice. good for practice. good for practice. what am I doing, I am using two pointers to find out the prefix and suffix. Right, the question itself is asking you to use two pointers, that is why this Two pointer Two pointer Two pointer technique is not clear cut, I told you the technique is not clear cut, I told you the problem clearly hints at delete from problem clearly hints at delete from two ints, two pointer is the only thing you have to use. two ints, two pointer is the only thing you have to use. Okay, so let's see with this example. If you want to Okay, so let's see with this example. If you want to use two pointer, then I have use two pointer, then I have taken two pointer, one is here. taken two pointer, one is here. taken two pointer, one is here. is fine here, so I had already told you that when will you be able to move ahead from A here and when will you be able to move ahead from J here, when I and J cutter should be equal, if I and Jth If not then If not then If not then you will not be able to progress further, you will never be able to progress further. Right, you will not be able to progress further, you will never be able to progress further. Right, look here, 'i' character is 'c', 'jet' character is 'c', look here, 'i' character is 'c', 'jet' character is 'c', meaning you can progress further, you can meaning you can progress further, you can delete it, now I will delete it, now I will see here how many such big see here how many such big prefixes I can extract. prefixes I can extract. prefixes I can extract. no C next to it, okay, so you can take only this much, right, here C is ahead and if there is no C, then J will remain till this much and we will first delete these two, so both of them will be I will come here and I will come here and I will come here and J will come here. J will come here. Okay, now let's see here, first Okay, now let's see here, first see if both the vectors are matching or see if both the vectors are matching or not. Yes, they not. Yes, they are matching. Okay, after that let's see how much more we are matching. Okay, after that let's see how much more we can take. A is further ahead. can take. A is further ahead. can take. A is further ahead. is B next, then only this A can be taken, here also A is next, otherwise you can only take this one, right, so you deleted both of them, then I came Okay, now Okay, now Okay, now look here, B and B are equal, meaning you look here, B and B are equal, meaning you can consider both of them for deletion. Let's can consider both of them for deletion. Let's see how big a prefix we can make. see how big a prefix we can make. Here B is there, if B is not there, Aa, Here B is there, if B is not there, Aa, make such a big prefix. make such a big prefix. make such a big prefix. make such a big prefix because here there is A, isn't it, and this is B, so you deleted both of them, then I came here, J came here, look here, Have to Have to Have to do a lesson h should be na aa do a lesson h should be na aa equal to b also h why can't you because it will equal to b also h why can't you because it will intersect na here intersect na here you have deleted these two aa gr sorry g e is done you have deleted these two aa gr sorry g e is done so the value has broken ours ok so the value has broken ours ok so now attention so now attention so now attention entire string is deleted, then my answer should be zero. Okay, let's see one more last example, you will write the code easily from that. This example is quite good, isn't it? Let's solve it, Let's run it once in the example also. Let's run it once in the example also. Let's run it once in the example also. First of all, what we have to see is First of all, what we have to see is that the I character and the J character should be equal. Only that the I character and the J character should be equal. Only after that you can find the prefix and suffix. So A is equal. Here A is here. A is okay. Meaning. is equal. Here A is here. A is okay. Meaning. is equal. Here A is here. A is okay. Meaning. can be done, now I will see how big a prefix Aa can make, so which character is ours? First of all, let's find out which character is A of Aa, isn't it, and s is off h, s is off h, s is off h, this is the only way we will move ahead, so okay, a off aa this is the only way we will move ahead, so okay, a off aa si means equal to a, okay, so si means equal to a, okay, so I moved aa forward, this is also equal to a, I moved aa forward, this is also equal to a, so I moved aa forward, I mean, so I moved aa forward, I mean, find such a big prefix aa. find such a big prefix aa. find such a big prefix aa. can delete, similarly J will also do the same and see how many A's he can find in the suffix, so J found this A, so J came here, but now J did not find A, So we So we So we can delete this prefix and this suffix, can delete this prefix and this suffix, okay, after that we will check again that the okay, after that we will check again that the rectangle character is B, so rectangle character is B, so what is the rectangle character, it is B and the jet character is also B, what is the rectangle character, it is B and the jet character is also B, so it can be deleted, now let's find out that so it can be deleted, now let's find out that How big can we make prefixes and suffixes? How big can we make prefixes and suffixes? So the rectangle character is now equal to B, so So the rectangle character is now equal to B, so Aa will come next. Aa will come next. Here, Aa comes next, but now it is equal to C. If a Here, Aa comes next, but now it is equal to C. If a different character comes then we can different character comes then we can get only this much prefix. Similarly, J is also J. get only this much prefix. Similarly, J is also J. Look, if J is equal to B, then J will come next. Look, if J is equal to B, then J will come next. This is also equal to B. J will come next This is also equal to B. J will come next but it is not equal to B now. So J but it is not equal to B now. So J got such a big suffix, so we got such a big suffix, so we deleted this prefix and this suffix at once. deleted this prefix and this suffix at once. Okay, now look at the i and zth character, they are Okay, now look at the i and zth character, they are not equal because the rectangle character not equal because the rectangle character is C and the zth character is A, so now we will is C and the zth character is A, so now we will break, there is no use of going further, break, there is no use of going further, you cannot delete, that is why you cannot delete, that is why your length is there, see how much it is. your length is there, see how much it is. your length is there, see how much it is. do indexing? 0 1 2 3 4 5 6 7 8 yes, then how much will j be? 5 - 3, how much is p, the length is three, this was the answer, so if you see, it is very easy from here. To derive what will be its code, first of all you had to keep in mind that the i which is there should be less than h and end you move ahead only when s off aa is equal to There is There is There is no use in you going ahead if these no use in you going ahead if these two characters become equal, meaning now we will two characters become equal, meaning now we will ask I and J to ask I and J to find out their respective prefixes and suffixes, then first of all we will find out the find out their respective prefixes and suffixes, then first of all we will find out the character that is the character that is the character which is equal. character which is equal. character which is equal. then it is the same thing, both are equal. Now I will give the opportunity to i to create a bigger prefix as far as v can delete. So let's do the lesson and and s of i. As long as this Till i plus plus will continue to happen na Till i plus plus will continue to happen na similarly pay attention here one thing j is greater than a a till this will continue na and and a of j till c is equal to the character then we will keep increasing j too till j is made minus minus Okay, after that when we come out of Y loop, what we have to return is to return j - aa + 1 ok now look pay attention this will give you the answer. Obviously this one will be solved but here I have marked it with blue, I have marked it with blue, I have marked it with blue, what is its reason, you will be able to what is its reason, you will be able to understand only after making a mistake, so look here, let us understand only after making a mistake, so look here, let us take an example from where it will be clear take an example from where it will be clear why I have marked it with blue. why I have marked it with blue. Okay, look at this example. Let's assume that Okay, look at this example. Let's assume that this is yours. this is yours. this is yours. pointer is here. I will say to I I will say to I that you make your prefix, that you make your prefix, which character is s of i or it is h which character is s of i or it is h then see what i will do I will then see what i will do I will say that I make your prefix say that I make your prefix now i < h should be and and s of a is now i < h should be and and s of a is equal to i is equal to equal to i is equal to equal to i is equal to is equal to i, it will be plus, right, so look here, pay attention, i is equal to a, yes, then i has moved ahead, okay, but now look, if i is not moving, then there is a break here, in which index is at index number one. Okay, is at index number one. Okay, is at index number one. Okay, now similarly remember the while loop of j used to run now similarly remember the while loop of j used to run as long as j is equal to jth character a as long as j is equal to jth character a then j will keep decreasing but notice then j will keep decreasing but notice what condition you wrote that j should be what condition you wrote that j should be greater than greater than greater than right here, but what will be the problem here, see Aa because Aa could not find so many prefixes, that Ai used to move ahead after this, okay, so here Ja What will you do? You will run a while loop on J is equal to I, What will you do? You will run a while loop on J is equal to I, What will you do? You will run a while loop on J is equal to I, otherwise this otherwise this character will be missed. It's okay, so for this character will be missed. It's okay, so for this you will have to put J is greater than equal to A, you will have to put J is greater than equal to A, not equal to A, that is why not equal to A, that is why I wrote here in blue. I wrote here in blue. I wrote here in blue. we can correct it later and it's totally fine, this mistake is released very often only after making a mistake. So here now see, this Y loop will run since it is greater than equal to two, isn't it? We will say, OK, we can delete it, then J will move ahead, right, J has moved ahead, now look, J is the lesson, then this while loop will not work, right, this while loop will not work because J is the lesson. Okay, so j is here, your index number is at zero, okay, now pay attention to one thing, after this, nothing can be deleted because look, lesson j is no more, right, Pay Pay Pay attention j - aa + 1 we would have returned attention j - aa + 1 we would have returned otherwise j what is mine is zero aa my one is done pv otherwise j what is mine is zero aa my one is done pv see the answer zero has come see the answer zero has come na that means this part is still correct na that means this part is still correct we just had to correct this thing j greater we just had to correct this thing j greater One must be equal to two and equal to has been One must be equal to two and equal to has been done just so that it does not get stuck in such cases. See, in this example of yours also the same case comes, the last one had come here, See, in this example of yours also the same case comes, the last one had come here, if the character had come here, then both the characters are if the character had come here, then both the characters are equal. equal. equal. see 'ha', it is equal to 'a', so 'aa' will come here, then 'je' should not stop here. Then the second loop should run, then j will come here, now j less then come, now the loop will break, right, after this j my a pv, here also the answer will be zero because So we have So we have So we have almost done the code, let us code quickly almost done the code, let us code quickly and finish it, but and finish it, but yes, time complex. If you see, we are yes, time complex. If you see, we are visiting each character only once, visiting each character only once, then it will seem like a time complex. Okay, then it will seem like a time complex. Okay, and how much is the space complex? and how much is the space complex? and how much is the space complex? because we have not taken any extra space and there is one more suggestion that if we assume that such a question comes in the future and if they say that you have to If If If you want to remove it then you can solve it from dex. It you want to remove it then you can solve it from dex. It is not from dex, what is there in dex that you will be able to is not from dex, what is there in dex that you will be able to insert the character easily and can delete it from the front also, you insert the character easily and can delete it from the front also, you can delete it from the back also, can delete it from the back also, then the remaining characters will be saved. then the remaining characters will be saved. then the remaining characters will be saved. create a string from it, because if you delete the string in the given input itself, let us assume from the front that you have deleted it, then it will be an o of n operation because If it is If it is If it is done by one then o will be off n, done by one then o will be off n, that will not be the correct solution, that means we that will not be the correct solution, that means we can give time limit sheet, that will be the best can give time limit sheet, that will be the best data structure for d, this means that it data structure for d, this means that it can be a follow up question. If this problem is can be a follow up question. If this problem is correct, then d can also be from k. correct, then d can also be from k. correct, then d can also be from k. and see if you are able to print the remaining string r Not for now just find the length So let's quote it and finish it So let's code it First let's find the length n and i and Let's define pointed n = add length aa will Let's define pointed n = add length aa will Let's define pointed n = add length aa will start from 0 j will start from n-1 start from 0 j will start from n-1 ok for pointer now ok for pointer now look while the length should be j and look while the length should be j and when will you start when i character when will you start when i character will be illu ill tj character will be illu ill tj character will be illu ill tj character not equal then there is no point in moving ahead. Like see the first example, aa vector zth vector is not equal then you cannot delete anything. Right, If it is equal, If it is equal, If it is equal, then which character is it? S = s, isn't it? then which character is it? S = s, isn't it? Then s of j is equal, only then you have Then s of j is equal, only then you have moved ahead. Now I will say i as a prefix. Make moved ahead. Now I will say i as a prefix. Make your i i < j. End and s of i should be your i i < j. End and s of i should be equal to s. equal to s. equal to s. you will be able to make further prefix i + + after this, if j is equal to i, I have explained to you why and and s of j should also be equal to this s, In the end nothing will be In the end nothing will be In the end nothing will be returned j - i + 1 returned j - i + 1 Submit and let's see Any doubt raise Submit and let's see Any doubt raise in the comment section Try to help or in the comment section Try to help or out See you Next video Thank out See you Next video Thank you | 2024-03-22 11:47:32 | 1,750 | Minimum Length of String After Deleting Similar Ends | Simple Two Pointers | Leetcode 1750 |
|
YtoibyDlzk0 | ok the name of the question is it has been asked many times it has been asked many times ok Google Amazon Meta Adobe Bloomberg mentarax ok I came to college in mental graphics this company then they asked this If If If there is input problem then understand what there is input problem then understand what is the question? The question is very simple. It is clear from the name also is the question? The question is very simple. It is clear from the name also that you have been given two binaries. that you have been given two binaries. You have to tell whether they You have to tell whether they are from both the objects or not, are they are from both the objects or not, are they replicas from both the objects or not, are they replicas from both the objects or not, are they correct to each other. correct to each other. correct to each other. van, okay man let's take root tu, so you have to tell whether both the trees are exactly the same or not, then it's okay, now you are on root van and root tu, so now find out whether these two What will you do after that go to the left of Route Van go to the left of Route Van and go to the right of Route Tu and after checking them, You You You will check right only then the exact will check right only then the exact structure should be correct. Values should also be same. structure should be correct. Values should also be same. If the root is left, then root 2 will If the root is left, then root 2 will also go to the left and then match it. Are these also go to the left and then match it. Are these two from both? Yes, they are from both, it is two from both? Yes, they are from both, it is very good, this is so. very good, this is so. very good, this is so. left is finished, the left is finished, then the route goes to the right of the van. This is one of the human beings. If all of them are done then our answer will be true. Okay, so see, the flow will be like this, the flow will be simple. The There are There are There are not many two, like look here, like I take, both of them are equal, it is very good, it is said, brother, check the left side also, so go to the left side and check, he will I will I will I will go and check that both of us will have to be go and check that both of us will have to be exact, structure wise exact, structure wise and value Vijay too, so when I extracted it from both of them, and value Vijay too, so when I extracted it from both of them, then both of them returned true to the then both of them returned true to the route van, brother, it is from the left side, route van, brother, it is from the left side, you returned it, it is you returned it, it is right. right. right. extracted from both, both we are getting to know that both the sides are we are getting to know that both the sides are absolutely true, so we have to do nothing else, absolutely true, so we have to do nothing else, how will we do it, the answer will be true, it how will we do it, the answer will be true, it is from everything. Write anything, it's okay, write anything, right, and just keep comparing, tree, okay, in this both the routes have been passed, tree, okay, in this both the routes have been passed, root van and root tu root van and root tu are okay. See, first of all, are okay. See, first of all, both the routes should be empty. both the routes should be empty. both the routes should be empty. my tap and end Root is also my tap, so it is an obvious thing, friend, still both are similar, both are empty trees, so even then my answer if it happens that brother, you have become Root Van, if it happens that brother, you have become Root Van, okay okay end end end Root Tu is not equal Tu, this is a okay, one, this case happened, then brother, it got messed up, it is return false, I mean, I am saying something like Root Van, this is Root Tu, So there was a note here and if not on its So there was a note here and if not on its So there was a note here and if not on its left then it is the same thing that if if it should be then it should be with only the route, you tap, or only the route, you tap, or only the route, don't take, see, or only the route, don't take, see, or both are tap, then we both are tap, then we will return the tour very much. will return the tour very much. will return the tour very much. both the notes are not tapped then either of them or one of the two will tap only and the other one [music]. [music]. So now our code looks something like this that So now our code looks something like this that if both the notes are tapped then if both the notes are tapped then start the return or else start the return or else start the return or else only one, then you will do return force, it means it is a toilet, it has a left side, this tree is not on its left side, it is okay, either take its voice and the like, it does not have a left side, it has a left side. Okay, either take it like this, it has a right side, it does n't have a right side, either take it like this, it goes to the right, it doesn't go to the right, okay, then there is a root, either one, if it is only null, then return This thing is cleared, why This thing is cleared, why This thing is cleared, why is it so, okay, the route has been checked, now we have to is it so, okay, the route has been checked, now we have to move ahead, move ahead, okay, so what I said, brother, if okay, so what I said, brother, if you have to go from this to this tree, then the left of the root van you have to go from this to this tree, then the left of the root van and the and the left of the root should also be equal. left of the root should also be equal. why end and end because brother, everything should be left right, why end and end because brother, everything should be left right, everything should be right for the route van return whatever comes from here, return whatever comes from here, okay, this is ours, this is the way of recovery, is okay, this is ours, this is the way of recovery, is n't it just a request? n't it just a request? n't it just a request? this is fine, what else can happen, write simple BF, everyone knows the BF signal, let's take main and we will pop both of them here, let's take main and we will pop both of them here, if the value of both does not match. if the value of both does not match. So return will be false, if value is not returned [music] then similarly we will check at the same time that if any one of the two notes is not presented, then return will be false. Okay, now when we go to court then it will be But it will also become clear, but it is But it will also become clear, but it is But it will also become clear, but it is basically the same thing, now those who are basically the same thing, now those who are checking in DFS should also check in BF checking in DFS should also check in BF that if we take main, it is a tree, it is its left that if we take main, it is a tree, it is its left child, is it right otherwise it will return child, is it right otherwise it will return false similarly. false similarly. false similarly. child and it doesn't have right side, even then we will attend false 22. Okay, so this is the simple check, you are done in BFS also, so let's code If If If you will understand it well, then let's do you will understand it well, then let's do this, this, so let's support, it is a simple so let's support, it is a simple question, okay, first of all, question, okay, first of all, what I said is that if P = N people what I said is that if P = N people means root, van means root, you are right, It is done by trick, we will return it. It is done by trick, we will return it. It is done by trick, we will return it. After this, what did I say that if there After this, what did I say that if there is only one tap then either this tap should be done is only one tap then either this tap should be done or it should not be done, or it should not be done, if both are there then it is absolutely right, it is a good thing, if both are there then it is absolutely right, it is a good thing, but there is only one tap. but there is only one tap. but there is only one tap. another condition in the middle, just don't take any one, remember this optimized condition, I told you that there is a long version as well, you can write that too, you are okay, we will return it to the case, okay, and what I said to And the value should be from Vijay also, And the value should be from Vijay also, And the value should be from Vijay also, which I which I probably missed this line in the explanation. Okay, the probably missed this line in the explanation. Okay, the value is also from If, okay, it should be from Well, which is not equal, the value of is P and K will P and K will P and K will go left, right? If we go left, right? If we call this entry return, right? We should get true on both sides, only then we will accept. Okay, let's say that it has been submitted. Let's solve this question by submitting. Let's reduce this. reduce this. reduce this. Okay, the first check will be that if both of them have null Okay, we will put P and similarly Okay, we will put P and similarly why will we put it in q2, till now it is clear, why will we put it in q2, till now it is clear, after that the old family method. Isn't it cute, till these two become empty, these people will keep going on, then what will happen in these note vans, q1 will come out in the front and why will they note tu will come out from where q2 has been note tu will come out from where q2 has been taken out from q2 and YouTube has been done, okay [ equal then it is a very good thing. Now if you have equal then it is a very good thing. Now if you have become equal then you will have to see all this below left right. become equal then you will have to see all this below left right. Okay then on the left side of note van Okay then on the left side of note van if there is no tap [ Music] [Music] If you are And this did not happen, does it And this did not happen, does it And this did not happen, does it mean that only mean that only one of the two's left chal is present i.e. one of the two's left chal is present i.e. Nude van's left equal tu must have been tapped Nude van's left equal tu must have been tapped or Note tu's left equal tu na or Note tu's left equal tu na dooba must have been present. If both were present then it is a very good thing. dooba must have been present. If both were present then it is a very good thing. Okay, so in such a case, the rate of return is fine for Note 2. If both are present then it is very good. We have attached the right side of both of them. It is okay. If both are not present then only one of them will be Right is Right is Right is present, if note tu ka is not present present, if note tu ka is not present then note tu ka right is present, if noteban is then note tu ka right is present, if noteban is not present then we will make it false in the case of not present then we will make it false in the case of return and in the last we will start return. If return and in the last we will start return. If false is not present anywhere false is not present anywhere then it is ok, what does it mean? then it is ok, what does it mean? If we reached the end, it means we did If we reached the end, it means we did not return false anywhere, everything was fine, let's not return false anywhere, everything was fine, let's see after submitting, this will also be done. Let's see see after submitting, this will also be done. Let's see great fair files question using BFS also. Similarly, both Yes, but there is a Yes, but there is a Yes, but there is a process for both to practice, process for both to practice, still code, it's ok if you get the hang of it, still code, it's ok if you get the hang of it, then you can see the next video, thank you. | 2024-03-20 13:53:37 | 100 | Same Tree | DFS | BFS | Google | Leetcode 100 |
|
ZFxI3kKcnGM | hey hey everybody this is larry this is day day 21 of the leco daily challenge for 21 of the leco daily challenge for september september uh hit the like button hit the subscribe uh hit the like button hit the subscribe button join me on discord and let's go button join me on discord and let's go get started on today's problem get started on today's problem carpooling um carpooling um you're driving a vehicle that contains you're driving a vehicle that contains capacity of me the vehicle only drives capacity of me the vehicle only drives these these so going from left to right say give me so going from left to right say give me a list of trips from number passengers a list of trips from number passengers starting and starting and and contains the number of padding that and contains the number of padding that must be picked up and it'll get bigger must be picked up and it'll get bigger give me this okay return troop it was give me this okay return troop it was possible to drop them off okay possible to drop them off okay so okay and capacity is given to you uh so okay and capacity is given to you uh so yeah this seems like a very so so yeah this seems like a very so basically because basically because um the car can only go from left to um the car can only go from left to right or you drive these right or you drive these um you basically have this thing where um you basically have this thing where you just go from left to right right um you just go from left to right right um and from that this should this motion or and from that this should this motion or this idea this visualization of going this idea this visualization of going from left to right from left to right should give you an idea which is uh the should give you an idea which is uh the sweep line algorithm and that's sweep line algorithm and that's basically what i'm going to do basically what i'm going to do by converting these into series of by converting these into series of events and then let people get offers events and then let people get offers and stuff like that and stuff like that uh basically very greedy and then see uh basically very greedy and then see whether we're able to whether we're able to uh and we'll go over the details as i go uh and we'll go over the details as i go do this do this but but that's the general idea um it's but but that's the general idea um it's okay for example at station one you pick okay for example at station one you pick up two up two person two people at station three you person two people at station three you pick up three and that's not you know pick up three and that's not you know it's not possible right and so stuff it's not possible right and so stuff like that like that uh let me know what you think i think uh let me know what you think i think this is okay so let's see this is okay so let's see uh so let's start with defense as you go uh so let's start with defense as you go to a list to a list and then four i'm just looking at the and then four i'm just looking at the trips format so trips format so yeah four passengers oops yeah four passengers oops uh start and in trips uh start and in trips let's let's put it in the events right let's let's put it in the events right so we add two events to each one so we add two events to each one um the first one is getting on so we add um the first one is getting on so we add the number of passengers on the start the number of passengers on the start event event and then this latter one is the end and then this latter one is the end right or negative passengers because right or negative passengers because that's how many passengers are getting that's how many passengers are getting off off um the thing that i'm looking for here um the thing that i'm looking for here now now is try to figure out whether we get off is try to figure out whether we get off exactly at a location or end location exactly at a location or end location minus or plus one minus or plus one uh sometimes in the problem context you uh sometimes in the problem context you have to figure it out have to figure it out in this case it is okay and what i mean in this case it is okay and what i mean by that is that by that is that if two people get on at the same time if two people get on at the same time well if one gets off well if one gets off uh or people get on and off at the same uh or people get on and off at the same station station how do you hand resolve that right so how do you hand resolve that right so so in this case i think it should be so in this case i think it should be okay um okay um because in this case because the way because in this case because the way that we sort if that we sort if there's a tiebreaker between two there's a tiebreaker between two locations uh the negative ones will locations uh the negative ones will always go first always go first and and then varian is that you can you and and then varian is that you can you will always have will always have at most passengers on the on the right at most passengers on the on the right right you can't go negative because right you can't go negative because you can't have negative passengers right you can't have negative passengers right so so so we we want to greedy on uh so that's so we we want to greedy on uh so that's why why this sorting order is okay because we this sorting order is okay because we want to agree on the number of want to agree on the number of passengers first on the same point but passengers first on the same point but we're still going from left to we're still going from left to right so we're sorting under the right so we're sorting under the starting point so yeah so i think that's all we need for this part and then now we have to process each event at a time yeah let's go to station just trying to yeah let's go to station just trying to find naming um find naming um and passengers in uh events and passengers in uh events right so let's have also uh current right so let's have also uh current passengers passengers current number of passengers maybe it's current number of passengers maybe it's zero and then here we go okay zero and then here we go okay current passengers we could simulate current passengers we could simulate uh we add the number of passengers and uh we add the number of passengers and because we set the delt the um because we set the delt the um the minus explicitly this allow us to the minus explicitly this allow us to get negative passenger so another way get negative passenger so another way you can do this is actually have two you can do this is actually have two events events so for example uh for start you can have so for example uh for start you can have uh uh getting on the event and getting off the event right and then in this case you would write maybe something like and then this is positive and then you get something like if getting off you do negative or something like that but uh but that's already baked into how we structure this so that's okay and then now so there are two invariants that we want to keep here right the first one is passengers has to be greater than zero and this one is trivially true because just by the the way that we construct this uh there's a symmetry to this and assuming start is always going to be bigger than n which is seems to be the case here um you know you can like the number of negatives can only appear after they're positive so it's always gonna be zero but i'm just putting here for visualization and we um yeah and so this is okay and then the other one is within capacity right uh so that's the other thing that i'm concerned with so this is good so we just continue maybe we could win in another way or maybe another way to write it is if this is not true um then we return force because that means that there's too many people on the train or on the bus or what the car uh or to feel right so if at the rate and we pass everything then we can return true uh and that's pretty much uh i think that's pretty much it we'll go over the complexity in this second are the the test cases in here what is going on okay maybe i should what is going on okay maybe i should have just done it have just done it a different way i am solving this live so sorry this is uh this part is less interesting but anyway okay so one detec code run it it should be good um yeah and then maybe the only thing i would check is like empty or too much too soon or same station i too much too soon or same station i don't i think don't i think can it be same they get on and off at can it be same they get on and off at the same station the same station um no it cannot so okay um no it cannot so okay so let's say the next station uh a so let's say the next station uh a thousand i don't know thousand i don't know 10. yeah so just a few a few more test 10. yeah so just a few a few more test cases and you could cases and you could add us to oh i guess that's weird where is the list index our that's weird where is the list index our range range did i have a typo it's a little bit awkward but huh i mean i don't do anything why is that weird those trips would be just empty trips right so this doesn't huh did i have a typo huh did i have a typo or an empty array this index out of or an empty array this index out of range range this is not um this is not a standard python ever so maybe it's just something on the other side i don't think uh let's prove me wrong i'm gonna submit it i'm confident enough about this uh and they don't tell you that this is this they don't tell you that this is this could be greater than zero that's why i could be greater than zero that's why i added that test but maybe there's added that test but maybe there's something wrong on the service problem something wrong on the service problem uh uh a solution yeah so what is the a solution yeah so what is the complexity of this well we do create um complexity of this well we do create um an event for every trip or two events an event for every trip or two events where we trip so it's gonna be linear where we trip so it's gonna be linear space space and with that result it's gonna be 2 and with that result it's gonna be 2 n log 2 n which is n log n uh n log 2 n which is n log n uh so n again time so n again time uh and space um of n space uh and space um of n space so yeah that's that's the problem i have so yeah that's that's the problem i have here uh it's pretty straightforward and here uh it's pretty straightforward and once you kind of get used to this once you kind of get used to this technique you can see that um technique you can see that um it's pretty straightforward right uh and it's pretty straightforward right uh and it's very it's very few places to make errors so yeah it's few places to make errors so yeah it's what i prefer what i prefer anyway um hit the like button hit the anyway um hit the like button hit the subscribe button join me in discord let subscribe button join me in discord let me know what you think about this farm me know what you think about this farm how did you do how did you do do you like cardboard uh maybe not doing do you like cardboard uh maybe not doing the pandemic but the pandemic but anyway uh i will see y'all next prom anyway uh i will see y'all next prom tomorrow tomorrow bye | 2024-03-25 17:18:37 | 1,094 | 1094. Car Pooling - Day 21/30 Leetcode September Challenge |
|
ak1VtSLhibI | hello guys and welcome back to lead Logics this is the path Crossing problem Logics this is the path Crossing problem from lead code this is a lead code easy from lead code this is a lead code easy and the number for this is 1496 so in and the number for this is 1496 so in the given problem we are having a string the given problem we are having a string path where path of i path where path of i signifies uh a letter in from the signifies uh a letter in from the following n s e w representing uh north following n s e w representing uh north south east and west and one unit at a south east and west and one unit at a time so we have to start at the origin time so we have to start at the origin on a 2d plane and walk on the specified on a 2d plane and walk on the specified path and we have to return true if it path and we have to return true if it crosses the path crosses itself at any crosses the path crosses itself at any point of time uh while traversing so point of time uh while traversing so let's see for this example first we move let's see for this example first we move to the to the north so north so suppose uh we move one unit not we reach suppose uh we move one unit not we reach this this point the coordinate for this will point the coordinate for this will be 0 uh 0a 1 and then we we we move one be 0 uh 0a 1 and then we we we move one coordinate East to the coordinate East to the coordinate new coordinate now become 1 coordinate new coordinate now become 1 comma 1 and now we move to the South so comma 1 and now we move to the South so the new coordinate the new coordinate becomes becomes the 1 comma 0 the 1 comma 0 so in the process we haven't reached 0a so in the process we haven't reached 0a 0 yet again so that means 0 yet again so that means that this uh part doesn't cross that this uh part doesn't cross itself now let's see the another example itself now let's see the another example now we have n s now we have n s ww so first we move to the north yes the ww so first we move to the north yes the coordinate becomes 0 1 Now we move to coordinate becomes 0 1 Now we move to the east the coordinate becomes 1 1 then the east the coordinate becomes 1 1 then we move to the South the coordinate we move to the South the coordinate becomes 1 becomes 1 Z and then we move to the West that then Z and then we move to the West that then the coordinate become 0 0 this means we the coordinate become 0 0 this means we have have Crossing then at 0 0 we have a have have Crossing then at 0 0 we have a Crossing that means we can return true Crossing that means we can return true so the answer is true so the answer is true so uh it is not very important that you so uh it is not very important that you uh map the coordinates correctly on like uh map the coordinates correctly on like X on the xaxis like X first or the Y X on the xaxis like X first or the Y first according to the mathematics as first according to the mathematics as you create the pier but it is important you create the pier but it is important that you keep a variable for the that you keep a variable for the vertical displacement and a horizontal vertical displacement and a horizontal displacement and at any point of time if displacement and at any point of time if the uh vertical displacement and a the uh vertical displacement and a horizontal displacement become Zero from horizontal displacement become Zero from the point you can uh the point you can uh definitely uh return true and if at the definitely uh return true and if at the end of the string after traversing the end of the string after traversing the string if if it does not uh reach 0 that string if if it does not uh reach 0 that means it does not cross the path so you means it does not cross the path so you can simply associate a plus with the can simply associate a plus with the North and a minus with the South for a North and a minus with the South for a variable and you take another variable variable and you take another variable and plus with the East and minus for the and plus with the East and minus for the west or vice versa as you like and you west or vice versa as you like and you we can keep a map and in the map uh that we can keep a map and in the map uh that will be a map of will be a map of pairs and uh we can keep pairs and uh we can keep the displacement for per unit like for the displacement for per unit like for every move we can save every move we can save the uh displacement per unit the uh displacement per unit displacement and we can keep a visited displacement and we can keep a visited array or a visited set of pairs array or a visited set of pairs that keeps that keeps the uh visited locations at and at any the uh visited locations at and at any point of time if you get the 0 again or point of time if you get the 0 again or if you get any if you get any other any other visited location in the other any other visited location in the set already then we can return to now set already then we can return to now let's come to the code section but let's come to the code section but before that do like the video share it before that do like the video share it with your friends and subscribe to the with your friends and subscribe to the channel so we'll take a map of channel so we'll take a map of character and character no that will be a map of uh character with the integer let's call this moves and a hash [Music] so let's say for not we move zero and this and then for South we'll this and then for South we'll move 0 andus one and then we have East East 0 1 0 1 Z and the then we have a Z and the then we have a West that will West that will be minus be minus one and West n ew all four one and West n ew all four complete now let's define a set of pairs complete now let's define a set of pairs of of integer an integer this will be used to store the visited locations at and at any point of location we'll say that the path crosses itself but before this I think we need to add the origin in set visited do set visited do add new zero so okay we have added the origin zero so okay we have added the origin now we have to move in now we have to move in the now we'll take a pair at a so this will be the current so this will be the current [Music] [Music] move and that comes from the move dot move and that comes from the move dot get C so if it will be n the PIR return get C so if it will be n the PIR return will be 01 if it will be S the PIR will be 01 if it will be S the PIR return will be 0 n minus one and return will be 0 n minus one and similarly for w as similarly for w as well now in DX equal to current dot well now in DX equal to current dot get so the key value is the get so the key value is the X and Dy is the current dot get value right so the current do get value and then we have x + DX and the y Dy but we need to define the XY Dy but we need to define the XY here for this so let's Divine pair so the new pair consist of the X pair so the new pair consist of the X and the and the Y and Y and if visited do if visited do contains pair then we return to if at any point of time we see that the pair already exist in the visited array we simply return I think it will be returned through because it is a Boolean function and otherwise we'll add the pair pair and if at all after all the loops we do and if at all after all the loops we do not get a true returned we return a not get a true returned we return a false now let's run for the sample test false now let's run for the sample test cases so the sample test cases are cases so the sample test cases are passed you can see let's try to run for passed you can see let's try to run for the hidden test cases as well so hi test cases are also passed with a good time complexity and a fair memory complexity so the time complexity for this solution is O of n because we iterate through the string ones and the space complexity is also o of n because the we keep a map and so this map takes constant space but this set contains the number of uh path pairs so for this actually the uh the space OB becomes ofn you can also check the C++ Python and JavaScript code by going into the solutions panel and then checking my [Music] solution for you it will be available in the H section but it is think this this one is my solution you think this this one is my solution you can go check it out it can of the can go check it out it can of the explanation intuition approach explanation intuition approach complexity the Java solution C++ Python complexity the Java solution C++ Python and JavaScript and yes do remember to and JavaScript and yes do remember to upot and also tell if you are a cat upot and also tell if you are a cat person or a dog person so I hope you person or a dog person so I hope you understood the logic thank you for understood the logic thank you for watching the video please like the video watching the video please like the video share it with your friends and subscribe share it with your friends and subscribe to the channel if you're new to the to the channel if you're new to the channel thank you have a nice day | 2024-03-21 11:04:07 | 1,496 | ✅ Path Crossing - LeetCode 1496 - Map Single Pass - Explained and Visualized - Strings - Maths |