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
|
---|---|---|---|---|---|
gcqGtHZx3-w | continue from an ass problem which is 51 in Queens let's take a look at number 52 in Queens let's take a look at number 52 in Queens number 2 so the problem is in Queens number 2 so the problem is same except that we need to return the same except that we need to return the number of distinct solutions well it's number of distinct solutions well it's it's totally the same right so please if it's totally the same right so please if you if you have any questions if I have you if you have any questions if I have something I'm familiar with this problem something I'm familiar with this problem please take a look at my previous video please take a look at my previous video in my channel which is 51 and Queens in my channel which is 51 and Queens here I just copy paste my code I'll get here I just copy paste my code I'll get to do some to do some tricks to do some to do some tricks so the the problem asked us to return so the the problem asked us to return the result number of results with not the result number of results with not the results so let's say results equals the results so let's say results equals 0 here we will put the final result 0 here we will put the final result rather than this we were just update the rather than this we were just update the result plus 1 and it should be issue result plus 1 and it should be issue work yay yay this actually would be the work yay yay this actually would be the fastest solutions in my home this will fastest solutions in my home this will be the fast the shortest video in my be the fast the shortest video in my channel so here that's all for this channel so here that's all for this problem please take a look at my other problem please take a look at my other videos for example the previous Sudoku videos for example the previous Sudoku problem and these n queen problem problem and these n queen problem they're all backtracking hope it helps they're all backtracking hope it helps you a little bit that's all for this you a little bit that's all for this time see you next time bye bye | 2024-03-20 10:13:09 | 52 | leetCode 52 N-Queens II (Backtracking) | JSer - algorithm and JavaScript |
|
4zbV0xSMo2k | Hello, this is Nagopa from Live Coding. Today, I will solve problem number 1255 of Litcode, Maximum Score Today, I will solve problem number 1255 of Litcode, Maximum Score World Form by Letters. The pronunciation is a bit bad, but please pronunciation is a bit bad, but please understand and the understand and the difficulty level of the problem is hard. The problem was difficulty level of the problem is hard. The problem was taken from Litcode, taken from Litcode, but it is a hard problem. but it is a hard problem. but it is a hard problem. not that difficult. It was a very typical backdracking problem. Still, if you look at it, the ratio of likes to dislikes is much higher than you might expect. I don't know if people gave it good scores because the problem was easy, but they gave it very good scores and it was because it Well, this number Well, this number Well, this number doesn't seem to be that many. To doesn't seem to be that many. To put it simply, to put it simply, you create a world put it simply, to put it simply, you create a world using letters and letters according to conditions. using letters and letters according to conditions. When you create a world according to conditions, you create the highest score and return it. create the highest score and return it. Now, I Now, I will explain in detail what the conditions are. As input, the worlds come in like this, the letters come in, and the score comes in. These three types of information come in, and these worlds can be made using these letters first. Since there is a dog, Since there is a dog, we we can make a in this dead, and there can make a in this dead, and there are three d. So, we are three d. So, we can make soybeans, and it becomes good, so we can make soybeans, and it becomes good, so we can make a national road. And can make a national road. And since cat does not have a t here, we since cat does not have a t here, we cannot make a cat. In the cannot make a cat. In the case of dog, case of dog, like dog. like dog. like dog. using laterals. Once you create a world using laterals, the using laterals. Once you create a world using laterals, the letters you used cannot be used. Because they have been used, they will be removed. So, if you Because they have been used, they will be removed. So, if you make this or that in Word, the make this or that in Word, the letters will disappear, so you could make them in the past. letters will disappear, so you could make them in the past. making a word, there are cases where you making a word, there are cases where you cannot make the next word. cannot make the next word. And the And the scores below are scores below are 26, 26, a is 1.c is 9 points, etc. a is 1.c is 9 points, etc. So a is 1.c is 9 points. So a is 1.c is 9 points. d is 5 points, d is 5 points, g is 3 points, 5 is 2 points, g is 3 points, 5 is 2 points, so a number is entered in the position of a c d g o like this. As a so a number is entered in the position of a c d g o like this. As a result, the result, the optimal result is 23. optimal result is 23. When choosing which one, When choosing which one, dead is 11 points and 9:00 20 is dead is 11 points and 9:00 20 is 12 points. 12 points. is an explanation of why it is best to choose this way. is an explanation of why it is best to choose this way. If you understand the problem, let's solve it right away. First of all, in order to increase efficiency a little, for optimization, it is increase efficiency a little, for optimization, it is not that big of a deal, but I will give you a score not that big of a deal, but I will give you a score for this world in advance. for this world in advance. for this world in advance. calculated it. Using preprocessing like this, the world's score is 10 points because there is no dog cat t, and dad is 11 points from good to 12 points. Yes, so I So, I So, I So, I calculated the score of the world that can be created in advance. So, rather than calculating these over and over again whenever necessary, once the word is set, the score is set, so I created a table like this in advance and reused it to reduce runtime time. And And backtracking is typical backtracking. I don't backtracking is typical backtracking. I don't know if I need to explain it here, but know if I need to explain it here, but to help you understand, I to help you understand, I created a state space tree. I will show you how to update the remaining counters of this letter while creating a state space tree. remaining counters of this letter while creating a state space tree. first one is 0 because nothing was selected, and first one is 0 because nothing was selected, and initially we initially we expressed the input letters in this way. expressed the input letters in this way. Then, the Then, the light child is the score value of the tool when the tool is selected when selected. score value of the tool when the tool is selected when selected. score value of the tool when the tool is selected when selected. since poison was used, the values are updated here. Cat cannot have a right child, so of course it cannot have a right child. So it goes straight to the left child. And then, so now the point is also 10.5. It is the same and the letters are unchanged. Then, when you select dead, the ratter for dead is removed and since dead is worth 11 points, 21 points are expressed. Good cannot be made with the current letter counter, light child light child light child go straight to the left child, the current point is 21 points as the maximum point, and since all 4 points have been turned, the since all 4 points have been turned, the current maximum value is 21. current maximum value is 21. And because it And because it returns to the back, which is called backdragging. returns to the back, which is called backdragging. When you throw away the good and go back, this letter is renewed again. I thought you were using beads, but you didn't. That's why you renew it again, and since you can't go to the light, it goes up to the back again and updates it here. So, it's updated like this. if you do not select dead again, this value is maintained as is and the point is also maintained at 10. Then, you cannot select a bead again here, because you need good, but there is only one o. So it becomes the left child, the letter does not change, and the point does not change. So, we were recording 21 earlier, and this time, since the value was 10, we will ignore it. So far, we want to find the maximum value, It keeps going and It keeps going and It keeps going and goes up and goes up and goes up and goes up and goes up and goes up and goes up and so on, goes up and so on, and in the end, if you don't select the dock, the letter will be maintained and if you do n't select the tool, the point will be 0. And since you can't select the cap either, this part is a bit narrow, so I skipped it. If you select Goyo Dead, it is updated like this and you get 11 points. And in this state, because there are two 5s, you can select g5d. So 23 points, so 21 points was the optimal score earlier, but it is updated to 23 points. Now, if you do Now, if you do Now, if you do n't select the number, it's n't select the number, it's 11 points, so it won't be updated and 11 points, so it won't be updated and 23 points will be 23 points will be returned. returned. Of course, it's Of course, it's natural, but if you don't select something, there's no point in choosing it, it's less than 23, so it's than 23, so it's just just just Yes, so now, if I put this into coding, the code may seem a bit long. It may look long, but I will explain this part in more detail when I live code it. First, I will explain only the skeleton, starting with the large framework. This word. word. word. calculate the world score in this way, and calculate the world score in this way, and if we can't make it now, we if we can't make it now, we put 0 in the score and preprocess the calculation in this way, which becomes the backtracking code we need. becomes the backtracking code we need. becomes the backtracking code we need. order to use the return type, which is a global variable, I just put it in like this. If I go to the end, I save the larger of the two between the current highest score and the highest score save the larger of the two between the current highest score and the highest score so far. Otherwise, it ends here. The return of this solve function is this word The return of this solve function is this word of the current score. of the current score. of the current score. score, the score is passed on. You have made a choice. You have chosen to create the current world. That is why, if you look at the statement above, the counter value is continuously subtracted. By continuing to subtract the necessary count values from this world, the The update occurs, and The update occurs, and The update occurs, and then this function part is finished, and then this function part is finished, and when it returns to the back, the subtracted part is when it returns to the back, the subtracted part is added again to restore the original. added again to restore the original. Yes, that's why this name is called backdracking. Yes, that's why this name is called backdracking. When selected, it When selected, it has this type of structure. This rumor has this type of structure. This rumor has this type of structure. This rumor can you choose? I couldn't make a choice in the case of the cat earlier. So in this case, if you get caught, you will definitely not ride the part below. You will definitely not ride the part below. You will all go down. If you get caught in the cat, you have to choose. get caught in the cat, you have to choose. get caught in the cat, you have to choose. can choose between doing it or not doing it. When you get caught in a cat, you are forced to not make a choice. If you are a child who can make a choice, you will go through this type of routine and make a choice. And of course, if you do not make a choice, you will use the By passing it in, the current score is By passing it in, the current score is By passing it in, the current score is maintained and the letter is also maintained. maintained and the letter is also maintained. Since the letter is maintained, there is no need for a function to restore it when the function is finished. no need for a function to restore it when the function is finished. So, with the Solve function, the So, with the Solve function, the starting point and current point are also 0, and if you starting point and current point are also 0, and if you pass the letter counter, this function will take care of it. pass the letter counter, this function will take care of it. will return the desired result to us, so it is a problem will return the desired result to us, so it is a problem of this type where we just need to print the return as the return value. However, because it was a hard problem today, the explanation was a bit However, because it was a hard problem today, the explanation was a bit long, but if today's lecture long, but if today's lecture was helpful, please subscribe, like, and set an alarm. Listen to the was helpful, please subscribe, like, and set an alarm. Listen to the lecture. lecture. lecture. | 2024-03-19 17:36:26 | 1,255 | [LeetCode][Hard]1255 Maximum Score Words Formed by Letters 강의 |
|
Xzpm4uqlObs | Ask question will solve maximum products sub is aa products sub is un given date has largest product and return d non empty sequence of element with it saying non empty sequence of element with it saying ok ok first let's see ok ok first let's see how to solve it here how to solve it here 2 * 2 * 2 * next one after this will be negative, so let's see how we will solve it, now we have done it to express [Music] Question Related Topics Dining Programming Maximum product is all right, Maximum product is all right, Maximum product is all right, it will be solved, so what will be your output here? If it becomes negative then it will we take? One, we will take minimum, we will maintain minimum we take? One, we will take minimum, we will maintain minimum and we will maintain maximum. and we will maintain maximum. Two things, we will maintain minimum and Two things, we will maintain minimum and maximum. Why? maximum. Why? maximum. Why? may be a case like this, I have a negative data, later another negative here I have positive data, here I have positive data, so to handle it, I so to handle it, I need both minimum and maximum because need both minimum and maximum because here the product. here the product. here the product. I have to handle another case, if zero is gone in between, zero is gone in between, what will happen in that case, in this case, if you multiply any data, it will become zero, then to handle it, find the minimum. In that case, I will close the minimum and make the maximum gobi maa [Music] Now what, when the next turn comes, what will happen in this case, [Music] [Music] 72 So here is negative The maximum is 36 till now, The maximum is 36 till now, 36 here like this -4 * 9 If I take this much from here, then eight will come from here If I take this much from here, open a new folder and put [ So here [Music] Products Products Products are ok earning in music, I will slice the van to Max, I will come to the next line, but take him, it's simple, all three have passed, take him, it's simple, all three have passed, in some languages, all three cannot pass, in some languages, all three cannot pass, its alternative, now if a video of it will be made its alternative, now if a video of it will be made then I then I it will be updated then I will it will be updated then I will take it here then it will be messed up so I have take it here then it will be messed up so I have already done it to fix it then I will do it now then Going Going And then to find N*, I don't need it right now. If after that I still need any data in which I comment, I used to update something in my scale. I used to update something in my scale. I used to update something in my scale. what will I do with the result, I will take max of I know this much that my friend, I know this much that my friend, everything is going well, how can I find out in a simple way, if I tell you in a simple way, before I wind up, let me tell you a little bit, what have I done, what have we Kar Max and Karma Liya End Kyun Kyun Kyun [ Music] [ ] [ doing it, nothing else is doing it, doing it, nothing else is doing it, so now only time will remain simple, there was so much so now only time will remain simple, there was so much in this video, there was so much in this video in this video, there was so much in this video in this video, there was so much in this video in the next video had ended the video but before that I had ended the video but before that I forgot to tell you one small thing, let me tell you a forgot to tell you one small thing, let me tell you a simple condition, this condition is written, there is simple condition, this condition is written, there is no need of any condition, it will reduce it because no need of any condition, it will reduce it because of Max and Mini. of Max and Mini. of Max and Mini. maximum it will be zero in case, then it will be A in the minimum and zero in whatever and whatever. Exactly means we are also writing n here, which is going to be xid, there is a So it will So it will So it will not make any difference if I not make any difference if I take this case here, where in the first indication, take this case here, where in the first indication, where will be the zero from zero max and where will be the zero from zero max and what is the minimum, here it will what is the minimum, here it will reach the next step in this way, then how much will it be reach the next step in this way, then how much will it be if here, it will be zero, but there is already here, it will be zero, but there is already -4 here, the smaller one, so here it will -4 here, the smaller one, so here it will be -4. In this case, because we are be -4. In this case, because we are also looking at N, it is not small in one, but it is also looking at N, it is not small in one, but it is not small, then it is in one. not small, then it is in one. not small, then it is in one. also doing it as per his requirement, then now when these people come here, what will happen here also, 982 is -72, here 94 will be plus, 36 will be the maximum, here this is the maximum and 136 is the zero case. Now I remove it here, there is no need for this one, its condition is not needed here, you can do without it also, so I do not need to put its condition here, directly It will be less, this was the little thing It will be less, this was the little thing It will be less, this was the little thing that I had to cover, so I that I had to cover, so I started the video again and if you started the video again and if you liked the video, please subscribe liked the video, please subscribe [Music] | 2024-03-21 13:14:57 | 152 | Maximum Product Subarray - Dynamic Programming - Leetcode 152 |
|
5OMkd0iikJ0 | hello everyone today we will be going to discuss discuss uh question number three from today's uh question number three from today's bi-weekly contest from lead code bi-weekly contest from lead code uh by weekly contest 32 so the problem uh by weekly contest 32 so the problem we are going to discuss today is minimum we are going to discuss today is minimum insertions to make a parenthesis uh insertions to make a parenthesis uh string balanced so uh what we meant by string balanced so uh what we meant by balance parenthesis in this question is balance parenthesis in this question is uh we have uh we have given a string s and it only consists of given a string s and it only consists of opening and closing parenthesis opening and closing parenthesis so a string is balanced if and only if so a string is balanced if and only if if the opening parenthesis if the opening parenthesis uh comes before the closing parenthesis uh comes before the closing parenthesis and the opening parenthesis is followed and the opening parenthesis is followed by two consecutive closing parenthesis by two consecutive closing parenthesis in generally we have only one in generally we have only one consecutive uh consecutive uh one closing parenthesis but in this case one closing parenthesis but in this case in order to make a balanced in order to make a balanced balanced uh balanced parenthesis string balanced uh balanced parenthesis string we just have we just have to make sure that one opening bracket is to make sure that one opening bracket is one opening parenthesis is followed by one opening parenthesis is followed by two consecutive two consecutive parentheses so here ah but we don't have parentheses so here ah but we don't have to to ah check if the string is balanced or ah check if the string is balanced or not but not but we have to check how many characters we we have to check how many characters we how many minimum number of characters we how many minimum number of characters we need to add need to add in this string such that we in the end in this string such that we in the end the string is the string is a balanced parenthesis for example in a balanced parenthesis for example in this sample input one this sample input one we have this string okay so uh this we have this string okay so uh this i got first opening parenthesis then we i got first opening parenthesis then we have one more opening parenthesis then have one more opening parenthesis then it is followed by two it is followed by two uh closing parenthesis so this string is uh closing parenthesis so this string is balanced balanced but in the end uh this opening but in the end uh this opening parenthesis have only one closing parenthesis have only one closing parenthesis so we need to add one more parenthesis so we need to add one more character that is character that is one more closing parenthesis so that one more closing parenthesis so that this uh whole this uh whole this whole string gets balanced this whole string gets balanced so we just have to output one because we so we just have to output one because we just need to add one more just need to add one more closing parenthesis so here we have closing parenthesis so here we have this string is already balanced because this string is already balanced because this opening parenthesis this opening parenthesis followed by two closing parentheses followed by two closing parentheses that's we output zero that's we output zero so this problem can be solved by using so this problem can be solved by using similar approach similar approach which we used in uh in order to check if which we used in uh in order to check if the string is balanced or not by using the string is balanced or not by using stack stack so but in this case we just have to make so but in this case we just have to make sure and sure and aware of some special cases so we'll be aware of some special cases so we'll be discussing on the discussing on the on while implementing the solution so on while implementing the solution so first we take a stack first we take a stack stack of character st and we trade from stack of character st and we trade from left to right left to right uh in a string okay i is uh in a string okay i is s dot size okay now if s dot size okay now if we have two case if the ith character in we have two case if the ith character in the string is an opening parenthesis the string is an opening parenthesis okay and if the ith character in the okay and if the ith character in the string is a closing parenthesis so if we string is a closing parenthesis so if we got an opening parenthesis we just got an opening parenthesis we just we do just nothing we just push it in we do just nothing we just push it in the stack okay the stack okay push it into the stack so sf5 push it into the stack so sf5 and we just do i plus plus and we just do i plus plus now if we got a closing parenthesis so now if we got a closing parenthesis so if we got a closing parenthesis we can if we got a closing parenthesis we can have two cases have two cases that is if our stack is empty stack is that is if our stack is empty stack is empty empty or if our stack is not empty stack or if our stack is not empty stack is not empty now let's first discuss is not empty now let's first discuss about the case when stack is empty about the case when stack is empty so when stack is empty that means we so when stack is empty that means we don't have any opening don't have any opening parenthesis for this one okay now this parenthesis for this one okay now this can be the k can be the k now and we also have to make sure that now and we also have to make sure that the closing parenthesis we have should the closing parenthesis we have should have have two consecutive closing parentheses that two consecutive closing parentheses that we have to just to check we have to just to check whether the i plus one character is also whether the i plus one character is also a closing parenthesis or not a closing parenthesis or not what if the i plus one character is in what if the i plus one character is in opening parenthesis okay opening parenthesis okay so if our stack is empty so if our stack is empty like if our stack is empty if our stack is empty okay then we have to check for two cases uh that whether our i plus one character is an opening parenthesis or a closing parenthesis if it's in closing parenthesis if our i plus one if a character at i plus one is a closing parenthesis then we just don't have to do anything we just uh count plus plus because we just have to add one opening path one opening parenthesis okay just to make the string balance because we know that we have this string just we have to add one opening parenthesis okay in order to make the string balance and we just do i plus equals to 2 because we just now move at i plus uh third index okay but what if our i plus 1 character is not a closing parenthesis then we have to add count plus equals to 2 and we just do i plus plus because i plus at i because the character at i plus 2 is an opening parenthesis okay this also handles that case whenever i plus 1 character when the position uh but what if the i plus one character is out of bound let's say we have this closing parenthesis then it will be out of bound right so then we have to make sure that i plus one is in the bounds of string okay and if it also handles the case like when we have only one closing parenthesis then we go to the else part and we just add count plus plus and we just count plus equals to 2 and we just add i plus plus so this is all about when stack is empty but what if stack is not empty that means we have uh one opening parenthesis okay that that means we have uh one opening parenthesis just before the closing parenthesis okay so the and now we in this case also we have two cases when i plus one but the character at i plus one character is an uh is a should is closing parenthesis and if it's not so if it is closing parenthesis we just don't have to do anything we just have to do this i plus equals to 2 okay but but if it's not a closing parenthesis then we just have to add a closing parenthesis is here and we just have to do uh i plus plus okay okay and we just have to also make sure that i plus one character is in the uh bounds of the string and if it's not in the bounds of the string then we just have to do it also handle that case two because we just have to do i count plus plus and i plus plus yeah and also make sure that uh uh for when the string when the stack is not empty we just also pop out the last opening parenthesis from the stack so that's it uh we just written in the end answer and okay like count we took count and count equals to zero yeah uh sorry i just forgot one more case where like we don't have any closing parentheses we just have uh like what if in the end we don't have an empty stack like we have we have followed by with couple of opening parenthesis oh all right so here for all opening parenthesis we should add to closing parenthesis so while our stack is not empty while our stack is not empty we just have to pop the stack and we just have to count plus equals to yes so all right 1 0 3 twelve five and let me submit it 1 0 3 twelve five and let me submit it accept it so thanks for watching guys i accept it so thanks for watching guys i hope you got the hope you got the solution of this problem uh see you in solution of this problem uh see you in the next video | 2024-03-21 11:41:57 | 1,541 | LeetCode | Biweekly Contest 32 | Problem: Minimum Insertions to Balance a Parentheses String |
|
4HeIMp1NTOA | Problem is today's problem, you have to solve this fruits in basket so let's solve this fruits in basket so let's get into this problem. So today's problem is that get into this problem. So today's problem is that you have put two food baskets inside it you have put two food baskets inside it and told yourself and told yourself that you have only one fruit in one basket. that you have only one fruit in one basket. Now you have Now you have given yourself many different numbers of fruits given yourself many different numbers of fruits and you have to tell yourself and you have to tell yourself what is your maximum number of what is your maximum number of fruits out of all these fruits. You can put them in both the baskets fruits out of all these fruits. You can put them in both the baskets and tell yourself the maximum number of and tell yourself the maximum number of fruits. fruits. fruits. a small condition of its own in this, that is, if you have started with any fruits, it is if you have started with your first root, now it is not necessary that You You You can also start from the fruit, can also start from the fruit, but if you start from your first route, but if you start from your first route, then you cannot do this. then you cannot do this. Skip the second fruit and come to your third route. Skip the second fruit and come to your third route. If you are If you are starting from any one fruit, then your starting from any one fruit, then your take all the fruits behind it till the last, till then the condition of your basket becomes false. take all the fruits behind it till the last, till then the condition of your basket becomes false. If any If any fruit is skipped, along with it, you have to This is a simple This is a simple This is a simple question, so if you understand this question question, so if you understand this question from this example, then in this example you have from this example, then in this example you have given yourself only two types of fruits given yourself only two types of fruits and you have only two baskets, then and you have only two baskets, then you can take all these fruits in your basket. you can take all these fruits in your basket. And three is your answer to And three is your answer to all the foods you have given yourself. If you all the foods you have given yourself. If you talk about this example, then talk about this example, then in this example you have given yourself three types of in this example you have given yourself three types of fruits, one is zero type fruit and fruits, one is zero type fruit and one is first type fruit. one is first type fruit. one is first type fruit. this is our second type of fruit. We have only two baskets and in each basket we can keep only one type of fruit. So if we keep our type of fruit in one basket and the If you If you If you keep your second type of fruit, then you have keep your second type of fruit, then you have nowhere to go, so you will nowhere to go, so you will not do this. What will you do if you did this? You kept your first type of fruit in one basket and your second type of fruit kept your first type of fruit in one basket and your second type of fruit in another basket. in another basket. in another basket. one fruit, you have kept one fruit once and these two fruits of second type and I have kept both the fruits in one basket, then how many fruits are you taking in total, you are taking three fruits Your answer is, Your answer is, Your answer is, if you look at it from this example, then if you look at it from this example, then in this example too, keep yourself with three types in this example too, keep yourself with three types of fruits, but if you of fruits, but if you start from the beginning, then you will start from the beginning, then you will put the first fruit in one of your baskets and put the put the first fruit in one of your baskets and put the second fruit in one of your baskets. second fruit in one of your baskets. second fruit in one of your baskets. no space left and we no space left and we cannot do this by skipping the third fruit and putting these cannot do this by skipping the third fruit and putting these two fruits back in the second basket two fruits back in the second basket because it is not possible to do this. We have because it is not possible to do this. We have already told ourselves that we already told ourselves that we can start with any fruit but can start with any fruit but After that, you cannot skip any of your fruits. After that, you cannot skip any of your fruits. Okay, so what will you do, you will Okay, so what will you do, you will start with your second fruit, start with your second fruit, put this fruit in the basket, put this fruit in the basket, then put this third fruit then put this third fruit in another basket, and then return to these two. in another basket, and then return to these two. solve all your questions then solve all your questions then solve all your questions then how we will solve this question. To solve this question, I have taken this example. Now what will be our answer in this example? Our answer will be six, three will be our zero-root fruits and three will be our own There will be types of fruits, okay, so There will be types of fruits, okay, so There will be types of fruits, okay, so six should be your answer. If you six should be your answer. If you take this stack of yours, then your answer would be take this stack of yours, then your answer would be five and here you are getting the answer six five and here you are getting the answer six and you want the maximum answer and you want the maximum answer which is your six, okay now. which is your six, okay now. which is your six, okay now. see how you will solve this, then what will you do to solve this, you will travel in your simple map, that is, you will keep putting all the values in the map and whenever the size of your map If If If you come to know that you have three types you come to know that you have three types of fruits, then what will you do? of fruits, then what will you do? In case yours is the first type of fruit In case yours is the first type of fruit or will you make a race with the one that came first, or will you make a race with the one that came first, that you want only two types of that you want only two types of fruits? fruits? fruits? do? First of all, you took this first fruit of zero type, put it in your map and also closed your answer that now you have got a fruit in your answer, then There was only one fruit so There was only one fruit so There was only one fruit so here you made it a plus plus and here you made it a plus plus and in the answer also you made it 2 so that you have in the answer also you made it 2 so that you have got two fruits, then when your third got two fruits, then when your third zero came, here too you made it a plus plus and made it zero came, here too you made it a plus plus and made it three and here also you made a three. three and here also you made a three. three and here also you made a three. I have got three fruits of the same type, now I have adopted them, so what did I do by becoming one and stopped corresponding. In this case too, the size of your map is yours, your two are the same Let's Let's Let's take it and Apna has take it and Apna has also started doing it for the second time. Apna has two types of also started doing it for the second time. Apna has two types of fruits, so as of now Apna does not have any invitation fruits, so as of now Apna does not have any invitation condition, Apna will say that condition, Apna will say that she has got four fruits, three are of she has got four fruits, three are of one type and one is of another type. one type and one is of another type. one type and one is of another type. then similarly it will happen for both of them that there will be three here and you will get six pilot fruits, that means you will get six fruits, one or two, three will be of zero type and three will be of first type, aaya tu to When you expand your map, you will come to When you expand your map, you will come to When you expand your map, you will come to know that the size of your map has been reached, know that the size of your map has been reached, that is, you have got your three types of that is, you have got your three types of fruits, like if your three types fruits, like if your three types of fruits are available, then what will you do to check this, you will get of fruits are available, then what will you do to check this, you will get all the growth type all the growth type fruits in your map. fruits in your map. fruits in your map. your size will return to yours. How many fruits do you have? One, in your map, these three fruits are of first type and this one fruit is of second type, so what will be your answer? Answer is 4 but you have already got answer 6, hence you will not update your answer. Then if this last second type of fruit comes then you will make it a plus and still your answer in this case means this In your condition, my answer In your condition, my answer In your condition, my answer is five and I am already answer 6 of the patient, is five and I am already answer 6 of the patient, hence I will not update my answer. hence I will not update my answer. apneutation is over and we will return whatever our answer is in the last, once we see its code, then once we see its code, then in its code, I have first created a knotted map in its code, I have first created a knotted map inside which I will reduce this one, inside which I will reduce this one, then I have created a great map inside my area. To do this, another answer has been created inside which we will store it manually, then I created it like this, now how I traded like this, let me first explain to you, Han, I have kept the concept of sliding window, If you have taken the numbered fruit, then meaning both of these become zero and plus van's meaning both of these become zero and plus van's Apna means that you have got one of your fruits, Apna means that you have got one of your fruits, then what will you do? Answer, we will get one then what will you do? Answer, we will get one fruit stored. Similarly, then fruit stored. Similarly, then what will happen to Apna? what will happen to Apna? what will happen to Apna? okay then what will happen to you, if the value of I is one, the value of I is zero and in your answer, the fruits will go till here, in your answer, the fruits will go till here, meaning as soon as the value of K meaning as soon as the value of K reaches here, you will be on. what will we do by pressing what will we do by pressing plus icon means we will make zero here, if we remove plus icon means we will make zero here, if we remove those three zero fruits, then one open pressed once, then did it twice and then did it three times. After pressing plus three times, it has come All the All the All the three fruits of zero type have been three fruits of zero type have been done. Now we are seeing here. Okay, done. Now we are seeing here. Okay, so as soon as Apna has so as soon as Apna has reached where it is, Apna Three and Three Six Seven reached where it is, Apna Three and Three Six Seven means it has reached the six position and Apna has reached the means it has reached the six position and Apna has reached the third position. third position. third position. 3 + 1, then what is your answer? What is your answer? Four has come, but you have already got 6 in the answer, so you will not update it, similarly, then you will look here, like this, What What What I did was that I iterated it completely, I did was that I iterated it completely, after that I said that in your map, add plus plus after that I said that in your map, add plus plus to the value and then see that to the value and then see that if the size of your monastery is greater than yours, if the size of your monastery is greater than yours, then what will happen to you, what will you then what will happen to you, what will you do when yours? do when yours? do when yours? is, the first value of your account which was correct in the map, which was the highest value in the map, keep mining his account till it becomes zero and such that his So race it So race it So race it from your map and keep adding plus plus to your i, from your map and keep adding plus plus to your i, then your i will be three times and your then your i will be three times and your i will go here and there, i will go here and there, ok and what will happen to your, ok and what will happen to your, store the maximum value in your answer, answer and store the maximum value in your answer, answer and min's i plus van's. min's i plus van's. min's i plus van's. answer, if you have your answer, then return your answer, then it is absolutely submitted, that means it is an accurate solution, now you can consider it, hope you have understood, if you understood, if you like the video, then like the video. Do subscribe the channel and if you have any doubt then please mention it in the comment box. We are always ready to help you in doubt sales. Thank you | 2024-03-25 10:24:04 | 904 | 904 || Fruit Into Baskets || C++ || Leetcode Daily Challenge |
|
KH3hEFw-CXQ | hello everyone welcome to day 27 of the february decode challenge and the february decode challenge and the question that we have in today's maximum question that we have in today's maximum width of binary tree here in this width of binary tree here in this question we are given a binary tree and question we are given a binary tree and we need to identify the maximum width we need to identify the maximum width that exists among all the levels in this that exists among all the levels in this tree as soon as you read the word levels tree as soon as you read the word levels you should get the hint that bfs you should get the hint that bfs traversal is the way to go and how do traversal is the way to go and how do you define width value width at any you define width value width at any level is defined as the length between level is defined as the length between the end nodes the right most and the the end nodes the right most and the left most non-null nodes left most non-null nodes wherein the null nodes between them are wherein the null nodes between them are counted into the length calculation so counted into the length calculation so remember this definition and let's walk remember this definition and let's walk through a few examples here they have through a few examples here they have provided us with this provided us with this binary tree and the maximum would be binary tree and the maximum would be equal to four how we have five this node equal to four how we have five this node this is the leftmost node this is the this is the leftmost node this is the rightmost node how many nodes are in rightmost node how many nodes are in between them between them one two three four so we have to count one two three four so we have to count the null nodes as well that exists in the null nodes as well that exists in between them between them so the total bits becomes four so the total bits becomes four let's walk through this particular case let's walk through this particular case what is the left most node left most what is the left most node left most what is this right most node is this what is this right most node is this and we need to identify the bits between and we need to identify the bits between them so the maximum bits would be of two them so the maximum bits would be of two units and this is what the answer is units and this is what the answer is let's walk through this particular case let's walk through this particular case here the leftmost node happens to be here the leftmost node happens to be this one however there is no right most this one however there is no right most note to complete it so we have to skip note to complete it so we have to skip this level we will go back to the this level we will go back to the previous level which is three and two previous level which is three and two what is the maximum bits between them it what is the maximum bits between them it is of two units and the answer is two is of two units and the answer is two also i would like to highlight one more also i would like to highlight one more case case which is not that intended from this which is not that intended from this question which is this one question which is this one we have 1 3 2 5 3 6 46 15 we have 1 3 2 5 3 6 46 15 and from the look of it and from the look of it uh what would be the answer uh what would be the answer corresponding to this we have 46 here corresponding to this we have 46 here so we have null and this is the leftmost so we have null and this is the leftmost node 15 is the rightmost node so upfront node 15 is the rightmost node so upfront it may appear to you that the maximum it may appear to you that the maximum would be equal to would be equal to one two one two null here because we have null here null here because we have null here we have three here so we will when both we have three here so we will when both the children are null three four and the children are null three four and five five from the look of it you may feel the from the look of it you may feel the answer should be five however that's not answer should be five however that's not true the answer for this particular case true the answer for this particular case would be 7 would be 7 and this is the most important test case and this is the most important test case which most folks will tend to miss which most folks will tend to miss how will it be 7 i'll explain the how will it be 7 i'll explain the presentation so let's quickly hop on to presentation so let's quickly hop on to it maximum bits of binary tree lead code 662 it's a medium level question on lead code and i totally feel the same so let's go back to the basic example we have a binary tree with two nodes and one is the root of the tree the left child is three the right child is two so what can i do i can assign weights onto this nodes so the root will have zeroth weight the leftmost node will automatically inherit the weight twice the parent node so it would be equal to two times of zero which again makes it zero and the rightmost node will acquire the weight two times the parent plus one so it would give us 2 into 0 plus 1 which is 1. here we did 2 into parent i'll tell you why will this work and how will this work once you have calculated this you will start the bfs iteration level by level and what do you do you will calculate the bits between the leftmost node and the rightmost node it would be equal to the leftmost node weight is zero the rightmost node weight is one so one minus zero plus one would give you the answer which is 2 in sync with our expectation let's proceed ahead let's go and start assigning weights to it we have 0 to the root next we have 3 so 2 into 0 gives us 0 so we'll have 0 here we'll have 2 into 0 plus 1 so we'll have 1 here let's proceed ahead we'll have 0 here 2 into 0 is 0 2 into 0 plus 1 is 1 here we will have 2 into 1 plus 1 because we're moving we are moving in the right direction so this will give us 3 and let's go level by level we will calculate the value for this particular level it will give us 1 minus 0 plus 1 in sync with our expectation the maximum width for this particular level happens to be 2. we did it in the previous section as well with respect to this what is the leftmost node this one what is the rightmost node this one so what would be the value 3 minus 0 plus 1 3 minus 0 plus 1 and this will give us 4. so far the algorithm seems pretty easy and simple and we have appropriately calculated the expected value for width and so once you have calculated these values across levels you can pick up the one which gives you the maximum answer now comes the most interesting case this is a same tree that i showed in the presentation so we have 1 3 2 5 3 6 46 and 15. the answer for this turned out to be 7 as i how let's have a look at it so we have 46 here we have null here we have null here we have null here and what people tend to miss is this null node so we have null here we also have two nulls here which upfront doesn't exist but yes if you think that it's a complete binary tree then it will exist now if you count the number of nodes between 46 and 15 it will turn out to be 1 2 3 4 5 6 7 which is in sync with our expectation the answer should be 7 rather than 5 people tend to miss out on these nodes as a result of which their algorithm will never work this is the most important part of this problem which is not that intended from the description now comes the question our algorithm be appropriately fit into this the answer is yes how let's walk through it let me just change the color of pen and let's get started so we have zero here we are moving towards the left so we'll multiply the parent value weight with two so zero into two is zero here we'll have one zero into two plus one let's proceed ahead next we have five and here the weight would be zero here the weight would be one here the weight would be zero and let's move towards this part of the tree here we are moving towards right so we'll multiply the weight by two and add one to it this gives us three let's proceed ahead since here we are moving towards the left most direction not the right one so we'll multiply the parent weight into two so parent two into parent will give us the weight for this particular node and it turns out to be six now let's use the formula and calculate the width at various levels here the width would be equal to 1 minus 0 plus 1 1 minus 0 plus 1 so one possibility for answer turns out to be 2 absolutely correct here the width would be equal to three minus zero plus one what is the node value here three so three minus zero plus one gives us four so the other possibility counts out to eight to four and here the last possibility would be equal to six minus zero plus one which is seven and the maximum width that you were able to identify turns out to be seven and this becomes the answer to conclude it further let's quickly have a look at the coding section here i've taken a max fit variable here i have taken the map and the key would be the tree node and the value would be the way that we have allocated to it so this is node and i have declared as a hash map i have and i have declared as a hash map i have put the value for the root as zero and i put the value for the root as zero and i start the bfs reversal i add the root start the bfs reversal i add the root into the queue while my queue is not into the queue while my queue is not empty i calculate the size i calculate empty i calculate the size i calculate the weight associated with my the weight associated with my left most um node in my map left most um node in my map and i use q dot peak for finding out the and i use q dot peak for finding out the left most node corresponding to a left most node corresponding to a particular level this is slightly particular level this is slightly different and unusual but that that we different and unusual but that that we we usually don't peek out elements up we usually don't peek out elements up front from a particular level but if you front from a particular level but if you carefully visualize this will give you carefully visualize this will give you the left most weight value associated the left most weight value associated with the leftmost node with the leftmost node while size minus minus is greater than 0 while size minus minus is greater than 0 i pull out the head value i calculate i pull out the head value i calculate the current width the current would be the current width the current would be equal to map dot get head minus left equal to map dot get head minus left plus 1 and i compare it with the maximum plus 1 and i compare it with the maximum width variable that i have already width variable that i have already calculated calculated if moving ahead if my if moving ahead if my map dot head is not null i what do i do map dot head is not null i what do i do i add it to my queue and i update the i add it to my queue and i update the weight associated with my weight associated with my head dot left node head dot left node that is equal to 2 into map.head that is equal to 2 into map.head map dot get head this is important and map dot get head this is important and in case my right is also not null i add in case my right is also not null i add it to my queue and it to my queue and update my map with update my map with write dot head node comma 2 into the write dot head node comma 2 into the parent's parent's weight value plus one so two into weight value plus one so two into parent's weight value plus one here we parent's weight value plus one here we simply use two into parent's weight simply use two into parent's weight value once i'm done with this i simply value once i'm done with this i simply return the maximum weight that i have return the maximum weight that i have calculated so far awesome uh it is six seven times better there can be slight improvement done uh over here but i think it's fine if you are able to come up with this kind of an approach in an interview this brings me to the end of today's session if you are interested in more tree playlist then i am attaching the link in the description below do give it a shot and also don't forget to like share and subscribe to the channel for more updates from coding decoded thank | 2024-03-22 16:10:52 | 847 | Maximum Width of Binary Tree | Leetcode 847 | BFS | Live coding session 🔥🔥 |
|
5G7jNmqGUck | hi guys welcome to one more video in this video we'll take a look at in this video we'll take a look at convert sorted array to binary search convert sorted array to binary search free difficulty level is easy free difficulty level is easy so the problem title itself gives out so the problem title itself gives out that we would be given a sorted array that we would be given a sorted array and then we need to convert it to a and then we need to convert it to a binary search tree so it's kind of a d binary search tree so it's kind of a d serialized operation like we're given an serialized operation like we're given an array or string and we need to array or string and we need to deserialize it to binary deserialize it to binary so that's the problem statement however so that's the problem statement however there are two important things first of there are two important things first of all it's a binary search tree so what is all it's a binary search tree so what is a binary search tree so binary search a binary search tree so binary search tree is a binary tree where tree is a binary tree where root node is always greater than the root node is always greater than the right i mean left child so root is right i mean left child so root is greater than the left hand left child is greater than the left hand left child is smaller than the root and right child is smaller than the root and right child is always greater than root always greater than root so so root is kind of middle root is kind of middle left child is smaller and right child is left child is smaller and right child is bigger so that's a binary search tree bigger so that's a binary search tree and what we need to make sure it's that and what we need to make sure it's that it's a height balance minor tree so what it's a height balance minor tree so what is height balance monitoring means so is height balance monitoring means so height balance tree means that height balance tree means that the height difference between the the height difference between the complete lift or complete left tree and complete lift or complete left tree and complete right tree cannot be greater complete right tree cannot be greater than one so if the depth of than one so if the depth of left tree is let's say five left tree is let's say five then depth of right tree can be either then depth of right tree can be either four or six or five it cannot four or six or five it cannot it can differ but not more than one so it can differ but not more than one so that's height balance tree so that's height balance tree so that's the problem uh we have couple of that's the problem uh we have couple of examples we'll examples we'll do those examples on the whiteboard and do those examples on the whiteboard and we'll understand how we can solve it and we'll understand how we can solve it and then come back and run the code okay okay so this is our array we'll take our array as minus three to three and we'll try to convert it into a binary search tree which is also height balance and this is our complete code so this is a recursive function and all we are doing is we are splitting the array into two half so what we do so we have all the elements in the array we take a middle element and we put that as our node and everything left from that node or the middle element is part of the left tree and everything right from that middle is part of the right tree and we just keep we recursively keep doing that until all the elements are done and we get our tree so let's see how will our draw out or how the tree will become so what we do is let's say our this is our array so from zeroth element sixth element right and when we do middle so obviously zero is our middle element so that's our first node and what we do we say this is our left tree and this is our right tree now we recursively call those uh as left node and right node with low and mid minus one and mid plus one and high so this is our left tree this is our right tree now let's do the left tree first okay so now this becomes our array right minus 3 minus 2 minus 1 and what we do we repeat the process take the middle number minus 2 and then this is the left tree this is the right tree so this will come out as minus 3 and minus -1 and that's the left tree now left part is done now let's move on to the right part we'll follow the same process we'll take out the middle element which is two this is the left tree this is the right tree so this is the left tree this is the right tree there you go so we have our binary search fee which is also height balance so simple process to make our binary search free from and sorted array so let's take one more example let's take a bit bigger array and let's see how the uh how our binary search tree looks like in that case okay so this is our second example we just added two more elements to our previous array we added minus four and four so a little bit larger array not that pretty large but still so let's try to draw the tree from this array using this logic so what we'll do is we'll pick the middle element and then we'll say this is your left tree and then this is your right tree right same process so we'll have zero as our node and then left tree and then right tree right so let's first do the left tree so now in this one our middle would be again minus 3 so minus 3 would be the root and then this would be the left tree right now over here what will the middle in two elements so minus 2 would be the middle there's no left there's only right so minus one would be the right node and likewise same here in this array the middle would be two and left tree would be one right tree right so in three four three would be the middle element root and then four would be the right shadow right there's no left child so there you go guys if you look here the height difference between these this left tree and this right tree there is only one and likewise height difference between this left tree and this right tree is one so it's height balance also it's binary search free and that's what the question needs so there you go guys uh i'll spare you from looking at my code which is like written with a very bad handwriting let's go to the vs code where the code is nicely indented consistent fonts and everything so let's do that okay guys this is our final code so we have our main method in which we are taking those two examples of array and then we are passing it to sorted array to bst method now this method in turn calls that make bst right and in make bst what we do is what we discuss on the whiteboard right take the array find the middle element and then middle element becomes a node and then left child of that node is the complete left part of the array and right child of that node is complete right part of the array i figured out left right for you guys so anyway guys uh i don't have uh i haven't written any way to like print array or print the tree so we just have to run it and assume that uh it does what it's supposed to do so i'm sure you guys believe me so so there you go guys the code is there uh i'll put the link to the code in the description and if you guys like the video give me a big thumbs up let me know your feedback and suggestion in the comments uh this is not the only way to do it there are multiple ways but this is the way i found it which is more logical so if you guys have a better way let me know and then as usual subscribe to the channel | 2024-03-21 10:29:43 | 108 | Convert sorted array to binary search tree | LeetCode 108 | Easy |
|
xmJZSYSvgfE | problem is called a gas station problem and it has been asked quite a few times and it has been asked quite a few times in in amazon google microsoft uber and apple amazon google microsoft uber and apple interviews interviews so let's see what is this problem so in so let's see what is this problem so in this problem you have a few gas stations this problem you have a few gas stations so this array or list of so this array or list of gas denotes the different gas stations gas denotes the different gas stations so gas station 0 so gas station 0 1 2 3 4. so let's draw them here 1 2 3 4. so let's draw them here so you have to think that they are in a so you have to think that they are in a circle circle so you visit these gas stations in a so you visit these gas stations in a circular fashion circular fashion and you can start from any of those so and you can start from any of those so let's say this is zero let's say this is zero this is one this is two this is one this is two this is three and this is four these are this is three and this is four these are the five gas stations the five gas stations and these are different capacities which and these are different capacities which you can fill your you can fill your car with so when you go to gas station 0 car with so when you go to gas station 0 you can take one unit of you can take one unit of fuel from this and this cost fuel from this and this cost which is of same size as this denotes which is of same size as this denotes that that cost 0 will denote that you need at cost 0 will denote that you need at least least 3 units of fuel fuel to go to next 3 units of fuel fuel to go to next station that is if you are at 0 next station that is if you are at 0 next would be 1 would be 1 so you have to go in this clockwise fashion so you need three units to go from zero to one so let's say you start from zero so you can fill with your car with one unit of fuel but you need three units to go to one so you cannot do that so initially your car is empty the tank of your car is empty so you will this is not possible you cannot start from here similarly when you start from here you will fill it with two units so you have two units of fuel but at one you need four units to go to two so again you cannot make this trip so you will also not start from here gas i should be greater than gas i should be greater than or equal to cost i in order to start or equal to cost i in order to start from there from there so we can think of this as a difference so we can think of this as a difference or surplus so let's or surplus so let's call it delta call it delta gas i minus cost i this should be gas i minus cost i this should be positive in order to start positive in order to start so till you are getting negative you so till you are getting negative you cannot start now here look at this gas you can fill is 3 but you need 5 again not possible here you can fill your tank with four units of fuel and you need just one unit to go from three to four so you will you can start from here you will start or not will depend on the future values but here you can definitely start since here you will have surplus so here we filled with plus four unit then we came here we lost one unit because we need one unit so minus one now we have a surplus of three at 4 we can fill another 5 so 3 plus 5 8 now we have 8 and we come here and we lose 2 units of fuel so now we have 6 here so we fill with one so seven we consume three when going here so minus three so now we have four and we fill with two so six then we consume four units so minus 4 now we have 2 here and we fill with 3 so 5 and when going from here to here we need 5 units so minus 5 and now it becomes 0. so we have completed a trip we started from here and we reached here so this is what we are required to answer here so which what should be the starting index so in this case the answer should be 3 because we can start from here and reach a round trip and another thing to note is that let's say the cost is the total cost is more than total gas available then definitely you cannot make any trip no matter where you start uh because let's say you have cost is 50 units of fuel and total available fuel is just 45 units then no matter where you start you cannot complete the trip so this is another point this total should be always more than this or that is total delta sum of deltas should be positive or 0 greater than equal to 0 in this case it was exactly 0 so that was good enough now is the problem for finding the starting point so you can also draw this circle here 0 1 2 3 and 4 so you start in this direction and then go back to 0 so let's see how we will find the starting point so let's take a general example and i will draw just one point let's and i will draw just one point let's merge these two into one merge these two into one this cost and gas with this delta that this cost and gas with this delta that is gas minus cost is gas minus cost so it should be if it's greater than so it should be if it's greater than equal to 0 equal to 0 at a given point we can start from there so what we will do we will keep track of two variables we also need this total maybe you started from here and reached here but overall total was less than zero this total delta then we cannot complete the journey so we keep track of two variables total and current delta and current delta so let's say it's negative here negative so let's say it's negative here negative negative negative so you start from here you see it's so you start from here you see it's negative negative so you come here you reset everything to so you come here you reset everything to zero zero so initially it's zero both are zero we so initially it's zero both are zero we have not started yet have not started yet so when it's negative let's say it's so when it's negative let's say it's negative a negative b then it's plus c so this will keep incrementing you will keep accumulating this is nothing but accumulator and in the end we will just use it to check if it's less than zero or not if it's less than zero we will straight away return false otherwise we will return the starting point so you can even forget this for now this is just accumulated no other purpose so we come here we check what is current delta so current delta will be current delta plus this value let's call it so this is nothing but gas i minus cost i so this is the delta so we are adding so initially it was zero now it becomes if it's negative then it's minus so if it's negative we will not start journey from here or whatever was our previous starting point so we started from some point and we moved to some points and we reached here and now it has become negative that means this starting point was invalid because when we start from here now once we reach here it's negative so it was false it was the wrong starting point we cannot complete the journey so what can be the next starting point after this why not here or here let's see let's see we started from here and this point was positive this delta was positive that's why we started otherwise we cannot even start next let's say it was also positive so you you'd say that why you reset the starting point only when the current running delta becomes negative why not try from this point also this is also positive we don't try from this point because when we started from this point this is the starting point so our fuel this is the starting point so our fuel was was zero so it was exactly zero when we came zero so it was exactly zero when we came here here and we loaded our tank with this fuel and we loaded our tank with this fuel so when we go from here to here so when we go from here to here we already have something positive if if we already have something positive if if it becomes negative we are resetting it it becomes negative we are resetting it anyway anyway so we are not resetting it that means we so we are not resetting it that means we reached with some positive capacity reached with some positive capacity or in the worst case may be 0 not less or in the worst case may be 0 not less than 0. than 0. so we reached with some positive so we reached with some positive capacity so obviously this point is capacity so obviously this point is better better because if you start from here you reach because if you start from here you reach this point with some positive delta and this point with some positive delta and then you will then you will add this value also the tank the fuel add this value also the tank the fuel capacity at this station capacity at this station so total will be more so you have this so total will be more so you have this fuel capacity gas fuel capacity gas i this you will load i this you will load and you already reach with this positive and you already reach with this positive delta so now it will become plus delta delta so now it will become plus delta but if you start from here its value but if you start from here its value will be just gi will be just gi so it's always better to start from here so it's always better to start from here so that's why so that's why starting from any of these intermediate starting from any of these intermediate points will not be points will not be better than this one so we will start better than this one so we will start from here from here and when we the running delta becomes and when we the running delta becomes negative negative then we know that the starting point was then we know that the starting point was invalid and invalid and if starting from here we reach a if starting from here we reach a negative value negative value then starting from here also we will then starting from here also we will reach negative when we reach here reach negative when we reach here because when we start from here our tank because when we start from here our tank will have even less value will have even less value gi when we start from here our tank had gi when we start from here our tank had gi plus delta gi plus delta so gi plus delta becomes negative that so gi plus delta becomes negative that means gi will also become negative means gi will also become negative so this was the best starting point that so this was the best starting point that we chose and still we got negative we chose and still we got negative so this was invalid so next starting so this was invalid so next starting point will be 1 after this point will be 1 after this because this was negative anyway that's because this was negative anyway that's why the overall become negative why the overall become negative so next we will start from here and so next we will start from here and again the same logic again the same logic if it's remaining positive we will if it's remaining positive we will continue if at any point of time it continue if at any point of time it becomes negative becomes negative then we start from here and when we then we start from here and when we reach the reach the end and the value is greater than equal end and the value is greater than equal to 0 to 0 then we know that from this starting then we know that from this starting point point s we have reached here s we have reached here with some positive capacity left with some positive capacity left then we check if the total delta is then we check if the total delta is greater than 0 or not greater than 0 or not so if it's less than 0 no point in so if it's less than 0 no point in checking further return false total is checking further return false total is less than 0 no less than 0 no there is no way we can reach but if this there is no way we can reach but if this total is greater than 0 or equal to 0 total is greater than 0 or equal to 0 then return this starting point this then return this starting point this will be a valid starting point will be a valid starting point now in this problem we now in this problem we have seen that from here when we started have seen that from here when we started from here we did not from here we did not face any such situation where it became face any such situation where it became negative otherwise we would have reset negative otherwise we would have reset it it we did not reset till the end that means we did not reset till the end that means from here we have reached still here from here we have reached still here now our only concern is that we have to now our only concern is that we have to prove that prove that with whatever capacity we have here with whatever capacity we have here delta we can reach delta we can reach from this 0 till this node and if we can from this 0 till this node and if we can prove that we are done prove that we are done so this is now guaranteed that t delta so this is now guaranteed that t delta is greater than zero is greater than zero otherwise we we will return false so otherwise we we will return false so so now we have these things so we have this is the starting point from there when we started we reached end point so let's call it n for nth point and this is zero starting point and this is the last starting point that did not violate anything and we still end so reaching from here to here is valid we have seen and total delta is greater than zero or greater than equal to zero 0 now we have to prove that we can reach from 0 to s in this round trip so after this we go here so at nth point we added the capacity of g n minus 1 and subtracted cost n minus 1 and if it's positive that means we can go to 0. so from s we can so we are here at 0. so here we will so we are here at 0. so here we will again add again add the cost for 0 plus g 0 and subtract the cost for 0 plus g 0 and subtract cost 0. so we have to prove that from 0 cost 0. so we have to prove that from 0 we can reach we can reach s with this surplus s with this surplus plus delta we reached here with plus plus delta we reached here with plus delta delta so let's say uh we cannot reach so let's say uh we cannot reach from 0 to s let's prove it by from 0 to s let's prove it by contradiction so let's say contradiction so let's say from s to n we successfully came then from s to n we successfully came then from n we go to zero because it was from n we go to zero because it was greater than equal to zero greater than equal to zero this difference now from zero we started this difference now from zero we started moving at some direction moving at some direction at next gas stations at next gas stations and somewhere at this gas station let's and somewhere at this gas station let's say point p say point p it became negative so if we face such it became negative so if we face such situation situation then we will say that we cannot complete then we will say that we cannot complete the trip when we start from s the trip when we start from s but we have to prove that such point but we have to prove that such point will not exist if will not exist if total delta was greater than equal to 0 total delta was greater than equal to 0 this thing so let's assume that there is this thing so let's assume that there is such point where it's negative then what such point where it's negative then what is the condition for this to be negative is the condition for this to be negative we started from here we started from here when our capacity was 0 so this point when our capacity was 0 so this point let's call it let's call it x this part and let's call it this part x this part and let's call it this part as as y and this part as z y and this part as z so x plus y plus z will be this total so x plus y plus z will be this total delta delta so this we know that is greater than so this we know that is greater than equal to zero equal to zero this is equation one this is same as this is equation one this is same as this variable that we this variable that we were keeping track of here cumulative sum so this is greater than equal to zero otherwise we would have returned earlier only so this is first equation next we stop here that is from s we cannot go past five we go past p so what this means this part is x and this part is y so that means this is less than zero that's why we have got a overall negative when we reach here we started with 0 now it's negative so this x plus y is negative this is second so x plus y is negative okay this is negative and this complete thing is positive now if z is positive from this first and now if z is positive from this first and second equation if we combine this second equation if we combine this clearly z has to be positive then only clearly z has to be positive then only this negative this negative plus some positive will make it positive plus some positive will make it positive so if z so if z is positive we would have started before is positive we would have started before only only not s why because uh we had not s why because uh we had some positive values let's break the z some positive values let's break the z this is z this is z we are looking at z so z will have some we are looking at z so z will have some positive some negative some positive positive some negative some positive we are merging positives together so we are merging positives together so this if we have plus plus plus this if we have plus plus plus then we would take it as one plus so it then we would take it as one plus so it would have different would have different regions of positive and negative and regions of positive and negative and this overall is positive this overall is positive we are in the contradiction part only so we are in the contradiction part only so if if let's say this part so if this positive let's say this part so if this positive was was more than negative that is this much more than negative that is this much positive and this much negative so this positive is more so if we start from here when we reach here we will still have some positive left and then this positive again will add to it so we will have even more positive and we know that it's positive so we will successfully cross this so we would have never reached negative here we started from here because just before it it was negative so in that case we would have started from p only so this is the first case where this positive was more now let's say this positive is less negative was more then what will happen we start from here when we reach here overall it's negative so we would have started from here so this part is now negative overall sum this plus let's say plus 2 minus 4 so this overall becomes negative so now it becomes minus plus minus so we would have started from here and we had said that this complete thing is positive so this thing also will be positive so again by the same logic if you start from here you would cross this with positive since the total is positive so that contradicts that jet cannot be greater than zero so z will be less than zero now we arrive at a contradiction from one and two if such point p exists then from one and two this z has to be positive but we have shown that z will be negative that's why we started from here so we arrive at a contradiction and such point p will not exist at all so what will be our strategy what we had done we started from here we kept two variables one is for running delta or surplus other is cumulative this cumulative is not used anywhere it's used just when we complete this iteration we check if cumulative is negative return false else return the last starting point and we started from here and we at every point we added this value to both the current delta and total delta and at any point of time if current delta is negative then we reset it because our starting point was wrong so we start from next point so that's why we reset and finally when it's greater than zero then we return the starting point so let's write the code for this understanding is this is more tough writing the code is very simple and in this problem it's given that it's and in this problem it's given that it's a unique solution but that does not make a unique solution but that does not make a difference we are already picking the a difference we are already picking the best starting point possible so even if best starting point possible so even if it's not unique it's not unique we would return a valid starting point both sizes are equal you can pick any of total surplus it's not the total fuel total fuel will be the sum of all values here and we are subtracting total cost so total surplus and current surplus and current surplus or just right surplus equal to zero or just right surplus equal to zero next uh starting point let's denote my next uh starting point let's denote my capital s capital s is zero this is the first starting point gas i minus cost i and the same thing so if surplus so if surplus becomes negative then the starting point becomes negative then the starting point was wrong so we reset it was wrong so we reset it and starting point s becomes next point and starting point s becomes next point because this current point is a big because this current point is a big negative that's why the total negative that's why the total became negative or related was positive became negative or related was positive and when this loop ends we will check if and when this loop ends we will check if [Music] [Music] this total surplus is negative then return uh minus one so if the solution does not exist you have to return minus one otherwise otherwise the actual index so we can combine it into one return with this statement ternary operator then return -1 else or return the starting point so this answer is correct so this answer is correct and the solution is accepted so now what and the solution is accepted so now what is the time complexity of this is the time complexity of this solution we are just iterating through solution we are just iterating through this this array both are same size and we are array both are same size and we are traversing from left to right traversing from left to right so this is o of n so time complexity is so this is o of n so time complexity is o of n and space we are just keeping a few variables like total surplus surplus and starting point so space complexities of one now let's write the same thing in java and the solution is accepted in java and the solution is accepted in java also finally python so else 7 else 7 else s | 2024-03-21 12:02:53 | 134 | Gas Station | LeetCode 134 | C++, Java, Python |
|
K8bmvM2_ZZQ | on everyone so today we are looking at lead code lead code number 15. it's a question called number 15. it's a question called threesome threesome okay so this is a very popular question okay so this is a very popular question it builds off of it builds off of its predecessor which is a is leak code its predecessor which is a is leak code number one number one which is twosome also extremely popular which is twosome also extremely popular and we're going to look at three and we're going to look at three different ways we can approach this different ways we can approach this we'll look at a brute force we'll look at a brute force strategy and then we'll look at a more strategy and then we'll look at a more efficient strategy on approaching this efficient strategy on approaching this and we can see here that this is very and we can see here that this is very frequently asked frequently asked amazon facebook in the last six months amazon facebook in the last six months it's one of the most frequently asked it's one of the most frequently asked types of questions two sum types of questions two sum and threesomes so it's good to be and threesomes so it's good to be familiar with this pattern and familiar with this pattern and understand understand how to solve this and the drawbacks and how to solve this and the drawbacks and the different strategies to approach the different strategies to approach this particular problem okay so let's this particular problem okay so let's take a look at the prompt take a look at the prompt given an integer array nums return all given an integer array nums return all triplets triplets num of i num of j num of k such that i num of i num of j num of k such that i does not equal does not equal j i does not equal k and j does not j i does not equal k and j does not equal k and nums of i equal k and nums of i plus numbers of j plus nums of k is plus numbers of j plus nums of k is going to equal going to equal zero notice that the solution must not zero notice that the solution must not contain contain duplicate triplets so here we have duplicate triplets so here we have an input of minus one zero one two an input of minus one zero one two minus one and four and we have minus one and four and we have our triplets of minus one minus one and our triplets of minus one minus one and 2 and minus 2 and minus 1 0 and 1. 1 0 and 1. empty array is going to return an empty empty array is going to return an empty array and array and nums of 0 is also going to return an nums of 0 is also going to return an empty array empty array okay so let's take a look at different okay so let's take a look at different ways we can approach this let's see this ways we can approach this let's see this input is minus one input is minus one zero one two zero one two so we're gonna have minus one uh let's see here what was it minus one zero one two minus one and minus four zero one two minus one and minus four let's just double check make sure that's right zero one two minus one minus four okay so what we wanna do now we can do this in a brute force way with just three for loops okay i'll quickly quickly kind of go over that strategy here let's say we have an index i an index j and an index k right and we can just check does this equal zero do the three values that these indices equal zero this one it does so what we're going to do is just put this in a result we'll go ahead and put in -1 0 and 1 and then move the move the k-th into c forward so does this equal 0 no it does not does this equal 0 no it does not does this equal 0 no it does not and then what we do is we go back and we increment our j index whoops okay we'll go ahead and increment j and then just rinse and repeat all right so now j will be over here k will be over here k will increment k will increment and we'll go and find all the all the combinations of three values that equal zero now we may get duplicates so what we could do is we could create a hash set the value convert the arrays stringify them set them as the keys and then make sure that and pull out the duplicates make sure there's no duplicates okay so that's one way we could go about this what would be the performance on that let's kind of analyze that okay let me clear this out here so if we're doing three for loops what are we gonna have to do space or time wise well it's going to be o of n cubed on time okay if we use the hash method to remove the duplicates it's going to be o of n space but we might be able to figure out a way uh to check if we've been there before and we might be able to get this in constant space we actually should be able to get that in constant space but the time would be really bad we're going to get o of n cube time actually we would not have constant space we've got o of n space because we're going to have to return all the all the triplets which could be worst case the size of the input okay so not really not really that great now if you're familiar with the problem twosome we can use a modified approach that we used in two sum okay so what if we use a three point our okay so what if we use a three point our approach here approach here okay so we have um i okay so we have um i j and k but we we do it a little bit j and k but we we do it a little bit differently differently so let's say we have the ith index here so let's say we have the ith index here we're going to start with i we're going to start with i as our first our first value as our first our first value and we're going to we're going to uh and we're going to we're going to uh flip the operator so we're going to flip flip the operator so we're going to flip it if it's negative we'll make it it if it's negative we'll make it positive it's positive we'll make it positive it's positive we'll make it negative so let's just say negative so let's just say target is going to equal and we'll call this okay so we're going to do nums of i times -1 and all that's going to do is just negate it so if we have one it's going to turn it into one and now all we have to do is in this portion of the array the rest of the array we can just run our regular twosum strategy and see if the target if it equals a target if it equals a target we just go ahead and flip that sign again and take the two values that equal that target package it into a sub result and then pass that push that into a final result okay so let's let's kind of just walk through that i know that's a lot to take in but let's just kind of walk through what we're going to do and also if we're going to take this approach we're going to have to sort this input array okay so we have to sort it if we're going to use that two-pointer approach so let's just go ahead and do that let let's go ahead and clear this out let's go ahead and clear this out and take a look at those inputs again we and take a look at those inputs again we have the input of have the input of minus one zero one two minus one zero one minus one and minus four okay so the first thing we wanna do with this nums here okay and when we sort this what's our okay and when we sort this what's our cost cost going to be it's going to be and time going to be it's going to be and time complexity it's going to be an complexity it's going to be an n log n cost n log n cost that we're gonna have to do for this okay so now that we have sorted this let's go ahead and look at what this looks like sorted we're going to have minus four minus one minus one zero one and two okay so we have just we've taken that input array and we have sorted it now what we're gonna do is we're gonna we're gonna basically run through this run through this array iterate through this array but at every iteration the rest of the array we're gonna run two sum on okay so i'll just kind of step through that so here we have i and now we're going to go ahead and take everything from this index here the i plus one index which is where i'll set j and the end of the array which is where k will be and now j and k are going to act like two sum with the target being the value at i with a flipped uh flipped operator like a flipped symbol so if it's positive it's going to be negative negative it's going to be positive because we want the target to be zero so let's just go ahead and walk through that okay and from our sorted numbs array okay and from our sorted numbs array we're going to go ahead and take the i we're going to go ahead and take the i element so nums at index i and we're just going to multiply it by -1 to flip the symbol on it now what we're going to do is we're going to run two sum on the rest of the array on the j and k so we're going to say okay does j plus k equal the target which is four okay the target is going to be four in this case uh no it doesn't okay and is if it doesn't then is it greater than is the combination of j and k is it greater than four no it's not if it's not greater than 4 then we're going to increment the jth element okay here we're going to do the same thing is the is the target which is 4 is the sum of the value at j and the value at k the sum of those two does it equal uh does it equal four no it does not is it greater than four no it's not it's less than four if it's less than four we're going to go ahead and increment j we're going to increment j all the way until we get to our base case uh where j has to be lower than k we break out of that all right so let's just go ahead and all right so let's just go ahead and remove all this remove all this now what we're going to do is go back to now what we're going to do is go back to our main loop our main loop and we're going to go ahead and and we're going to go ahead and increment our i okay so now i is going to increment here and we're going to have j and we're going to have k and now we have to check does we're going to flip the target so the target now is 1 minus 1. we're going to go ahead and flip that so it's going to be 1. and now we check does the sum of the j-th value and the k-th value equal 1 yes it does okay because 2 plus -1 is um is one okay or one minus two is is one okay so now what we're going to do is we're gonna go ahead and re-flip that we're gonna go ahead and re-flip that target so we'll go ahead and put that target so we'll go ahead and put that back to -1 back to -1 and we're going to add the value of j and we're going to add the value of j and add the value at k okay the sum of all three of those equals zero increment and decrement k and we check increment and decrement k and we check does that equal does that equal does that equal our target which is which is one okay so the sum of one zero and equals one and that does equal our target so now we're going to do the same thing we're gonna flip our target which is going to be -1 and we're going to add okay and now we decrement k okay and now we decrement k and increment j and we're going to see and increment j and we're going to see we're out of range we're out of range and we move on so that's the basic idea and we move on so that's the basic idea now there is a bug with this approach now there is a bug with this approach there is an edge case here in the edge there is an edge case here in the edge cases the solution set cases the solution set must not contain duplicate triplets must not contain duplicate triplets okay so that that's a that's a tricky okay so that that's a that's a tricky edge case here edge case here where let's take in another example and if this this solution right here is not clear i suggest just stepping through it just writing out the numbers and stepping through it so it becomes clear or if you're not clear with how how we're kind of working this part of the solution i suggest reviewing twosome reviewing the solution for twosome okay so now let's say we have an input we have an edge case here where the numbers are where the numbers are minus two zero 0 minus two zero 0 2 and 2. 2 and 2. okay and so what's going to happen here okay and so what's going to happen here is let's say we use that approach this is let's say we use that approach this is already sorted but is already sorted but let's just say we use that approach we let's just say we use that approach we used before we have the ith variable used before we have the ith variable here here we have j here and we have k here well we have j here and we have k here well this is going to equal this is going to equal zero so we're going to get minus two zero so we're going to get minus two zero zero and two but now when we decrement j and and two but now when we decrement j and uh uh or when we increment j and uh uh or when we increment j and decrement k decrement k we're going to see it's the same numbers we're going to see it's the same numbers and now we're going to get and now we're going to get a repeat we're going to get a duplicate a repeat we're going to get a duplicate which is not what we want okay so what we need to do we need to do three things okay we're going to have an outer loop and then we're going to have an inner loop where we're basically performing two sum and we'll do we'll use a helper function to accomplish that but what we want to do is first you want to check if we have if the ith variable and the previous one i minus 1 if these are the same okay then we just want to move we want to move i forward we don't want to deal with any duplicates okay so that's what we want to do in the outer loop we want to first check have we already checked this number okay so if i increment and the previous number is the same number as the current number then we just want to increment even further we want to get out of any duplicates so that's what we want to handle on the outer loop on the inner loop what do we want to do what we want to do on the interlap is what we want to do on the interlap is the inner loop is the same thing we want the inner loop is the same thing we want to to handle any duplicates and the way we do handle any duplicates and the way we do that that is let's say we have our ith variable is let's say we have our ith variable here here our jth variable here and our kth our jth variable here and our kth variable here and we have gotten variable here and we have gotten our first result here subresult now we our first result here subresult now we go ahead and go ahead and increment j and decrement k increment j and decrement k and what we need to check is while k is equal to its uh previous element so k plus one so while these are equal we need to just keep on decrementing k and similarly while j is equal to its previous element j minus one we need to keep on incrementing j and if it gets out of the range we just break out of there okay and that will guarantee that we don't go and get uh we don't have duplicates that we're only seeing each triplet once all right so let's just quickly talk about time and space complexity so what is our time complexity well we have an outer loop that we're running okay so that's n and then we have our inner loop which is also a linear operation okay so our time complexity here is o of n squared okay we do have we do have the sorting but because we have we're gonna then run an outer loop and then we have to run an inner loop we're running two sum again this is gonna be at o of n squared and our space complexity here okay we're going to have to create okay we're going to have to create relative amount of space relative amount of space relative to the size of the input but relative to the size of the input but it'll never be bigger than the size of it'll never be bigger than the size of the input okay so let's go ahead and all right so first what do we want to do all right so first what do we want to do first we want to sort first we want to sort the input array so we can just do a the input array so we can just do a nums.sort okay so that will sort it and then we want to go ahead and have an uh outer result now what we're going to do is we're now what we're going to do is we're going to iterate over our nums so we're going to iterate over our nums so we're gonna do four gonna do four let i equals zero i is less than nums let i equals zero i is less than nums dot length dot length you can do a micro optimization and do you can do a micro optimization and do i've nums dot length minus two but i've nums dot length minus two but either way works we can do an i plus either way works we can do an i plus plus here plus here and now what we want to do is we just and now what we want to do is we just want to make sure that if we're at the want to make sure that if we're at the i-th i-th element the previous element was not the element the previous element was not the same if it was the same then we just same if it was the same then we just want to continue want to continue and this is just so we can avoid and this is just so we can avoid duplicates so if duplicates so if nums at i equals nums at i equals nums at i minus 1 okay now what do we want to do next okay now what do we want to do next now we have to get the target right we now we have to get the target right we have to create the target variable have to create the target variable and that's going to be whatever is at and that's going to be whatever is at our num our num nums i index we want to flip the sign nums i index we want to flip the sign so we can say let target so we can say let target equal nums of i equal nums of i times minus 1. that'll just flip the times minus 1. that'll just flip the sign on whatever that value is sign on whatever that value is okay now we're going to use a helper okay now we're going to use a helper function method here so we can just say function method here so we can just say let sub result is going to equal two sum and we are going to have a start a target and our nums array so now our start is just going to be i plus 1 okay because we're going to use two pointers here so we want to make sure that our j is starting at i plus one and the k at the element will always be at the end it'll be the last element all right now once we get our sub result all right now once we get our sub result we just want to push that into our we just want to push that into our result result so we'll just do a result.push and we so we'll just do a result.push and we want to use the spread operator here want to use the spread operator here and uh use that for our sub result and uh use that for our sub result and you'll see why when when we when we and you'll see why when when we when we create the helper function because we're create the helper function because we're going to have a nested going to have a nested array of all the results from the two array of all the results from the two sum helper function sum helper function when we push that into our final result when we push that into our final result we want to make sure we spread it all we want to make sure we spread it all out so then we don't have a bunch of out so then we don't have a bunch of nested arrays okay and then we're just going to return so now let's go ahead and uh create our so now let's go ahead and uh create our helper function okay and this is going to take in a um we can actually just call this um we can actually just call this j a target okay and now we can go ahead and create okay and now we can go ahead and create our k let k our k let k equal nums dot length minus one array okay so now what do we want to do want to follow that same pattern that we did for before two sum and here what we're gonna do is say okay what do we want to do okay what do we want to do we want to check do we have we want to check do we have a target so let's first get the values a target so let's first get the values out and set them into a variable so we out and set them into a variable so we can say let can say let left val equal left val equal nums at j and let right val equal nums at i or i'm sorry num's at k okay so now we have our left value and okay so now we have three cases here we okay so now we have three cases here we want to say if want to say if uh left val plus right uh left val plus right val is greater than val is greater than target okay so if target okay so if if if we are dealing with an addition if if we are dealing with an addition and it's and it's greater than the target then what do we greater than the target then what do we want to do we want to decrement our want to do we want to decrement our k-th element we want to decrement from k-th element we want to decrement from the right the right so we just want to say k minus minus so we just want to say k minus minus okay else if left okay else if left val plus right val val plus right val is less than target what do we want to do we want to okay now else if they're equal okay now else if they're equal what do we wanna do well we wanna we what do we wanna do well we wanna we wanna push into our result and then we wanna push into our result and then we wanna just make sure that there's no wanna just make sure that there's no duplicates okay so what we can do here is we can just say result dot push and then here we can just go ahead and flip our target so we can say target times -1 okay because we don't want that negated value as our target in our result we want it the original value and then we can just go ahead and put in our left vowel and our right vowel okay now what we want to do is make sure that we move out of any repeating numbers in the i-th index so we can say while k index so we can say while k is less than or log j is less than k is less than or log j is less than k and nums at j equals nums at k what do we want to do okay if nums at j or i'm sorry if nums j equals nums at j plus one okay well all we want to do is just and similarly we want to do while j is and similarly we want to do while j is less than k and nums at k equals nums at k minus 1 we want to decrement k and then we want to again increment j and decrement k so if we have any uh duplicates it'll go out of range and if if it you know if they're if they're bunched together so this will take care of that and then all we want to do is return our result now because we're pushing into results and it's going to be a 2d array with the result that's why we're going to use the spread operator here so that way we spread it out and push it into our final result okay okay and we're good we made great uh okay and we're good we made great uh time and space complexity time and space complexity 90 90 percentile pretty good okay so 90 90 percentile pretty good okay so that that is threesome it is a very tricky is threesome it is a very tricky question question because of these edge cases with the because of these edge cases with the duplicates duplicates uh but if you're familiar with twosome uh but if you're familiar with twosome then this is a great way to kind of just then this is a great way to kind of just have a mental framework if you ever see have a mental framework if you ever see threesome it's just really a combination threesome it's just really a combination of of using two sum as a helper function using two sum as a helper function uh to to iterate over each element of uh to to iterate over each element of the nums array and then just use two sum the nums array and then just use two sum for that for that that sub problem and we can solve this that sub problem and we can solve this okay so hope you enjoyed it and i will okay so hope you enjoyed it and i will see you guys on the next one | 2024-03-19 15:33:41 | 15 | LEETCODE 15 (JAVASCRIPT) | 3SUM |
|
mjwnkXiFCho | [Music] hello everyone welcome to quartus camp hello everyone welcome to quartus camp we are 27th day of september leco we are 27th day of september leco challenge and the problem we are going challenge and the problem we are going to cover in this video is unique email to cover in this video is unique email addresses addresses so the input given here is a list of so the input given here is a list of strings where a list of email addresses strings where a list of email addresses given and we have to return the number given and we have to return the number of email address of email address where the where the that the email address actually receive that the email address actually receive mails and there are certain rules and mails and there are certain rules and conditions to identify them so let's conditions to identify them so let's understand this rules with an example so understand this rules with an example so before getting into the actual example before getting into the actual example given in the problem statement let's given in the problem statement let's understand the rules given in the understand the rules given in the problem so the first rule is dot rule problem so the first rule is dot rule that is the email address is first being that is the email address is first being divided into two parts the first one is divided into two parts the first one is local address and then the second part local address and then the second part is domain address is domain address so so the domain address does not have any the domain address does not have any rules they simply gonna stay the same as rules they simply gonna stay the same as such but the rules are for the local such but the rules are for the local address so first rule is if there is a address so first rule is if there is a dot and the dot should be ignored and dot and the dot should be ignored and this email address can be represented as this email address can be represented as dot rule at elitecode.com there is not a dot will be included in the receiving address and goes to the second one is the plus rule so the plus rule is nothing but whatever is left after plus will be ignored that is only applied to the local address not to the domain address so now considering removing the plus the receiving address will be plus at leadcode.com because after plus whatever is there in the local address will be ignored so these are the simple rules and the both the rules can be applied to a single email address and we have to return how many addresses will be receiving the email at the end so getting back to our actual example given in the problem statement there are three email addresses the first one is having dot as well as plus so as per the rule we have to ignore whatever is after the plus and we have to ignore the dot now the email address will actually become now moving to our second one second one now moving to our second one second one have two dots and one plus so after plus have two dots and one plus so after plus we have to ignore everything in the we have to ignore everything in the local address so bob.kathy will be local address so bob.kathy will be completely ignored and completely ignored and two dots will be ignored in the two dots will be ignored in the front thing so again this email id will front thing so again this email id will be test email at elitecode.com be test email at elitecode.com so going to our next one which is having so going to our next one which is having only one plus so we only one plus so we simply ignore it simply ignore it so now this email address is test email so now this email address is test email at at leadcode.tcode.com because the rules are not applicable to the domain address they are only applicable to the local address so this is going to be different by lead code at so now there are two unique addresses so now there are two unique addresses that is going to receive email at the that is going to receive email at the end so the output is going to be true end so the output is going to be true so hope you're understanding this so hope you're understanding this concept now how we're going to approach concept now how we're going to approach this this so it is going to be very simple so it is going to be very simple straightforward solution where we are straightforward solution where we are going to use string manipulation and get going to use string manipulation and get this done this done so first step we are going to do is we so first step we are going to do is we are going to split are going to split the given email address into local the given email address into local address and domain domain address by address and domain domain address by splitting it with the add sign because splitting it with the add sign because we have to apply the rules only to the we have to apply the rules only to the first part of the email not to the first part of the email not to the second part so once we separate it we second part so once we separate it we keep the second part for finally keep the second part for finally appending it to the final string appending it to the final string and the first part will be going to and the first part will be going to apply with the plus and dot rule and apply with the plus and dot rule and filter finally to add it with the domain filter finally to add it with the domain address so first we are going to split address so first we are going to split it with it with the plus and if there is a plus we are the plus and if there is a plus we are going to ignore the second half and going to ignore the second half and then we will get the rest of the address then we will get the rest of the address only with dot only with dot so once there is so once there is the rest of the address we check for the rest of the address we check for dots and replace them with the empty dots and replace them with the empty space or no space so that we will get space or no space so that we will get the rest of the domain at local address the rest of the domain at local address without dots and we finally have a without dots and we finally have a string without dots and without after string without dots and without after removing plus and we will append that removing plus and we will append that with the second part which is the domain with the second part which is the domain name and we are going to return the name and we are going to return the result in the form of result in the form of uh like we are going to save them in a uh like we are going to save them in a set and the set will be having the set and the set will be having the unique values so finally the size of the unique values so finally the size of the set will be our output set will be our output so this is going to take big o of n time so this is going to take big o of n time and n space complexity as we are going and n space complexity as we are going to store them in an array and to store them in an array and execute the number of email address execute the number of email address given in the input stream array given in the input stream array so let's go to the code so let's go to the code as i said we are going to first have a as i said we are going to first have a set which is going to store the final set which is going to store the final filtered email addresses so now we are going to separate the email addresses into two parts which is local and domain so the string paths will be separated or split using the so once this is split parts of 0 will be so once this is split parts of 0 will be having the domain address sorry local address and parts of one will be having the so now again with the local address we so now again with the local address we are going to split it based on the plus are going to split it based on the plus sign so now this will actually have local of xero will have text before and local of one will have and local of one will have text after plus text after plus so we don't need local of one actually so we don't need local of one actually because because we don't need anything we have to ignore we don't need anything we have to ignore the text which is present after uh plus the text which is present after uh plus so we now have to pick only local of so we now have to pick only local of zero and put the test the next rule zero and put the test the next rule which is the dot rule which is the dot rule so we are directly gonna add to our so we are directly gonna add to our result in that we are going to replace the dots in that we are going to replace the dots with with empty space and once that is added we are going to put the rest of the part by adding the add signature sorry add sign and the second part of the so yes this will complete the email so yes this will complete the email address which is valid and added towards address which is valid and added towards it now our set will be having only the it now our set will be having only the unique email addresses that will be unique email addresses that will be returned as part of returned as part of the result the result so we are finally going to return its so we are finally going to return its size but then we forgot to do one thing which so yes let's run and try yes so let's submit and try yes a solution is accepted and runs in 16 milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in | 2024-03-25 11:30:10 | 929 | Unique Email Addresses | LeetCode 929 | Coders Camp |
|
4lK5pdSXhCk | hello and welcome back to the cracking fang youtube channel today we're going fang youtube channel today we're going to be solving leak code problem 1011 to be solving leak code problem 1011 capacity to ship packages within d days capacity to ship packages within d days at the moment this question is really at the moment this question is really popular with facebook amazon and google popular with facebook amazon and google so definitely want to know if you have so definitely want to know if you have an upcoming on-site interview with any an upcoming on-site interview with any of these companies of these companies let's read the problem statement a let's read the problem statement a conveyor belt has packages that must be conveyor belt has packages that must be shipped from one port to another within shipped from one port to another within day's days day's days the ith package on the conveyor belt has the ith package on the conveyor belt has a weight of weights of eye a weight of weights of eye each day we load the ship with packages each day we load the ship with packages on the conveyor belt in the order given on the conveyor belt in the order given by weights we may not load more weight by weights we may not load more weight than the maximum weight capacity of the than the maximum weight capacity of the ship ship return the least weight capacity of the return the least weight capacity of the ship that will result in all the ship that will result in all the packages on the conveyor belt being packages on the conveyor belt being shipped within days days shipped within days days cool so that's the problem statement but cool so that's the problem statement but let's go through an example for example let's go through an example for example if we were given if we were given this array here weights this array here weights 1 2 3 4 5 6 7 8 9 10 and we were given 1 2 3 4 5 6 7 8 9 10 and we were given five days to ship these packages five days to ship these packages then our answer here would be then our answer here would be 15 15 and let's kind of see how they derived and let's kind of see how they derived that well you know if we chose 15 we that well you know if we chose 15 we could ship these first packages could ship these first packages on the day so this would be what this on the day so this would be what this would be weights of 14 on that first day would be weights of 14 on that first day this would be a way of 13 then 8 this would be a way of 13 then 8 9 and 10. 9 and 10. but that's not really intuitive you know but that's not really intuitive you know how the hell did they come up with 15 how the hell did they come up with 15 right like it doesn't make any sense at right like it doesn't make any sense at all so let's break this down and figure all so let's break this down and figure out a practical way to solve this out a practical way to solve this problem that makes sense because right problem that makes sense because right now it seems like they just picked 15 now it seems like they just picked 15 out of a hat so let's do that all right out of a hat so let's do that all right we've seen the example and we realized we've seen the example and we realized hey this doesn't make much sense how did hey this doesn't make much sense how did they get 15 they get 15 well well let's do this in an intuitive way let's do this in an intuitive way what is the minimum amount of weight what is the minimum amount of weight that we could ship on a day that we could ship on a day well if we think about this the minimum well if we think about this the minimum weight we could choose weight we could choose has to be whatever the maximum weight of has to be whatever the maximum weight of our packages here is why is that which our packages here is why is that which in this case is going to be 10 in this case is going to be 10 right why is that well if we chose right why is that well if we chose anything less than the maximum weight of anything less than the maximum weight of our array here then we would never be our array here then we would never be able to ship that weight able to ship that weight for example if we chose 9 as our maximum for example if we chose 9 as our maximum weight we could ship every single weight we could ship every single package here but we would never be able package here but we would never be able to ship this 10. therefore you know this to ship this 10. therefore you know this would take an infinity amount of time would take an infinity amount of time and it would never work so we know that and it would never work so we know that the minimum weight we can choose from the minimum weight we can choose from has to be the maximum of our array has to be the maximum of our array otherwise we can't ship it cool so otherwise we can't ship it cool so that's the minimum weight we can choose that's the minimum weight we can choose but what's the maximum weight we can but what's the maximum weight we can choose well if we think about it choose well if we think about it the maximum weight is going to be the maximum weight is going to be whatever the sum of our weights is right whatever the sum of our weights is right because in that case we could ship because in that case we could ship everything on a single day so you know everything on a single day so you know if we sum up this array we're going to if we sum up this array we're going to get that the weight here is actually 55. get that the weight here is actually 55. so so you know we could choose 56 57 100 100 you know we could choose 56 57 100 100 000 10 million 000 10 million 100 billion for our weight it wouldn't 100 billion for our weight it wouldn't matter we could still ship everything matter we could still ship everything here but remember that we're trying to here but remember that we're trying to result result we're trying to find the least weight we're trying to find the least weight capacity that would allow us to ship uh capacity that would allow us to ship uh these packages right if we chose 100 these packages right if we chose 100 billion we could ship this in one day billion we could ship this in one day still but all we need is 55 so we're still but all we need is 55 so we're wasting weight capacity so there's no wasting weight capacity so there's no reason to go any higher than whatever reason to go any higher than whatever the sum of our weights here is so that the sum of our weights here is so that gives us the bounds of our you know gives us the bounds of our you know weight search right weight search right it's somewhere between 10 and 55. it's somewhere between 10 and 55. so so if we kind of draw this out you know we if we kind of draw this out you know we have 10 11 have 10 11 12 12 and then you know some values here and and then you know some values here and then we have like 54 then we have like 54 and 55 right and it's going to be all and 55 right and it's going to be all the values between you know 10 and 55 the values between you know 10 and 55 and here i'm just kind of i don't want and here i'm just kind of i don't want to draw everything out to draw everything out so what we could do is you know we could so what we could do is you know we could start at 10 start at 10 and we could say okay you know how many and we could say okay you know how many days would it take to ship days would it take to ship um um these packages if we these packages if we only use 10 only use 10 and remember we have to ship them in the and remember we have to ship them in the order they come so on the first day we order they come so on the first day we could ship one could ship one two three so that would be six so we two three so that would be six so we could ship these packages could ship these packages and that would take one day and that would take one day then on the next day uh we have to ship then on the next day uh we have to ship this package five but we can't ship five this package five but we can't ship five and six because that would be eleven so and six because that would be eleven so we have to ship five on the next day so we have to ship five on the next day so that would take two days on the next day that would take two days on the next day we'd have to ship the six we'd have to ship the six so we'd ship that it would take an extra so we'd ship that it would take an extra day then we ship the seven that takes an day then we ship the seven that takes an extra day so now we're at four eight extra day so now we're at four eight would take its own day would take its own day so now we're at five so now we're at five and then nine would take its own day and and then nine would take its own day and then ten would take one day so we'd be then ten would take one day so we'd be at seven so it would take seven total at seven so it would take seven total days if we chose ten days if we chose ten and remember we have five so this weight and remember we have five so this weight doesn't work okay well doesn't work okay well what if we tried eleven um what if we tried eleven um you know it's the same thing i think it you know it's the same thing i think it would take like six days in this case would take like six days in this case but the point is we can't ship it with but the point is we can't ship it with this obviously we know that the answer this obviously we know that the answer here is 15 so i'm going to kind of just here is 15 so i'm going to kind of just do a little bit of skipping here do a little bit of skipping here uh you know we would try 12 and we can't uh you know we would try 12 and we can't do it so as you can see we're going from do it so as you can see we're going from left to right here and we're basically left to right here and we're basically just trying all of the weights just trying all of the weights so that's you know the first way to so that's you know the first way to solve this solve this is going to be you know the linear is going to be you know the linear solution solution where basically we're going to start at where basically we're going to start at the minimum weight we can do which is the minimum weight we can do which is going to be the maximum of the array and going to be the maximum of the array and we're going to walk towards whatever the we're going to walk towards whatever the the sum of the arrays which is like the the sum of the arrays which is like the maximum possible weight we could choose maximum possible weight we could choose for that day and we're going to find the for that day and we're going to find the first value that trips this um you know first value that trips this um you know that we can ship with and we know that that we can ship with and we know that that's going to be our answer that's going to be our answer so you know doing this would take o of n so you know doing this would take o of n time in the worst case time in the worst case times times whatever whatever the function cost is to figure out the function cost is to figure out whether or not we can ship it whether or not we can ship it so so you know you know we'll kind of just assume that function we'll kind of just assume that function takes o of n time to like sum up whether takes o of n time to like sum up whether or not we can do it right because we or not we can do it right because we have to check all the days so we'll just have to check all the days so we'll just be going from left to right of the be going from left to right of the actual weights here so this would be an actual weights here so this would be an o of n squared solution o of n squared solution okay okay but like i said this is the first but like i said this is the first solution and it's the linear solution solution and it's the linear solution how can we do better than that how can we do better than that well one thing to realize is that we well one thing to realize is that we can't get away from this function here can't get away from this function here that does the summing to figure out you that does the summing to figure out you know whether or not we can ship know whether or not we can ship something on a day this part we can't do something on a day this part we can't do better on but do we actually have to better on but do we actually have to scan from left to right to find this scan from left to right to find this first point and you know the more keen first point and you know the more keen of you will have realized okay well we of you will have realized okay well we actually can do this in log time actually can do this in log time because if you notice because if you notice we're going from 10 to 55 and this is we're going from 10 to 55 and this is increasing by one every time which means increasing by one every time which means that this array is actually sorted so that this array is actually sorted so we're looking for the first value we're looking for the first value that trips you know that trips you know um that would work for us and we have a um that would work for us and we have a sorted array so this should be screaming sorted array so this should be screaming to you hey we need this binary search to you hey we need this binary search here so we can actually take our run here so we can actually take our run time complexity from o of you know n time complexity from o of you know n squared down to you know n squared down to you know n log n log n times times o of n so we can reduce oh sorry this o of n so we can reduce oh sorry this isn't n log n this would just be log n isn't n log n this would just be log n so our final solution is going to be n so our final solution is going to be n log n log n so so that's gonna be the best thing we can do that's gonna be the best thing we can do if we use a binary search here and this if we use a binary search here and this is really what your interviewer is is really what your interviewer is looking for how you're gonna set up this looking for how you're gonna set up this binary search and also binary search and also you know how you do this the check you know how you do this the check whether or not you can ship it so that's whether or not you can ship it so that's the two parts we need right we need the the two parts we need right we need the binary search part binary search part uh and then we also need the uh and then we also need the some function to tell us whether or not some function to tell us whether or not we can ship we can ship our weights here our weights here so now that we know that that's what so now that we know that that's what we're looking for let's go to the editor we're looking for let's go to the editor and actually write the code and actually write the code and it's quite simple all right i'll see and it's quite simple all right i'll see you there welcome back now we're in the you there welcome back now we're in the editor let's write the code so we know editor let's write the code so we know that we're going to do a binary search that we're going to do a binary search so to do a binary search you need a left so to do a binary search you need a left and a right endpoint for your search so and a right endpoint for your search so let's define those remember that the let's define those remember that the left which is going to represent the left which is going to represent the minimum weight that we can ship on a day minimum weight that we can ship on a day is going to be the maximum of the is going to be the maximum of the weights that we're given right so we're weights that we're given right so we're going to say max of weights and the going to say max of weights and the right endpoint is going to be the sum right endpoint is going to be the sum of the weights we're given and if you of the weights we're given and if you don't understand how we got those go don't understand how we got those go back to the explanation portion where i back to the explanation portion where i go over why we choose the max as the go over why we choose the max as the minimum weight and the sum as the the minimum weight and the sum as the the right endpoint right endpoint cool so let's set up our binary search cool so let's set up our binary search and remember that we're looking for the and remember that we're looking for the the least value um so we won't actually the least value um so we won't actually be returning within our binary search so be returning within our binary search so we need to be careful to set up the we need to be careful to set up the binary search correctly so in these binary search correctly so in these cases where you're not actually cases where you're not actually returning a value from within the binary returning a value from within the binary search usually you use while left is search usually you use while left is less than right if we're looking for less than right if we're looking for something inside of the array we would something inside of the array we would use less left less than or equal to use less left less than or equal to right but in this case since we're right but in this case since we're moving our pointer down and we're moving our pointer down and we're actually going to move the point we're actually going to move the point we're going to return the pointer going to return the pointer value we don't want to use value we don't want to use the less than or equal to so the less than or equal to so with a standard binary search we're with a standard binary search we're going to do mid equals to left oops going to do mid equals to left oops left plus right divide by two and there left plus right divide by two and there is a way to avoid overflow in java i'm is a way to avoid overflow in java i'm using python here so um you know look it using python here so um you know look it up how to avoid the overflow in java if up how to avoid the overflow in java if you're using that or c plus plus you're using that or c plus plus anyway um so anyway um so what are the two things that can happen what are the two things that can happen here in our search right either we can here in our search right either we can ship the weight or we can't so we're ship the weight or we can't so we're going to define a function to do that in going to define a function to do that in a second but let's kind of just go a second but let's kind of just go through it conceptually so we're going through it conceptually so we're going to say if self dot can ship so if we can to say if self dot can ship so if we can ship ship the weight the weight with whatever our mid because that's with whatever our mid because that's going to represent the weight we're going to represent the weight we're using using uh we're going to pass weights and we're uh we're going to pass weights and we're going to ship the days that we're going to ship the days that we're allowed allowed if we can ship it with this weight if we can ship it with this weight we need to move our endpoint right we need to move our endpoint right so we're going to say right equals mid so we're going to say right equals mid and why do we use mid instead of mid and why do we use mid instead of mid minus one well let's think about this minus one well let's think about this if we did mid minus one and it turns out if we did mid minus one and it turns out that this weight mid that this weight mid was actually was actually the answer then the answer then if we did mid minus one then we would if we did mid minus one then we would never return never return that value because we would we would that value because we would we would accidentally go over it so we can never accidentally go over it so we can never do mid minus one when we know that we do mid minus one when we know that we can ship it because that could actually can ship it because that could actually be that left most point and therefore be that left most point and therefore our answer so if we can ship with a our answer so if we can ship with a weight we have to use right equals mid weight we have to use right equals mid conversely if we can't ship the weight conversely if we can't ship the weight then we know for sure that that value then we know for sure that that value and anything to the left of it will and anything to the left of it will never work right if if a certain weight never work right if if a certain weight is not shippable then any weight smaller is not shippable then any weight smaller than it will never be shippable we can than it will never be shippable we can only look for larger weights so when only look for larger weights so when it's not shippable then we can do mid it's not shippable then we can do mid plus one plus one so so in the end all we have to do is actually in the end all we have to do is actually return that right because this is gonna return that right because this is gonna be the solution and this is usually the be the solution and this is usually the case when you're looking for kind of the case when you're looking for kind of the left most or the right most value with left most or the right most value with the binary search if you're just the binary search if you're just returning a value you can typically do returning a value you can typically do mid plus one and then mid minus one for mid plus one and then mid minus one for you know whatever your left and right is you know whatever your left and right is and you would use the less than or equal and you would use the less than or equal to up here but in this case we're trying to up here but in this case we're trying to move our to move our we're trying to find the left most or we're trying to find the left most or the smallest weight that we can use uh the smallest weight that we can use uh we need to set it up this way we need to set it up this way and if this is a little bit unclear and if this is a little bit unclear we're going to go back to the drawing we're going to go back to the drawing board in the end and i'll show you why board in the end and i'll show you why this is the case so you can see it this is the case so you can see it visually because it is a little bit hard visually because it is a little bit hard to conceptualize the binary search this to conceptualize the binary search this way um so it is a little bit easier to way um so it is a little bit easier to just see it in actual you know a diagram just see it in actual you know a diagram anyway anyway this is how this is how the function to ship within days is the function to ship within days is going to need to look like but we need going to need to look like but we need to define our can ship to define our can ship so let's do that so we're going to say so let's do that so we're going to say def def can ship can ship and we're going to say self and this is and we're going to say self and this is going to be the candidate weight it's going to be the candidate weight it's going to take the weights and the days going to take the weights and the days that we're allowed to use that we're allowed to use so so what we need to do is we need to track what we need to do is we need to track the the current weight capacity of our ship and current weight capacity of our ship and we need to track the we need to track the days that we've taken so far days that we've taken so far so the current weight so the current weight is going to equal zero because we is going to equal zero because we haven't loaded anything onto our ship haven't loaded anything onto our ship and we're going to say that days taken and we're going to say that days taken is going to equal to one uh and the is going to equal to one uh and the reason that we're going to use one i'll reason that we're going to use one i'll explain at the end but basically what we explain at the end but basically what we want to do is that we know that if we want to do is that we know that if we have the case where we're actually using have the case where we're actually using the maximum amount of weight then it's the maximum amount of weight then it's always gonna take one if we did zero um always gonna take one if we did zero um within our code here which you'll see in within our code here which you'll see in a second we would never actually a second we would never actually increment the days and we would return increment the days and we would return zero which isn't correct because we have zero which isn't correct because we have to ship it in at least one day right we to ship it in at least one day right we can't unless you can't ship in zero days can't unless you can't ship in zero days so so let's go through it so we're gonna say let's go through it so we're gonna say for the weight in weights for the weight in weights what's gonna happen we're gonna say that what's gonna happen we're gonna say that the current weight of our ship the current weight of our ship it we're gonna add the weight to it it we're gonna add the weight to it now now if the current weight of our ship if the current weight of our ship exceeds the weight that we're allowed to exceeds the weight that we're allowed to use which is the candidate weight we use which is the candidate weight we know that our ship is overloaded and we know that our ship is overloaded and we weren't actually allowed to take that weren't actually allowed to take that last weight so what we need to do is we last weight so what we need to do is we need to say okay well we can send the need to say okay well we can send the ship off without this last weight here ship off without this last weight here so we're going to send it off and we're so we're going to send it off and we're going to say that day is taken going to say that day is taken we're going to add one to it and then we we're going to add one to it and then we need to reset our weight back to need to reset our weight back to whatever the weight we just took was whatever the weight we just took was that caused us to trip so for example if that caused us to trip so for example if the weight of our ship was 9 and the the weight of our ship was 9 and the next weight was say 4 and we were only next weight was say 4 and we were only allowed to load 10 on a given day allowed to load 10 on a given day obviously if we took the 4 then we'd be obviously if we took the 4 then we'd be at a weight of 13 we can't do that so we at a weight of 13 we can't do that so we have to ship that 9 weight and then the have to ship that 9 weight and then the 4 is going to remain for the next day 4 is going to remain for the next day so so we do this for all the weights and we're we do this for all the weights and we're going to increment you know our days going to increment you know our days taken as we go along and this is the taken as we go along and this is the reason that actually um reason that actually um you know we need to start with days you know we need to start with days taken as one because if the candidate is taken as one because if the candidate is actually the maximum weight actually the maximum weight this curve weight will actually never be this curve weight will actually never be greater than greater than um the candidate because they'll just be um the candidate because they'll just be equal in the end and we would never have equal in the end and we would never have incremented days taken and therefore we incremented days taken and therefore we would return zero so that's why we need would return zero so that's why we need to return days to uh we need to start to return days to uh we need to start with days taken as one with days taken as one and in the end all we need to do is and in the end all we need to do is return return days taken days taken is less than or equal to days right is less than or equal to days right because that's what we're looking for we because that's what we're looking for we need to be able to ship the day uh the need to be able to ship the day uh the weight weight within days so either we ship it within within days so either we ship it within you know five days here or less than you know five days here or less than that you know for this particular that you know for this particular example example so that's how you define the canship so that's how you define the canship function let's submit this and double function let's submit this and double check that it works check that it works and once this runs cool we can see that and once this runs cool we can see that it does and it's quite quick because it does and it's quite quick because it's the binary search solution it's the binary search solution so so before we go back to the drawing board before we go back to the drawing board to actually talk about to actually talk about kind of how the binary search is set up kind of how the binary search is set up in this case let us in this case let us talk about the time and space complexity talk about the time and space complexity so so you know what's going on here well we you know what's going on here well we know that we have a binary search so any know that we have a binary search so any binary search is always going to be log binary search is always going to be log of n right of n right now now that's going to be the binary search that's going to be the binary search part but within each binary search we part but within each binary search we need to call this can ship function so need to call this can ship function so let's find out what the time complexity let's find out what the time complexity of this can ship function is well of this can ship function is well in this case in this case what we do in the can ship is basically what we do in the can ship is basically we go from left to right to sum up you we go from left to right to sum up you know know the current weight that we have and then the current weight that we have and then compare it to our candidate so really compare it to our candidate so really what we're doing is we're just doing a what we're doing is we're just doing a sum over the sum over the the weights here and in the worst case the weights here and in the worst case we would have the maximum we would have the maximum uh weight which is going to be remember uh weight which is going to be remember the the total sum of the weight so we the the total sum of the weight so we would basically just sum our entire would basically just sum our entire array so in the worst case this is going array so in the worst case this is going to be an o of n operation to be an o of n operation so our time complexity in the end is so our time complexity in the end is going to be big o of n going to be big o of n log n log n space complexity wise at no point do we space complexity wise at no point do we actually define any extra space for our actually define any extra space for our solution here we have this left and solution here we have this left and right pointer but these are just right pointer but these are just pointers these are constant space pointers these are constant space variables so we don't actually define variables so we don't actually define any new variables here same with these any new variables here same with these these are just these are just you know pointer variables like what's you know pointer variables like what's the current weight what's the days taken the current weight what's the days taken so we don't you know define any arrays so we don't you know define any arrays or anything like that so the space or anything like that so the space complexity is actually going to be complexity is actually going to be constant space right constant space right so that's the time and space complexity so that's the time and space complexity cool cool at this point let's go back to the at this point let's go back to the drawing board and walk through a simple drawing board and walk through a simple example so you can see why the binary example so you can see why the binary search is set up in the way that it is search is set up in the way that it is because it's a little bit hard to grasp because it's a little bit hard to grasp if you've not really seen this before if you've not really seen this before and you don't understand how binary and you don't understand how binary searches uh that follow this pattern searches uh that follow this pattern work so i'll see you back at the editor work so i'll see you back at the editor in a second let's go over why the binary in a second let's go over why the binary search actually is set up in the way search actually is set up in the way that it is if you already understand it that it is if you already understand it and it's pretty intuitive to you you can and it's pretty intuitive to you you can skip this part go watch another video if skip this part go watch another video if you want um you don't need it if you you want um you don't need it if you were a little bit unclear this is the were a little bit unclear this is the portion of the video for you so let's go portion of the video for you so let's go into it into it so we remember you know what we do is we so we remember you know what we do is we set up our left to be you know set up our left to be you know this point here which is the maximum of this point here which is the maximum of our array here so this is gonna be four our array here so this is gonna be four and remember that the and remember that the the right point is going to be the the right point is going to be the actual sum of this array so you know if actual sum of this array so you know if we sum this up we actually get 16 and we sum this up we actually get 16 and i've drawn this out so basically we have i've drawn this out so basically we have all the values between 4 and 16 that all the values between 4 and 16 that could be the weight that we use could be the weight that we use so remember you know we're going to do so remember you know we're going to do while left is less than right while left is less than right so so you know we pick a midpoint what's the you know we pick a midpoint what's the midpoint here so it's going to be 4 plus midpoint here so it's going to be 4 plus 16 16 so 4 plus 16 equals 20 divided by 2 so 4 plus 16 equals 20 divided by 2 uh is going to be 10 right so the uh is going to be 10 right so the midpoint midpoint is going to be 10 here so we're going to is going to be 10 here so we're going to choose 10 as our weight cool choose 10 as our weight cool so so you know can we ship with 10 okay let's you know can we ship with 10 okay let's check it out so we could ship the three check it out so we could ship the three plus the two so that's gonna be a way of plus the two so that's gonna be a way of five five plus the plus the two again so that's going to be seven two again so that's going to be seven and then we get to the four so we can't and then we get to the four so we can't ship that because it would go up to 11 ship that because it would go up to 11 here so this weights would take one day here so this weights would take one day then the next one would take okay well then the next one would take okay well we could ship the four plus one so we could ship the four plus one so that's gonna be five plus four so that's that's gonna be five plus four so that's going to be nine so we can actually ship going to be nine so we can actually ship everything else on the second day so it everything else on the second day so it would take two days so 10 works right would take two days so 10 works right so 10 works which means that um you know so 10 works which means that um you know 10 could be a potential solution we 10 could be a potential solution we don't need to check anything else here don't need to check anything else here because these are all values greater because these are all values greater than 10 and remember we're looking for than 10 and remember we're looking for the least weight capacity so we know if the least weight capacity so we know if 10 works we don't care about anything to 10 works we don't care about anything to the right of it because we know that at the right of it because we know that at this point this point it's fine uh 10 could be our potential it's fine uh 10 could be our potential solution we don't need to try anything solution we don't need to try anything larger than 10 because we're looking larger than 10 because we're looking again for the least weight capacity again for the least weight capacity cool so now our right if we remember cool so now our right if we remember back from the code is going to equal to back from the code is going to equal to whatever the midpoint value was so now whatever the midpoint value was so now our right is going to be 10. our right is going to be 10. so so let's keep going you know is 4 still let's keep going you know is 4 still less than 10 yes it is so that means we less than 10 yes it is so that means we have to calculate a new pinpoint so have to calculate a new pinpoint so we're going to say 4 plus 10 divide by 2 we're going to say 4 plus 10 divide by 2 so this is going to be what seven right so this is going to be what seven right so that so now we're at the seven so that so now we're at the seven so let's try seven okay so let's try seven okay well well you know if we have our array here um you know if we have our array here um let's see we have three so on the first let's see we have three so on the first day we could ship the three we could day we could ship the three we could ship the two so that would be six and ship the two so that would be six and then trying or started five and then then trying or started five and then this one uh that would be seven so this this one uh that would be seven so this would be you know we could still ship it would be you know we could still ship it on one day on one day and then so that would take one day in and then so that would take one day in this case you know it would be four plus this case you know it would be four plus one five but we can't ship this last one five but we can't ship this last four because that would be nine so that four because that would be nine so that means that would take two and then this means that would take two and then this last four would take three days so seven last four would take three days so seven works because it's um works because it's um you know at least you know at least you know within d days so we're allowed you know within d days so we're allowed you know you know less than or equal to here so 7 works less than or equal to here so 7 works so that means that anything to the right so that means that anything to the right of 7 is no longer valid as well of 7 is no longer valid as well so we found a new best answer so now our so we found a new best answer so now our right is going to become 7. right is going to become 7. so what we want to do now is okay we so what we want to do now is okay we need to calculate a new midpoint so need to calculate a new midpoint so we're going to say 4 we're going to say 4 plus 7 plus 7 divide by 2 so this is 11 remember we're divide by 2 so this is 11 remember we're using integer division so this would using integer division so this would really be really be uh so this would be 11 by 2 is uh so this would be 11 by 2 is what 5.5 and then since it's integer it what 5.5 and then since it's integer it goes down to 5. goes down to 5. so we're going to choose 5 here so we're going to choose 5 here so uh let us and then i'll redraw this so uh let us and then i'll redraw this thing so we have 3 2 thing so we have 3 2 2 2 four one four okay so four one four okay so can we ship it with five okay well we can we ship it with five okay well we could ship this in one day because could ship this in one day because that's five that's five this is gonna be six here so we can't do this is gonna be six here so we can't do it so we have to ship the two separately it so we have to ship the two separately so we'd ship it it takes its own day we so we'd ship it it takes its own day we could ship this could ship this because it's five so that would take one because it's five so that would take one another day another day and then this would take its own day so and then this would take its own day so this would take four days so obviously this would take four days so obviously four four is greater than our allowed allotment of is greater than our allowed allotment of three so we can't actually ship it there three so we can't actually ship it there so that wouldn't work so that wouldn't work so that means that five is not a viable so that means that five is not a viable solution so that means our left pointer solution so that means our left pointer has to move up right has to move up right so we set is mid plus one so it's going so we set is mid plus one so it's going to be six here to be six here so now our left is six cool so now let's so now our left is six cool so now let's go through the process again go through the process again and let's find a new pin point so we're and let's find a new pin point so we're gonna say six plus seven divide by two gonna say six plus seven divide by two so this is 13 divided by two so that's so this is 13 divided by two so that's going to be what six right going to be what six right uh because it's um you know uh because it's um you know 6.5 6.5 and then obviously it's integer division and then obviously it's integer division uh so we're truncating down to six uh so we're truncating down to six cool so let's try now six cool so let's try now six so we're going to try okay can we ship so we're going to try okay can we ship this packages yes this is going to be this packages yes this is going to be five so this is going to take one day five so this is going to take one day obviously using the two wouldn't work obviously using the two wouldn't work because that would take us to seven so because that would take us to seven so then we reset it so then on the second then we reset it so then on the second day we could ship this because this is day we could ship this because this is six and then on the last day we could six and then on the last day we could ship these two because this is going to ship these two because this is going to be uh five so this would take three days be uh five so this would take three days cool so we know that six works because cool so we know that six works because we are within our three days right we we are within our three days right we take the three days that's fine so now take the three days that's fine so now we are good here so now our right we are good here so now our right pointer becomes six because we set it pointer becomes six because we set it equal to mid equal to mid so so at this point we have left equals six at this point we have left equals six and right equals six and remember that and right equals six and remember that our binary search is going to be while our binary search is going to be while left uh left is less than right so in left uh left is less than right so in this case they're actually equal so this this case they're actually equal so this binary search would break and remember binary search would break and remember the last thing we need to do is actually the last thing we need to do is actually just return the right which is going to just return the right which is going to be 6. so that's how they derived it be 6. so that's how they derived it hopefully that's a little bit clearer hopefully that's a little bit clearer explanation of how explanation of how you know the binary search works in this you know the binary search works in this case using you know left minus right and case using you know left minus right and then then moving you know right equals mid moving you know right equals mid uh uh if it's if it's good and then left uh uh if it's if it's good and then left equals equals i guess mid i guess mid plus one uh if it doesn't work if that plus one uh if it doesn't work if that was still unclear go back over this was still unclear go back over this explanation and hopefully you know explanation and hopefully you know re-watch it as many times as you need to re-watch it as many times as you need to to kind of visualize it maybe even work to kind of visualize it maybe even work through the example yourself and it through the example yourself and it should start to click so should start to click so that's how you do leak code problem 1011 that's how you do leak code problem 1011 or i guess 1011 or i guess 1011 capacity to ship packages within d days capacity to ship packages within d days hopefully you've enjoyed this video this hopefully you've enjoyed this video this is actually a very common problem that is actually a very common problem that you're going to see on leak code you're going to see on leak code not only because it uses binary search not only because it uses binary search which comes up in pretty much any which comes up in pretty much any company's onsite interviews these days company's onsite interviews these days but i think the problems that are very but i think the problems that are very similar to this are going to be cutting similar to this are going to be cutting ribbons and cocoa eating bananas so if ribbons and cocoa eating bananas so if you want to take the knowledge that you you want to take the knowledge that you learned from this problem uh go try learned from this problem uh go try those out if you don't understand it i those out if you don't understand it i should have a video coming out real soon should have a video coming out real soon about those two videos about those two about those two videos about those two problems so if you don't understand how problems so if you don't understand how to do those problems you can watch my to do those problems you can watch my videos and then hopefully you'll know videos and then hopefully you'll know how to do them so how to do them so thank you for watching if you enjoyed thank you for watching if you enjoyed this video please like comment and this video please like comment and subscribe and make sure to watch all of subscribe and make sure to watch all of my other videos if you're prepping for my other videos if you're prepping for an on-site interview have a good one | 2024-03-25 14:40:53 | 1,011 | CAPACITY TO SHIP PACKAGES WITHIN D DAYS | SOLUTION EXPLAINED [PYTHON] | LEETCODE 1011 |
|
yU1EnHZWscU | hey how's it goin guys so in this video we'll discuss about this problem we'll discuss about this problem counting bits given a non-negative counting bits given a non-negative integer number now for every numbers I integer number now for every numbers I in the range 0 to num calculate the in the range 0 to num calculate the number of buns in their binary number of buns in their binary representation and it turned imagine representation and it turned imagine Eddie so let us consider some examples Eddie so let us consider some examples first so for this example 5 the output first so for this example 5 the output is something like 0 1 1 2 1 2 is something like 0 1 1 2 1 2 so I'd represent numbers from 0 to 5 so I'd represent numbers from 0 to 5 over here in their binary format so you over here in their binary format so you get can be clearly seen that number of get can be clearly seen that number of ones in 0 is 0 so we have 0 over here ones in 0 is 0 so we have 0 over here number of ones in 1 is 1 so we have 1 number of ones in 1 is 1 so we have 1 over here similarly number of ones in 2 over here similarly number of ones in 2 is also 1 so we have 1 over here for 3 is also 1 so we have 1 over here for 3 the number of buns are 2 so we have 2 the number of buns are 2 so we have 2 over here and so on now let us see how over here and so on now let us see how we can solve this problem so this is the we can solve this problem so this is the number and this is a general number end number and this is a general number end ok and for this general number end this ok and for this general number end this is the least significant one what is the is the least significant one what is the meaning of least significant one it meaning of least significant one it means that this is the rightmost one so means that this is the rightmost one so in case there exist bits on the in case there exist bits on the tightening side of it though those all tightening side of it though those all will be 0 so this is the general number will be 0 so this is the general number and given to us now if you see this is and given to us now if you see this is the general number n minus 1 now if you the general number n minus 1 now if you see carefully what happens is on the see carefully what happens is on the left of the least significant one that left of the least significant one that is this part this part remains same for is this part this part remains same for n minus 1 the least significant one will n minus 1 the least significant one will be converted to 0 and in case there be converted to 0 and in case there exist bits on the dynein side of the exist bits on the dynein side of the least significant one which will be all least significant one which will be all zeros for n will be converted to all zeros for n will be converted to all ones now you might think that why this ones now you might think that why this holds so this is a very general thing holds so this is a very general thing this will hold for any two conjugative this will hold for any two conjugative numbers so you can take any two numbers so you can take any two consecutive numbers like 15 16 or 100 consecutive numbers like 15 16 or 100 hundred 1 or any two numbers it this hundred 1 or any two numbers it this thing will hold so I can show you this thing will hold so I can show you this thing with the help of an example so thing with the help of an example so this is the number 52 and this is the this is the number 52 and this is the number 51 so if you see carefully this number 51 so if you see carefully this is the least significant one for 52 that is the least significant one for 52 that is the rightmost one so what I just said is the rightmost one so what I just said is the left-hand part of the least is the left-hand part of the least significant one will remain same that is significant one will remain same that is this 1 1 0 will remain same for 51 as this 1 1 0 will remain same for 51 as per the least significant one will be per the least significant one will be converted to 0 and only died inside all converted to 0 and only died inside all zeros will be converted to all much zeros will be converted to all much now if I take the bit by the end of now if I take the bit by the end of these two numbers n and n minus 1 so these two numbers n and n minus 1 so what will happen is see on the left hand what will happen is see on the left hand side of the least significant one this side of the least significant one this part is same for n and n minus 1 so this part is same for n and n minus 1 so this part will remain same for this and end part will remain same for this and end and minus 1 as well this is 1 over here and minus 1 as well this is 1 over here and a 0 over here so this will be 0 and and a 0 over here so this will be 0 and on the items right there will be all on the items right there will be all zeros over here there will be all ones zeros over here there will be all ones over here so if this will be all zeros over here so if this will be all zeros correct so this is an end and minus 1 correct so this is an end and minus 1 now if you see carefully let us compare now if you see carefully let us compare these two numbers this number n and this these two numbers this number n and this number and end and minus 1 so if you see number and end and minus 1 so if you see carefully these two numbers will only carefully these two numbers will only differ in this bit this is 1 over here differ in this bit this is 1 over here and this is 0 over here everything else and this is 0 over here everything else will be seen so actually this is a will be seen so actually this is a common technique to remove the rightmost common technique to remove the rightmost bit or the least significant bit or the bit or the least significant bit or the least significant one least significant one so using this what you just did is for so using this what you just did is for from the end you have removed the least from the end you have removed the least significant one so this is the common significant one so this is the common technique that we use so what I can say technique that we use so what I can say is this number and this number differ is this number and this number differ only at one place that is this place only at one place that is this place correct so we have removed the least correct so we have removed the least significant one so what can I say can I significant one so what can I say can I say that the number of ones for distal say that the number of ones for distal will be equal to the number of ones for will be equal to the number of ones for this number plus one let me repeat it this number plus one let me repeat it again what I just said is this number again what I just said is this number and this number these two numbers only and this number these two numbers only differ at one bit that is the least differ at one bit that is the least significant one which is removed from significant one which is removed from one we have moved to 0 so what I just one we have moved to 0 so what I just said is the number of ones for this said is the number of ones for this number will be equal to the number of number will be equal to the number of ones in this number plus one so this is ones in this number plus one so this is what we are going to do in the problem what we are going to do in the problem so for any number n we will try to find so for any number n we will try to find it for this number and we'll just add it for this number and we'll just add one to the result and then we will find one to the result and then we will find the number of ones for this n so I the number of ones for this n so I written the algorithm over here you can written the algorithm over here you can pause the video you can read it out and pause the video you can read it out and I will write the code now and then I will write the code now and then things will be more clear things will be more clear so first what we'll do is we'll create a so first what we'll do is we'll create a result ignoring off size num plus 1y num result ignoring off size num plus 1y num plus 1 because we want plus 1 because we want number of ones in all numbers from zero number of ones in all numbers from zero to none now so result of zero will be to none now so result of zero will be actually zero actually zero why is that what I'm saying is the why is that what I'm saying is the number of ones in zero is zero this is number of ones in zero is zero this is already discussed the number of ones in already discussed the number of ones in zeros is actually zero and actually we zeros is actually zero and actually we don't have even have to write this thing don't have even have to write this thing why because it will be niche light to why because it will be niche light to zero only so I can just remove this zero only so I can just remove this thing and I will today from I equals 1 thing and I will today from I equals 1 to I less then num plus 1 I plus 2 is to I less then num plus 1 I plus 2 is now what I did do is result of I will be now what I did do is result of I will be same as result of I and I minus 1 plus 1 same as result of I and I minus 1 plus 1 so this is what we discussed over here so this is what we discussed over here there are number of ones for this number there are number of ones for this number will be same as number of ones for this will be same as number of ones for this number plus one so this is what we are number plus one so this is what we are doing over here and after this is done doing over here and after this is done you can simply return the result so I you can simply return the result so I guess that's it let me submit the guess that's it let me submit the solution so it got accepted so I guess solution so it got accepted so I guess that's it from the video in case you that's it from the video in case you have learned anything from the video you have learned anything from the video you can hit that like button and in order to can hit that like button and in order to support my book you may consider support my book you may consider subscribing to my channel thank you | 2024-03-24 10:54:02 | 338 | Counting Bits | counting bits | counting bits leetcode | leetcode 338 |
|
kEfPSzgL-Ss | hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve the problem maximum number let's solve the problem maximum number of vowels in a substring of a given of vowels in a substring of a given length we're given a string s and an length we're given a string s and an integer k k represents the size of our integer k k represents the size of our substring but I prefer to call it a substring but I prefer to call it a window because substring problems are window because substring problems are commonly sliding window problems so commonly sliding window problems so that's the first thing that I usually that's the first thing that I usually look for and in this case that's exactly look for and in this case that's exactly what's going to happen but don't worry what's going to happen but don't worry if you're not familiar with the sliding if you're not familiar with the sliding window algorithm I will really try to window algorithm I will really try to explain the intuition behind it because explain the intuition behind it because it's not a super crazy algorithm but if it's not a super crazy algorithm but if you're already familiar with it this you're already familiar with it this problem is pretty much a textbook problem is pretty much a textbook example of the fixed sliding window example of the fixed sliding window algorithm sometimes you also have algorithm sometimes you also have variable sliding windows but in this variable sliding windows but in this case we are just given the integer K and case we are just given the integer K and of course K is fixed so we have fixed of course K is fixed so we have fixed sliding Windows okay but what is the sliding Windows okay but what is the problem even asking of us so basically problem even asking of us so basically given a string we can take Windows of given a string we can take Windows of size K in this case k is three so the size K in this case k is three so the first three characters this this is a first three characters this this is a window the next three characters and window the next three characters and these three characters and just keep these three characters and just keep going exactly like that so for every going exactly like that so for every single window well how many windows are single window well how many windows are there roughly there are going to be n there roughly there are going to be n Windows what's the size of each window Windows what's the size of each window well of course it's going to be K so if well of course it's going to be K so if we had to go through every single we had to go through every single substring and just count the characters substring and just count the characters character by character this is what the character by character this is what the time complexity would be and that's time complexity would be and that's pretty much what we're doing in this pretty much what we're doing in this problem we're not actually counting each problem we're not actually counting each character we are checking each character character we are checking each character to see if it is a English vowel so we to see if it is a English vowel so we want to count the number of vowels in want to count the number of vowels in each of these substrings and what we each of these substrings and what we want to return is the maximum so want to return is the maximum so whichever one of these substrings has whichever one of these substrings has the maximum number of vowels that's the the maximum number of vowels that's the number that we want to return the number that we want to return the maximum number of vowels in any of those maximum number of vowels in any of those substrings and it's as simple as Big O substrings and it's as simple as Big O of n times K we could do it with a of n times K we could do it with a nested for Loop just to walk through it nested for Loop just to walk through it we'd go character the a is not a vowel we'd go character the a is not a vowel this is not a vowel and this is not a this is not a vowel and this is not a vowel so all three characters starting vowel so all three characters starting from here next we'd start at the second from here next we'd start at the second character here is this a vowel nope is character here is this a vowel nope is this a vowel nope is this a vowel yes so this a vowel nope is this a vowel yes so here we had one vowel next we're going here we had one vowel next we're going to do something similar we're gonna go to do something similar we're gonna go to the next character it's not a vowel to the next character it's not a vowel next character it's a vowel next next character it's a vowel next character it's a vowel so here we have character it's a vowel so here we have two vowels we can just continue going two vowels we can just continue going like this but are you kind of noticing like this but are you kind of noticing we're doing something a little bit dumb we're doing something a little bit dumb here when we're over here we know that here when we're over here we know that this window has a single vowel in it and this window has a single vowel in it and we just went character by character we we just went character by character we went through all three characters so if went through all three characters so if the next question is what about this the next question is what about this substring or window how many vowels are substring or window how many vowels are in this substring well most of the in this substring well most of the problem is already solved we already problem is already solved we already know how many vowels are in this portion know how many vowels are in this portion this green portion we already did that this green portion we already did that well we also did this but we don't need well we also did this but we don't need this right so we kind of want to remove this right so we kind of want to remove this we're chopping this off and adding this we're chopping this off and adding this next character just one character this next character just one character we remove this and add one character so we remove this and add one character so you can see going from one window to the you can see going from one window to the next window is actually an O of one time next window is actually an O of one time operation and how many windows we have operation and how many windows we have is n so actually this algorithm is Big O is n so actually this algorithm is Big O of n it's not super crazy is it the idea of n it's not super crazy is it the idea is that we can keep track of each window is that we can keep track of each window using exactly two pointers I like to using exactly two pointers I like to call them the left and right pointer of call them the left and right pointer of course the left pointer will tell us the course the left pointer will tell us the beginning of our window and the right beginning of our window and the right pointer will tell us the ending of our pointer will tell us the ending of our window now we're not going to quite window now we're not going to quite start out like this we're actually going start out like this we're actually going to start out like this where both to start out like this where both pointers are going to be at the first pointers are going to be at the first character left and right but then we're character left and right but then we're going to take this right pointer and going to take this right pointer and shift it to the next character so right shift it to the next character so right pointers here now then we shift it again pointers here now then we shift it again now we finally have a window of size K now we finally have a window of size K we could still consider these smaller we could still consider these smaller Windows that's not going to change our Windows that's not going to change our result so I won't pay any attention to result so I won't pay any attention to that but now we're finally at our first that but now we're finally at our first window it doesn't have any vowels so window it doesn't have any vowels so what are we gonna do well chop off this what are we gonna do well chop off this guy so shift our left pointer to the guy so shift our left pointer to the right by one over here and also shift right by one over here and also shift our right pointer this guy to the right our right pointer this guy to the right over here and now this is our window over here and now this is our window when we remove this character we have to when we remove this character we have to check is it a vowel or not for our check is it a vowel or not for our window we are going to keep track of a window we are going to keep track of a count variable we want to count how many count variable we want to count how many vowels are in this window at any given vowels are in this window at any given point originally it was zero for the point originally it was zero for the first window we had zero when we shifted first window we had zero when we shifted to the right we removed a non-vowel to the right we removed a non-vowel character and we added a vowel character character and we added a vowel character we added an i i is a vowel so now we we added an i i is a vowel so now we should increment our count so this should increment our count so this window has a count of one and of course window has a count of one and of course at the end we want to return what the at the end we want to return what the max count was among any of the windows I max count was among any of the windows I know I went pretty deep for a relatively know I went pretty deep for a relatively simple problem but I think taking the simple problem but I think taking the time to really understand exactly what's time to really understand exactly what's going on helps for a lot of the more going on helps for a lot of the more difficult problems so now let's code difficult problems so now let's code this up so the first thing I'm going to this up so the first thing I'm going to do is just create a vowel set so the do is just create a vowel set so the five vowel characters are lowercase a e five vowel characters are lowercase a e i o o and you since it's just five i o o and you since it's just five characters we probably don't need to put characters we probably don't need to put it in a hash set this is a hash set in it in a hash set this is a hash set in Python that's the Syntax for it we could Python that's the Syntax for it we could have put it in an array it doesn't have put it in an array it doesn't really matter because searching it is really matter because searching it is going to be a constant operation but you going to be a constant operation but you know I digress the space complexity of know I digress the space complexity of this function is constant because this function is constant because there's just five characters we don't there's just five characters we don't really need extra space here now we are really need extra space here now we are gonna start iterating we're gonna go gonna start iterating we're gonna go through the entire string the way I like through the entire string the way I like to do it is have an R pointer and you'll to do it is have an R pointer and you'll just have it iterate like this with a just have it iterate like this with a for Loop some people use while Loops for Loop some people use while Loops it's up to you but we just take the it's up to you but we just take the length of the string have a right length of the string have a right pointer that's going to go character by pointer that's going to go character by character through the input string we character through the input string we also though have a left pointer I'm also though have a left pointer I'm going to declare it up here it's going going to declare it up here it's going to initially be zero and we're also to initially be zero and we're also going to have a couple more variables going to have a couple more variables the count and the result so those are the count and the result so those are also initially going to be zero now as also initially going to be zero now as we go character by character we know we we go character by character we know we want to add one to the count if our want to add one to the count if our character at index R is a vowel character at index R is a vowel character so if this is in our vowel set character so if this is in our vowel set and I'm actually just going to change it and I'm actually just going to change it to vowel just to make it a little bit to vowel just to make it a little bit shorter but if it's not in the vowel set shorter but if it's not in the vowel set of course we want to do nothing so I of course we want to do nothing so I would just put 0 here which basically would just put 0 here which basically adds zero to count basically not doing adds zero to count basically not doing anything and of course we want to update anything and of course we want to update our result we want to set it to the max our result we want to set it to the max of the result and the count and you of the result and the count and you might think that's pretty much it and might think that's pretty much it and then we can go ahead and just return the then we can go ahead and just return the result but not quite because remember we result but not quite because remember we forgot about a parameter here K our forgot about a parameter here K our window can't be any bigger than K so window can't be any bigger than K so before we even try to take the result before we even try to take the result let's make sure we have a valid window let's make sure we have a valid window what happens if our window is invalid what happens if our window is invalid well the lengths would be bigger than K well the lengths would be bigger than K how do we get the length we can take the how do we get the length we can take the right index minus left plus one that right index minus left plus one that gives us the length of the window if you gives us the length of the window if you don't believe me try it out on an don't believe me try it out on an example prove it to yourself so this is example prove it to yourself so this is the length if it's bigger than k then the length if it's bigger than k then the window is simply too large we have the window is simply too large we have to make it smaller just by A Single to make it smaller just by A Single Character so we want to shift r our left Character so we want to shift r our left pointer by one you might think we want pointer by one you might think we want to shift our right pointer but we're to shift our right pointer but we're already doing that with the for Loop already doing that with the for Loop that's kind of why I like to code it up that's kind of why I like to code it up this way but again you can kind of feel this way but again you can kind of feel free to switch it up how you like don't free to switch it up how you like don't forget we don't just need to update the forget we don't just need to update the left index we also have to update the left index we also have to update the count because as we remove characters count because as we remove characters from our window we possibly want to from our window we possibly want to decrement the count by one so if the decrement the count by one so if the character at index left the reason I'm character at index left the reason I'm putting this line before the putting this line before the incrementioned by the way by before incrementioned by the way by before incrementing is because of course we incrementing is because of course we want to use the original left index want to use the original left index before we shift it we want to know was before we shift it we want to know was this character a vowel so is this in this character a vowel so is this in vowel if it's not just add zero or just vowel if it's not just add zero or just decrement zero which doesn't do anything decrement zero which doesn't do anything of course so this is the sliding window of course so this is the sliding window approach for this problem let's run it approach for this problem let's run it to make sure that it works and as you to make sure that it works and as you can see yes it does and it's pretty can see yes it does and it's pretty efficient if this was helpful please efficient if this was helpful please like And subscribe if you're preparing like And subscribe if you're preparing for coding interviews check out neat for coding interviews check out neat code.io it has a ton of free resources code.io it has a ton of free resources to help you prepare thanks for watching to help you prepare thanks for watching and I'll see you soon | 2024-03-21 02:46:17 | 1,456 | Maximum Number of Vowels in a Substring of Given Length - Leetcode 1456 - Python |
|
MdhHLUJTcws | welcome to part two of leeco the day keeps the dances away high script keeps the dances away high script edition we're gonna be solving lead code edition we're gonna be solving lead code questions using typescript and now as questions using typescript and now as always i'll be showing you guys multiple always i'll be showing you guys multiple solutions to the same problem solutions to the same problem and this one is add two numbers if this and this one is add two numbers if this is your first time on this channel uh i is your first time on this channel uh i do these lethal type of questions time do these lethal type of questions time to time i'm only on the second one uh it to time i'm only on the second one uh it is my goal to get through all of these i is my goal to get through all of these i don't know if that's possible but we'll don't know if that's possible but we'll try especially if you guys like this try especially if you guys like this content by clicking like and subscribing content by clicking like and subscribing to my channel that will help me tons but to my channel that will help me tons but i'm going to be going through these and i'm going to be going through these and my goal is to make the most in-depth my goal is to make the most in-depth tutorial for these tutorial for these in youtube in youtube quick interjection here if this is your quick interjection here if this is your first time attempting a singly linked first time attempting a singly linked list question i do have a very list question i do have a very comprehensive a deep dive into comprehensive a deep dive into singly linked lists uh this is my data singly linked lists uh this is my data structures and algorithm series in structures and algorithm series in javascript and typescript so please javascript and typescript so please check that out if you haven't done so check that out if you haven't done so already already so let's read this question and then so let's read this question and then i'll have you guys pause the video try i'll have you guys pause the video try it on your own and then come back to me it on your own and then come back to me and i will show you the multiple and i will show you the multiple solutions that i have come up with solutions that i have come up with add two numbers you are given two add two numbers you are given two non-empty linked lists representing two non-empty linked lists representing two non-negative integers non-negative integers the digits are stored in reverse order the digits are stored in reverse order and each of their nodes contain a single and each of their nodes contain a single digit digit add the two numbers and return the sum add the two numbers and return the sum as a linked list as a linked list you may assume the two numbers that you may assume the two numbers that contain any leading zero except the contain any leading zero except the number zero itself so there was a lot of number zero itself so there was a lot of nuggets in there um let's look at the nuggets in there um let's look at the example first 243 564 that would somehow example first 243 564 that would somehow give us 708 give us 708 and let's remember what they have said and let's remember what they have said so the digits are stored in reverse so the digits are stored in reverse order so this 243 is going to be 342 order so this 243 is going to be 342 and this 564 linked list is going to be and this 564 linked list is going to be 465. so what is 342 plus 465 that ends 465. so what is 342 plus 465 that ends up becoming 807 up becoming 807 and if you reverse 807 that will give and if you reverse 807 that will give you 708. so that should give you the you 708. so that should give you the linked list of seven linked list of seven zero eight zero eight uh there's a couple other things to keep uh there's a couple other things to keep in mind is we are given two non-empty in mind is we are given two non-empty linked lists meaning this l1 and rl2 linked lists meaning this l1 and rl2 will never be null so i don't know why will never be null so i don't know why they typed it like here they typed it like here also they're stored in reverse order as also they're stored in reverse order as we said uh these are representing we said uh these are representing representing two non-negative integers representing two non-negative integers they will never be negative they will never be negative and the nodes all contain a single digit and the nodes all contain a single digit meaning we're never gonna have something meaning we're never gonna have something like 12 here or like negative 5 here or like 12 here or like negative 5 here or negative 24 anything like that they're negative 24 anything like that they're all single digits another thing that all single digits another thing that helps us out is you may assume that two helps us out is you may assume that two numbers do not contain any leading zero numbers do not contain any leading zero except the number zero itself meaning except the number zero itself meaning we're not going to have extra zeros here we're not going to have extra zeros here to just pad the number because that's to just pad the number because that's essentially the same thing as 342 right essentially the same thing as 342 right so that is this first question now so that is this first question now please pause the video try this on your please pause the video try this on your own and come back to this to show to own and come back to this to show to look at my look at my solutions all right so the first way i'm solutions all right so the first way i'm gonna solve this is gonna solve this is we are gonna make a function first that we are gonna make a function first that gets a list node like this gets a list node like this and gets the list node like this and gets the list node like this and produces the correct number out of and produces the correct number out of them so this them so this function is gonna take this link uh list function is gonna take this link uh list node linked list or whatever and give us node linked list or whatever and give us 342 meaning it's gonna give us the 342 meaning it's gonna give us the digits in reverse and it's gonna give us digits in reverse and it's gonna give us from here for from here for 65. 65. so our first objective is to make a so our first objective is to make a function that gives us the correct function that gives us the correct number in the number type number in the number type of for uh the two linked lists that we of for uh the two linked lists that we have and then we're going to add these have and then we're going to add these together together we're gonna add these together and then we're gonna add these together and then spit out the digits back in the reverse spit out the digits back in the reverse order as a linked list so that's our order as a linked list so that's our objective let us go to our editor now i objective let us go to our editor now i have a code sandbox open here have a code sandbox open here let me just zoom in here a little bit let me just zoom in here a little bit copy this i've already copied the list copy this i've already copied the list node class here so that the typescript node class here so that the typescript won't complain to us whenever we define won't complain to us whenever we define it like this it like this and a couple important things to keep in and a couple important things to keep in mind they told us that we are given two mind they told us that we are given two non-empty linked lists meaning the way non-empty linked lists meaning the way that they typed it is not actually that they typed it is not actually correct because they're giving us correct because they're giving us they're saying that l1 is is either list they're saying that l1 is is either list node or null and l2 is either this node node or null and l2 is either this node or no or no that's not correct they should actually that's not correct they should actually only be a list node they can never be only be a list node they can never be known and because of that because we're always gonna have something for l1 and l2 that means we could always add something and our output should never be no either so let's get that out of here too now we have the correct type and as i have said where first our first goal is to make a function that takes in a link a linked list and spits out the number in the correct order so i'm just gonna define it as a function out here so what should we call this we will say uh get number from list and this will take a list as an argument which is a list node and it will spit back out to us a number like so and this function as i said we're going to be end up calling it for both l1 and l2 so what can we do to get this singly linked list as a number all right so in the beginning let's not worry about the fact that these are in the reverse order let's just worry about putting these into making this into a 243 now i got a question for you guys is it easier to make this 243 as a number or as a string um to make it a number how do you get the numbers 2 and number 4 and make them 24. it's easier to get the string to string 4 and then concatenate them together to get the string 24 right so that's what we're gonna do here so let us do this let a number in reverse order i'm just going to be explicit that this is explici uh in reverse order so that we remember to put it in the proper order afterwards and this is going to be a string type and we will instantiate it as an empty string because we're already instantiating as mp string here we don't need this typing so we'll just let typescript infer it and then we are gonna use the runner method to run through this linked list and grab each value until the runner uh is that null so let's define the runner that runner be the list it starts from the beginning of the list and we are going to do a while loop so while runner exists what do we want to do while the runner exists we want to append to this number in reverse order string the value that the runner contains in the string format so the way we are going to do that is number in reverse we if i could spell correctly reverse order we are going to add to that the um runner dot val which is a digit and we just wanna to string this to make sure that it stays as a string and then after we have added that value the current node is no longer use of use to us so we're just gonna set runner equals runner dot next he's gonna keep on going until he gets to the end and right now typescript is complaining to us because runner.next could also become null right but for this three as an example his next is no so we type the runner incorrectly or right now runner thinks his type is only a list note because that's what we pass as a list but the type of runner can be either a list note or null because at the end it's gonna become null the typescript is no longer complaining to us and now we should have had the correct number in reverse order as a string so now we want to make this into the proper order and the way that i do that is i'm feeling a little bit lazy so i'm going to be using a bunch of javascript methods that it provides us so one easy method that i know on how to reverse things is an array an array has a method called reverse that reverses the array so i'm just gonna convert the number in reverse order into an array i'm gonna store the result of whatever i'm gonna do as the output so this should give us the final number so first we are going to get the number in reverse order we are gonna make it into an array the easiest way to make a string into an array is just by splitting it at every single character that will give us two comma four comma three as an array and then now that it is an array we could just reverse it like so now it will give us 3 comma 4 comma 2. and after we have reversed it our usefulness of arrays are done so we're going to join it back to a string so now it becomes 342 and we just want and this is going to be our output and this is going to be our output um i forgot a parenthesis here um i forgot a parenthesis here so and we want to return this output so and we want to return this output right so we could either put a return right so we could either put a return output here or just erase this and output here or just erase this and return it straight away from here return it straight away from here like so like so so here is our get number from list so here is our get number from list let's think about the um time complexity let's think about the um time complexity of this of this so let's take a look we are running so let's take a look we are running through each of the list each of the through each of the list each of the nodes in the list that's o to the end nodes in the list that's o to the end operation operation we also are doing this split a reverse we also are doing this split a reverse and join and join uh i don't really know the upper o to uh i don't really know the upper o to the m for reverse but i believe it's o the m for reverse but i believe it's o to the n to the n so this is something like o to the 2n so this is something like o to the 2n operation uh one way we could speed this operation uh one way we could speed this up is not doing this whole reverse thing up is not doing this whole reverse thing and when we and when we instead when we uh formulate the string instead when we uh formulate the string we we add it in the proper order so let me do add it in the proper order so let me do a couple refactoring now to this a couple refactoring now to this remember what remember what we were remember what remember what we were doing here we were adding each value of doing here we were adding each value of the node to the end of our previous the node to the end of our previous string right instead of doing that why string right instead of doing that why don't we just add it to the front of the don't we just add it to the front of the string every single time string every single time the way that i am going to do that is the way that i am going to do that is i'm going to refactor this and i'm going i'm going to refactor this and i'm going to call this call this just number to call this call this just number string string then then get this get this number string i know this is incorrect number string i know this is incorrect right now right now but let me just do the refactor first we but let me just do the refactor first we don't need to do this split reverse join don't need to do this split reverse join trap again so we are just going to call trap again so we are just going to call this this type return the typecast of number a type return the typecast of number a number string number string and if we fix this this should work so and if we fix this this should work so instead of appending the value to the instead of appending the value to the end of the string like this what we are end of the string like this what we are going to do instead going to do instead is we are going to set the number string is we are going to set the number string get the value first put that in the get the value first put that in the beginning and then add the rest of the beginning and then add the rest of the number string number string like so like so and what that would do is first we have and what that would do is first we have to to let me get my pen out so let me just let me get my pen out so let me just show you guys what is going on here with show you guys what is going on here with this example we first start out as this example we first start out as an empty string number string is an an empty string number string is an empty string empty string we run through it we first start with we run through it we first start with two two so the empty string now becomes two so the empty string now becomes two like this like this and then we go to the next node which is and then we go to the next node which is four four our number string still stays as two but our number string still stays as two but we are appending to that in the we are appending to that in the beginning beginning the next value which is 4 the next value which is 4 like so so that becomes what 42 and then to our 42 at the end once we are at 3 we are adding 3 to that to the beginning which gives us a string 342 so that's essentially what we are doing here this is a bit more performant than the other solution because we don't need to do the whole reverse split join stuff instead we are just this is a strictly o to the end operation and now just for fun i'm going to show you guys one more solution on how to do this that involves a little bit of math i'm not gonna stick with this solution uh for reasons i will explain later but i just wanted to show you guys notice what we're doing here we are getting our number string as a string and then typecasting as number so there is a way to do this without doing the type test where our output stays as a number and we just return that so because i'm not going to use it i'm just going to copy this code here bring it down here and what i'm going to do is i'm going to say let output let's let the output start out as zero and let's just get uh actually let's just keep this and we don't need to typecast anymore we're just gonna return the output so what we are gonna do is this let me just write out the solution first and then i'll explain what's going on first uh after i mean so i'm gonna have another variable here called index and i'm gonna start that out as an index as zero and that will pretty much be the index of each of these elements uh imagining this list node as linked list as an array so what i'm to do here we're still going to be up adding the whatever value that we get at the beginning kind of like this previous solution and of adding that to the previous number except this time is the output right and this should also be the output instead of doing this string addition we are going to do addition by actual numbers and the way that i'm going to do that is this we are going to get the runner.value which is a number times math.power of 10 to the index power and then we're going to add that to the output that will somehow give us the solution runner is equal to runner.next i also want to increment our index so why the heck does math.power of doing this work let me guys show you what's going on so at the very beginning our runner dot value is 2 right so we have 2 times 10 to the what's our index right now is 0 power plus the output i'll put started out as 0 as you guys can see here what's 10 what's anything to the zero power that's one so this gives us two times one plus zero which is two and then we go to our next node which is four so we have 4 runner.value times 10 to the times 10 to the first power plus our previous output which was 2 what's 10 to the 1 power that is just 10 10 times 4 4 is 40 and that gives us 42 and notice what is happening right we are getting the number the next number is 3 times 10 to the 2 plus our previous number which is 42. uh 3 times 10 to 10 to the 2 is 100 so 100 times 3 is 300 300 plus 42 is 342 and that is the number that we want so that's why this works however i'm not gonna stick with this solution uh and i'll explain that will be more clear later so let's just erase this neat solution that we have here and stick with this solution for now where we are just adding it to the beginning the string and then returning the number form of it later so we have beaten this get number from list function to def let's get to the actual problem of adding the two numbers the actual main meat of the problem and we are just gonna call this get number from list twice so we're gonna say const number one n1 is equal to get number from list of l1 and const n2 is get number from list of l2 so that will give us the two numbers and what do we want to do with the two numbers we want to add them together so all right so this sum now should be all right so this sum now should be for this example it should be 807 for this example it should be 807 because that's the number of adding 342 because that's the number of adding 342 and 465. and 465. so how do we get from 807 so how do we get from 807 to become the linked list that is 7 to become the linked list that is 7 uh 0 uh 0 8 8 so how can we do this so first what we so how can we do this so first what we want to do is somehow iterate through want to do is somehow iterate through each of the digits on the sum each of the digits on the sum and form a linked list for each one and and form a linked list for each one and the way that i am going to do that is the way that i am going to do that is let's just pretend that we have made let's just pretend that we have made this iterable and there's actually a this iterable and there's actually a very easy way to do that just make it very easy way to do that just make it back to a string because strings are back to a string because strings are iterable iterable so once we have so once we have made this to a string we're gonna made this to a string we're gonna iterate through each of the digits iterate through each of the digits specifically eight zero and then seven specifically eight zero and then seven and this is what we're gonna do once we and this is what we're gonna do once we get to the first digit we will create get to the first digit we will create a list node that points to nothing a list node that points to nothing we're gonna go to the next digit we're gonna go to the next digit and then create a list node and then create a list node that points to the list node that we that points to the list node that we have graded previously like so have graded previously like so and we're just gonna continue this and we're just gonna continue this process until we get seven that leads to process until we get seven that leads to zero that leads to eight so let's go to zero that leads to eight so let's go to our editor now and try to implement that our editor now and try to implement that so as i've said we're gonna first make so as i've said we're gonna first make it into a string it into a string enhanced some string enhanced some string is equal to sum is equal to sum to string to string or to be short why don't we just or to be short why don't we just get this addition here get this addition here and just to string it right away that and just to string it right away that way we don't even need a sum string way we don't even need a sum string all right so now let's iterate through all right so now let's iterate through every single digit on the sum so we will every single digit on the sum so we will do four do four let i is zero i is less than some dot let i is zero i is less than some dot length length it's a typical it's a typical for loop for loop and let's just grab the digit that we and let's just grab the digit that we want right away that we don't have to want right away that we don't have to deal with anymore so const digit is deal with anymore so const digit is going to be the sum at the current index going to be the sum at the current index and now and now as i've said before we have to make a as i've said before we have to make a list node with our first digit so our list node with our first digit so our first digit here is seven first digit here is seven and the way that i am not actually i'm and the way that i am not actually i'm sorry it should be eight because our the sorry it should be eight because our the number that we have for this sum is 807 number that we have for this sum is 807 right right and we want to return the result of all and we want to return the result of all of this at the end so how about we of this at the end so how about we instantiate that in the variable here so instantiate that in the variable here so we'll say let we'll say let output which is going to be a list node output which is going to be a list node is not going to be null but i'm going to is not going to be null but i'm going to type it as null for now because we're type it as null for now because we're going to have it started out as not now going to have it started out as not now because we're always going to go with because we're always going to go with this for loop and we're going to put this for loop and we're going to put something here it's not going to be something here it's not going to be known any longer but for now because we known any longer but for now because we want to initially be null we'll just set want to initially be null we'll just set it as null and this is what we'll do it as null and this is what we'll do let output be equal to a new list node let output be equal to a new list node we're going to create a new list node we're going to create a new list node what is the first argument of list node what is the first argument of list node it is the value it is the value and the second argument is the next and the second argument is the next so the value is very easy it's just so the value is very easy it's just going to be the digit except the digit going to be the digit except the digit right now is a string so if we just right now is a string so if we just leave it like this typescript's gonna leave it like this typescript's gonna error out so instead we will just error out so instead we will just typecast it like so and what should our next be our first digit which was an eight should have a next of nothing but once we go to the next digit it's next should be the previous output right so why don't we just put output here like so so what will happen is we've create eight that has a next two null because it starts out as null then we create zero that has a next of the previous one which was the linked list with eight then we create seven that has a next to zero and this should work so at the end we could return output now typescript is going to complain to us because we have typed the output as listnode or null uh we only did this because we want to have it started out as no but it becomes a list node at the end and we know we're always going to go through this for loop at least once so we could just a piece typescript right now by saying return so this should give us the correct so this should give us the correct answer answer let us copy this let us copy this both functions get number from list and both functions get number from list and the attitude numbers just make sure you the attitude numbers just make sure you don't copy this class list note don't copy this class list note paste it here paste it here and if you run the code let me just zoom and if you run the code let me just zoom in here if you run the code here it in here if you run the code here it should pass should pass so this has passed now if we submit now so this has passed now if we submit now we're gonna see something very we're gonna see something very interesting and it's gonna fail and as interesting and it's gonna fail and as you can see it has failed in this you can see it has failed in this ridiculous test case where one of the ridiculous test case where one of the input is like one zillion one there is a input is like one zillion one there is a reason why this is failing and it's reason why this is failing and it's because we are converting these two because we are converting these two numbers at the end and we are trying to numbers at the end and we are trying to add the two numbers here so what is add the two numbers here so what is going on is going on is look at this function here get number look at this function here get number from list imagine passing this argument from list imagine passing this argument here this list here into the get number here this list here into the get number from this then it's gonna attempt to from this then it's gonna attempt to create a javascript number that is like create a javascript number that is like one zillion one but there is a problem one zillion one but there is a problem because in javascript's number type because in javascript's number type there is a maximum uh integer that the there is a maximum uh integer that the number can be and that is specifically number can be and that is specifically this right here let me zoom in real this right here let me zoom in real quick so that you guys can see quick so that you guys can see this is the maximum safe integer that this is the maximum safe integer that the number type can be and beyond this the number type can be and beyond this it is no longer safe and you're going to it is no longer safe and you're going to run into errors like the air that we are run into errors like the air that we are seeing here seeing here and what they recommend is for larger and what they recommend is for larger and larger integers consider using and larger integers consider using bigent so bigint is a new type that was bigent so bigint is a new type that was introduced to javascript couple years introduced to javascript couple years ago i believe like two or three years ago i believe like two or three years ago ago i did have a video that covers it but i did have a video that covers it but that is what we should be using instead that is what we should be using instead to uh get around this overflow here to uh get around this overflow here so we will refactor our solution to use so we will refactor our solution to use a big in instance so this should no a big in instance so this should no longer be returning a number but rather longer be returning a number but rather it should be returning a big end all in it should be returning a big end all in lower case lower case and let's see what else we have to do and let's see what else we have to do instead of type casting the number instead of type casting the number string as a number string as a number let us typecast it as not typecast but let us typecast it as not typecast but create an instance of a big end like so create an instance of a big end like so this is the javascript method it cannot this is the javascript method it cannot accept a string and it will convert that accept a string and it will convert that string to a bigit string to a bigit so so now that we have done that if you look now that we have done that if you look if you look let's go back to our editor if you look let's go back to our editor so that we have code completion so that we have code completion let me copy this code and come back over here if you hover over our n1 now it is a big if you hover over our n1 now it is a big end if you hover over on two is a big it end if you hover over on two is a big it and the sum of that and the sum of that was a big end was a big end i i wonder if you could see that but we i i wonder if you could see that but we have converted that to a string but this have converted that to a string but this all still works at this solution now all still works at this solution now should should pass all of our tests so i don't think i pass all of our tests so i don't think i made any changes so we could just submit made any changes so we could just submit this as is let us run the code first this as is let us run the code first that is passes and let's submit this that is passes and let's submit this time time and it is a success and it is a success so our run time was 107 milliseconds so our run time was 107 milliseconds which was 95.5 which was 95.5 percent of thai script percent of thai script which is pretty fast i'm actually which is pretty fast i'm actually shocked by this because i didn't get shocked by this because i didn't get this in my first attempt but regardless this in my first attempt but regardless this is a solution now this is a solution now let me let me come up with a solution that is come up with a solution that is a different than this one so let's think a different than this one so let's think about the on about the on time complexity here time complexity here what we did here this get number from what we did here this get number from list is o to the n where n is the length list is o to the n where n is the length of the list of the list and we are calling this twice and we are calling this twice and then and then we are iterating through each of the we are iterating through each of the digits digits and making a new list node so it's o to and making a new list node so it's o to the 2n of is technically the 2n of is technically the time complexity of this is o to the the time complexity of this is o to the this o to the this o to the n n plus m plus digits where n is the length plus m plus digits where n is the length of l1 m is the length of l2 of l1 m is the length of l2 and d is the length of the digits and d is the length of the digits which i believe should be which i believe should be the the addition of these so it's either addition of these so it's either the uh the greater of these two or the the uh the greater of these two or the greater of these two plus one i believe greater of these two plus one i believe that that's how the amount works let's that that's how the amount works let's see 99 plus 99 yeah nine and then if you see 99 plus 99 yeah nine and then if you do 99 plus 99 that gives you like 100 do 99 plus 99 that gives you like 100 something so three digits so it's either something so three digits so it's either the max of these or the max of these the max of these or the max of these plus one plus one so that is our time complexity here so that is our time complexity here let's see if we could reduce the time let's see if we could reduce the time complexity complexity by solving this solution in a different by solving this solution in a different fashion so let me just reset our board fashion so let me just reset our board here here there we go and i'm gonna copy this back there we go and i'm gonna copy this back to my editor to my editor here here let's erase these two functions that we let's erase these two functions that we have created have created and paste it here while keeping our list and paste it here while keeping our list node still here so that typescript node still here so that typescript doesn't complain to us the fact that we doesn't complain to us the fact that we are using it all right so how we are are using it all right so how we are going to solve this one is a little bit going to solve this one is a little bit tricky but i think you guys can follow tricky but i think you guys can follow along and what we are going to do is we along and what we are going to do is we are going to be creating our output are going to be creating our output or singly linked list or singly linked list as we iterate to each of the digits for as we iterate to each of the digits for both lists so we're gonna start with a both lists so we're gonna start with a runner that points to this two runner that points to this two a runner that point another runner that a runner that point another runner that points to this five points to this five add them together and create a new list add them together and create a new list node that is seven here node that is seven here and then we're gonna run to the next one and then we're gonna run to the next one add these two and put it here but add these two and put it here but there's a little problem right four plus there's a little problem right four plus six is ten but we want to only add zero six is ten but we want to only add zero here and do something with that one here and do something with that one later so what we can do is i don't know later so what we can do is i don't know if you guys remember from your basic uh if you guys remember from your basic uh arithmetic classes in like elementary arithmetic classes in like elementary school you carry that one over to the school you carry that one over to the next one right so that's what we're next one right so that's what we're going to do if our thumb of our two going to do if our thumb of our two digits is greater than 10 digits is greater than 10 or greater or equal to than 10 we are or greater or equal to than 10 we are going gonna get the one extra and bring going gonna get the one extra and bring it over to the next number so we're it over to the next number so we're gonna put zero here and add one either gonna put zero here and add one either to this three or to this four it doesn't to this three or to this four it doesn't matter you just have to pick one and add matter you just have to pick one and add one so let's just pretend that this has one so let's just pretend that this has become four so four plus four is eight become four so four plus four is eight and we are going to do that on the spot and we are going to do that on the spot and that should give us the output and that should give us the output so let us attempt to do that and as i've so let us attempt to do that and as i've said we're gonna have a runner that goes said we're gonna have a runner that goes through each one each of the lists so through each one each of the lists so i'm just gonna define them here i'm just gonna define them here let let r1 r1 that is going to be l1 that is going to be l1 and that r2 is going to be l2 and that r2 is going to be l2 and and i know that technically these and and i know that technically these shouldn't be null as i said before but shouldn't be null as i said before but whatever we'll just keep it as it is whatever we'll just keep it as it is not a big deal and then we are also not a big deal and then we are also gonna have an output here on output that gonna have an output here on output that we're gonna return at the end which is we're gonna return at the end which is going to be a list node or null going to be a list node or null technically it's not going to be no but technically it's not going to be no but we're going to instantiate it as no uh do i want to do this actually i don't want to do this i do want to not start it as null but let's have it start out as a new list node where we're gonna pass in the value of it later so i'm actually to erase this type in here get rid of that and then we're going to do some magic in between line 14 and 15 and at the end we're going to assume that the output is correctly formatted and just return the output so the magic will cut uh in between and what we are going to do is this while how long should we let this a while loop run while the rudder one and runner two runs we want this to continue until as long as r1 exists or r2 exists we want this loop to run and the reason why i'm doing this or is because the two lists can be of different lengths so for example here in this example l1 is greater than l2 so there will come a point when r1 is running at a number that um where r2 is pointing to null so we still want to keep on running still keep on adding the two numbers treat these empty digits as just zero keep on adding them together and just uh uh return the output at the end so let us do that right now let's get these some other digits i'm going to put that in a left variable for a reason i'll explain it it'll be clear later we'll add up the digits the values of the two runners right now and that should be our digit r1 value or r2 that value now typescript is complaining to us correctly because and there should be two signs r1 or r2 can be no and that's why you can't put get that value of null so what we have to do is if this exists we're gonna use optional chaining if this exists gives us the value or just use zero and we are going to do the same thing here and for those who are not familiar with this operator this optional chaining operator this is essentially the same thing as r1 so we'll just keep it concise and do so we'll just keep it concise and do this this so that will give us the digit but we so that will give us the digit but we have to consider the case where the have to consider the case where the digit is greater than 10. digit is greater than 10. and for that case and let's just think and for that case and let's just think about it what's the greatest number that about it what's the greatest number that this could possibly be let's pretend this could possibly be let's pretend that these two were nine and nine right that these two were nine and nine right and this was nine and nine so we did and this was nine and nine so we did nine plus nine and 18 we carry the 1 nine plus nine and 18 we carry the 1 over one of these becomes 10 so it's 10 over one of these becomes 10 so it's 10 and 9 10 and 9 is 19. and 9 10 and 9 is 19. so the greatest that this digit can ever so the greatest that this digit can ever be is 19 meaning be is 19 meaning if we are ever if we are ever in this scenario if the digit is greater in this scenario if the digit is greater or equal to 10 or equal to 10 then we know that the digit that we're then we know that the digit that we're gonna carry over has to be a one it will gonna carry over has to be a one it will never be greater than one never be greater than one so we could do something simple here so we could do something simple here what i'm gonna do is what i'm gonna do is i'm gonna first subtract the 10 from the i'm gonna first subtract the 10 from the digit to make the digit to be a proper digit to make the digit to be a proper digit let's do that right now digit is digit let's do that right now digit is going to be going to be we're subtracted by 10 and we're gonna we're subtracted by 10 and we're gonna do some other magic here to carry over do some other magic here to carry over magic here magic here let's just pretend that that is done and let's just pretend that that is done and we are outside of the if loop our digit we are outside of the if loop our digit if it was greater or equal to 10 is now if it was greater or equal to 10 is now back to a single digit or if it was back to a single digit or if it was never a two-digit number to begin with never a two-digit number to begin with we're just out here because we never we're just out here because we never entered this if condition what do we entered this if condition what do we want to do with that digit we want to want to do with that digit we want to add it to this list node on the output add it to this list node on the output so the way that we are going to do that so the way that we are going to do that is this is this output output that value that value is going to be the digit is going to be the digit and then we want our and then we want our output to go to the next one but this is output to go to the next one but this is where it gets tricky once we start re where it gets tricky once we start re uh reassigning what the uh output is uh reassigning what the uh output is pointing to when we return here we're pointing to when we return here we're going to be pointing to the last node going to be pointing to the last node that we created so we don't want to run that we created so we don't want to run with the output as a matter of fact with the output as a matter of fact instead we want to have a runner of the instead we want to have a runner of the output so let's just call that output so let's just call that um what should we just call let's just um what should we just call let's just call it runner call it runner of the output of the output like this and the type of this can be like this and the type of this can be list node or no list node or no so we're never going to be doing like so we're never going to be doing like output equals output.next because we output equals output.next because we want to keep the reference of the want to keep the reference of the original output original output and instead and instead let's do this instead of saying the let's do this instead of saying the output.value of digit we're going to set output.value of digit we're going to set the runner the runner that value is going to be the digit and that value is going to be the digit and just like we have created a new list just like we have created a new list node here if we need to create the next node here if we need to create the next list node let's do that in this first list node let's do that in this first iteration before we go to the next one iteration before we go to the next one and one is a scenario when we should and one is a scenario when we should create a new list though for the next create a new list though for the next one is if r1 exists and it has a next or if r2 exists and it has an x as long as one of these two has a next then we know that we need one more additional digit so let's just do that right now runner down next is going to be a new list node and then we're gonna set runner is equal to runner down next and it just auto completed a question and it just auto completed a question mark for me because it could also be mark for me because it could also be null um can it be no not necessarily because we have just typed it as a new list note here but typescript doesn't know that so we'll let that be and then we also have to let our r1 and r2 run right so let's do that but they could they should only run to the next node if they are not null to begin with so let's do that here if r1 then set r1 is equal to r1.x which may very well be null but that's fine if r2 r2 is going to be r2 down next so we are gonna keep on iterating over adding the digits doing some magic that carry over the one keep on doing that until we get to the end and at the end we could return the output who has started out as this empty list that we have populated uh here so now let us uh take care of this magic that is going on here that is if the digit that we have added together is greater or equal to 10 we have to carry over the one so this is gonna be a bit tricky to do and i'm gonna do this if r1 exists and it's next exist then just add it here add it to that one r1 the nexus val is going to be added by one like so that may not be the case maybe for r1 we are at the imagine this was l1 we are at the end of the line and but for l2 there is more next of values to exist then then r2 that next stop now then r2 that next stop now gets incremented by one gets incremented by one and let's put our l-sit here and let's put our l-sit here because we don't want we only want to because we don't want we only want to add one once add one once but these two now also might not be the but these two now also might not be the scenario scenario they both might not have an x meaning they both might not have an x meaning what if for this case what if for this case uh uh two plus four no no let's imagine this two plus four no no let's imagine this was like uh six right here right 6 plus was like uh six right here right 6 plus 4 is 10. we want to carry that one over 4 is 10. we want to carry that one over but neither of them have a next so let's but neither of them have a next so let's do this else if if r1 exists then we could make have it have a next then r1 done next is going to be a new list note this time because it didn't it didn't have a list now before and we're just going to set the value to one else it r2 because maybe r1 was already known and we just had to add it to r2 then r2.next is going to be a new list node with one and these four scenarios will actually take care of all scenarios whenever we hit this because we know that r1 or r2 at least one of them has to exist so worst case scenario is gonna hit this or it's gonna hit this it's never gonna pass on all of these if statements because of this fact right here so this should give us the correct solution now let us copy this and bring over to our lead code like so copy and paste it let's run the code for now to see if it passes and the reason why it failed is i did and the reason why it failed is i did something incredibly stupid something incredibly stupid uh you guys probably caught this uh you guys probably caught this hopefully hopefully this digit right here should have been a this digit right here should have been a plus plus like so like so let me go back here we are adding the let me go back here we are adding the two digits together not ordering it and two digits together not ordering it and that's why it gave us the first list that's why it gave us the first list because if you do something or this it because if you do something or this it will always give you the first one as will always give you the first one as long as that is true long as that is true so now this should work so now this should work yep it passes down let's submit yep it passes down let's submit and it passes so we got and it passes so we got 254 milliseconds 254 milliseconds um which was actually slower than the um which was actually slower than the other one i was expecting this one to be other one i was expecting this one to be faster faster uh however uh however we ended up using more memory we ended up using more memory um this is very inconsistent i noticed um this is very inconsistent i noticed like before when i did this this like before when i did this this solution was much faster than my first solution was much faster than my first solution solution so this is not 100 reliable i don't so this is not 100 reliable i don't think but either way those were the two think but either way those were the two different ways that we could solve this different ways that we could solve this add two numbers problem add two numbers problem so hope you guys like this uh if you so hope you guys like this uh if you guys like this content please like this guys like this content please like this video to let me know that uh you want video to let me know that uh you want more of it and uh when the time comes i more of it and uh when the time comes i will be submitting a part three of this will be submitting a part three of this lead code a day keeps the dentist away lead code a day keeps the dentist away so please stay subscribed subscribe to so please stay subscribed subscribe to my video subscribe to my channel i mean my video subscribe to my channel i mean and i will see you guys next time | 2024-03-18 10:03:44 | 2 | Leetcode in Typescript - 2. Add Two Numbers |
|
daDa5ycsdi0 | let's solod 1,804 Implement CH two and for this 1,804 Implement CH two and for this question give us to uh ask us to question give us to uh ask us to implement a CH structure and implement a CH structure and uh we need to implement uh the uh we need to implement uh the insert uh count insert uh count Words uh equal to that means Words uh equal to that means um we need to count how many times we um we need to count how many times we insert this word into our data structure insert this word into our data structure um and also counts start with the prefix um and also counts start with the prefix that means we need that means we need to um count what those kind of uh uh to um count what those kind of uh uh perefect how many how many uh we already perefect how many how many uh we already insert and also we need we have a insert and also we need we have a erase uh method we need to um Implement so for this question um we we also the same thing as a implemented child one the difference is that um we need to have two type of counts in the child node class and uh so we have node um children and post we have in in prefix count C zero and uh uh po count it's also equal to count it's also equal to there uh in our uh Constructor public uh there uh in our uh Constructor public uh class class public channnel I have children equals new 26 and also we are have prefix count 26 and also we are have prefix count equals z and word count equals to there equals z and word count equals to there so um we're going to have a Roth so um we're going to have a Roth here here no root and root equals new Char Noe so no root and root equals new Char Noe so for insert we have a cursor here let for insert we have a cursor here let that is Char node curent that is Char node curent equals roots and then for equals roots and then for every uh CH character say word um to char um so let's say if uh current children um a minus a equals now right now then we have I [Music] children children um C minus um C minus a uh equals new and uh so if it is just a new one right new one um if this is a a new one means uh this prefix counts um is zero word count is zero right so uh as long as we we this default default value there we go to this uh uh no current equals current do CH as last will go to this node uh that means uh it's prefix and prefix or add one right uh whether the word count I one depends on whether uh it finished so we have current. prefix count uh Plus+ okay and when this finish we have account um so now account um so now um let's try to see count the words right um so what we're going to do is that uh we're going to use a Char node current equals root and for character say in word to to char okay so we say if current do children uh say minus a uh equals not that means we didn't insert in this kind of pass we has to return zero right otherwise we're going to have a current equals current um when it finish we just need to return um when it finish we just need to return current word current word accounts right and uh for prefix count accounts right and uh for prefix count is is similar um do uh just um return prefix count not what count should be perix counts and then to so to so um you say that it's granted that erase um you say that it's granted that erase uh the word uh the word well exist in the chart so it prob be well exist in the chart so it prob be kind of straightforward right so we just kind of straightforward right so we just uh do the reverse operation as insert uh do the reverse operation as insert and then we don't need to charge this and then we don't need to charge this one right um we just um almost the same one right um we just um almost the same code but we use some code but we use some uh minus uh minus minus so it say that the try always minus so it say that the try always exist right if it does if it don't have exist right if it does if it don't have that condition we should return return that condition we should return return and uh this one also need to minus minus and uh this one also need to minus minus okay okay 44 uh prefix new channel | 2024-03-22 16:05:40 | 1,804 | 1804. Implement Trie II (Prefix Tree) |
|
sKjKLN5JswQ | Hello hello guys welcome to another video link syrup yes here all problem link syrup yes here all problem minimum number of curing stops work minimum number of curing stops work which traveling from starting question which traveling from starting question tourist destination and gas stations tourist destination and gas stations languages parameters for gas station languages parameters for gas station subscribe first parameter location of the the the the subscribe first parameter location of the the the the point to Subscribe Problem Me Too Play List Subscribe Problem Me Too Play List Number Three Do You Know Very True Love You All the Best All the Best Quite Amazed To See An Example To Understand Mystery Approach That Targets 120 Rate And Few Words Starting With Green Color Represents Your First Look Is Must Subscribe During Every Must Subscribe During Every Age October 10th Smile Age October 10th Smile Notification Gas Station Otherwise 12260 Will Take Notification Gas Station Otherwise 12260 Will Take You Will Not Want From You Love You Love You To You Will Not Want From You Love You Love You To You To You To You All Subscribe Now To You To You To You All Subscribe Now To You To You To are the users can still alive Yashwant's this are the users can still alive Yashwant's this reception also you use list number of gas reception also you use list number of gas stations on a pension also you use listed stations on a pension also you use listed very important part question leaves very important part question leaves means Lifestyle can we do with one is it means Lifestyle can we do with one is it possible Darbhanga station weekend rate possible Darbhanga station weekend rate demands how will decide demands how will decide demands how will decide Gas Station Is That Point Baby So Well It's Very Simple But You Are See Gas Station Between The Evening Dil Se 0.2 Cost You Anything For Any Objection Certificate This Subscribe Subscribe Subscribe Subscribe Redoo Location Number 6 Redoo Location Number 6 Redoo Location Number 6 Options 12131 Image Choose Option Of Station And I Was In The 4th Nov 06 2009 600 To The Number To Get Number Six Gas Ko Subscribe Number Location Location Ko Play Karo Ho Match You Can Reach To Sun Tan Dark Area Picture Love Picture Love Picture Love You All The Best Used Use Oil Target But Now You Can Only To You To You To You To You To You What Is The Problem Of The Great Khali When Problem Of The Great Khali When Time You Did Not Be Used To Give Me Time You Did Not Be Used To Give Me Food Subscribe To Maximum Do Food Subscribe To Maximum Do Tuition Logically Tuition Logically Tuition Logically Which Give Winners Maximum Accurate Want To Yagya Station Petites Giver Maximum You How Can We Use Oil To That Is Remakes To Forget You Give Access To Value Priority Queue Data Activated Successfully Automatically Store In Descending Order To No No No Network Problem Share with Your Target We Network Problem Share with Your Target We Start With You and Impotent Responsibility Important to the Page if you liked The Shadow Gas Station Location Trusted 1610 Shadow Gas Station Location Trusted 1610 Destination Location 2000 Leaders of 820 Destination Location 2000 Leaders of 820 Questions A Teacher Brings Tears of Fuel Questions A Teacher Brings Tears of Fuel and Wee Honey and Gas Station Off and Wee Honey and Gas Station Off and Wee Honey and Gas Station Off You Check Location Number 66 Give Winners For It's OK I Love You To Two Numbers And What Do You Points 1770 Simple Points 1770 Simple Quarter 100 And Making Box This Side To Quarter 100 And Making Box This Side To And Consider Tiffin Gas Station OK 12139 And Consider Tiffin Gas Station OK 12139 Latest Latest Latest Discussed at the Meeting Will Take Off the Subscribe to the Page if you liked The Video A Hero for Its Users to Know Where Can Reach Maximum 10 Chapter 1010 Tay Let Me All Okay Now School Thank You 33351 OK 33351 OK patient this edition power targets 128 MB patient this edition power targets 128 MB center and this center and this below that 02-01-14 use this booster food in the morning below that 02-01-14 use this booster food in the morning use this we have used gas stations the use this we have used gas stations the number of process what is the number of number of process what is the number of like this three like this three like this three Station and Location Tan First Use This End User Gas Stations Location On 16th User Gas Station Location Thirty Rights Beach Bajaria Station Reduce Entries for Different Topics Latest Right to Code This Typing Code Simple 131 Test Too Complex Thu I want to see what is the name of hussain kilometer 100 initially with 222 but what happens to lead to hussain kilometer 100 initially with 222 but what happens to lead to change with time and change with time and again to declare variables or 120 matka again to declare variables or 120 matka prem ko * vinod retail account simple prem ko * vinod retail account simple condition will be the that the that the that You can check one more thing you can You can check one more thing you can You can check one more thing you can oxide shooting valley and upright events to oxide shooting valley and upright events to rename fennel first person declare another rename fennel first person declare another in that implement declaring vaccine in that implement declaring vaccine developed form so instituted of twin boys per important condition developed form so instituted of twin boys per important condition introduction so will check introduction so will check point extension of that point extension of that now so much tension start size secondary now so much tension start size secondary Fuel Sun Text Always Been Said Will Get Fuel Sun Text Always Been Said Will Get Another And Order For You To Develop It's Okay Another And Order For You To Develop It's Okay No Tension No Tension No Tension Know What Will Be The What Is The No Tension No Tension No Tension Know What Will Be The What Is The Meaning Of The Story Story Meaning Of The Story Story Fuel Subsidy Gas In Our Hands Fuel Subsidy Gas In Our Hands Free Latest Latest And Field And Free Latest Latest And Field And How How How Clear Left Hand Book Maths You Can Reach Simple Loot Gayi Thi Okareshwar Tiffin To Make Her Way Into Introduce Particular Magic Saunf This To Be Kab Vishad Parameter Will Give Us Please Us Kab Vishad Parameter Will Give Us Please Us Unwanted Station For Unwanted Station For Unwanted Station For Comparing With Gas Parameter Support The Parameter Is Tower Location Location Therefore Maximum Dictionary - One Who Have Written This Is One Important Now You Can Definitely Increase The Account Dr To This Award Which Will Take You Top Most Volume to Volume to Volume to maximum alice what like and will 8282 what makes oo can maximum alice what like and will 8282 what makes oo can reach with top most reach with top most significant you is what is the few ladies significant you is what is the few ladies marketing and drop earing you marketing and drop earing you including father 10.2018 delhi removed from tomorrow morning rasam runtime hair soft it will ask tomorrow morning rasam runtime hair soft it will ask Veervansh Sexual 100 Kal Su Failed Blog.com Kal Su Failed Blog.com Aur Sundar Beta Hai Main Reduced IF Aur Sundar Beta Hai Main Reduced IF Possible Index Plus Plus What Is Possible Index Plus Plus What Is Happening In Solidworks Incriminating While It's Happening In Solidworks Incriminating While It's Coming Year Slide Yes I Will Have To Coming Year Slide Yes I Will Have To Halvis Remix After 10 Line End Halvis Remix After 10 Line End B5 Vaguely Defined S Gaj Spine of Languages Submit Gaj Spine of Languages Submit Gaj Spine of Languages Submit Incident Working on Incident Working on Hai Sach Walking Dead Thank you for being Hai Sach Walking Dead Thank you for being patient and listening | 2024-03-22 16:36:59 | 871 | Leetcode 871 Minimum Number of Refueling Stops ||Code + Example + Explanation ||June Daily Challenge |
|
EBij0moGIxs | then first 3 answer subset subset [Music] problem DP con string string s one 1 one 1 one 1 one 1 0 0 1 0 0 1 or one Z M five n three three result result find [Music] form size then for Z One Z integer Z count count of s Str begin okay then integer simple simple one one then Matrix from bottom to right and top then Matrix from bottom to right and top to left okay update update uh DP bottom bottom to bottom bottom to top bottom to top bottom right to bottom left sorry bottom right right to uh top left okay then similar one then DP of IAL maximum of DP J minus one plus then DP of n [Music] confused problem [Music] p oh alhamdulillah submit p oh alhamdulillah submit accepted submit so | 2024-03-22 15:23:17 | 474 | 474. Ones and Zeros LeetCode Solution || C++ |
|
81ieEUu-nS8 | hi and welcome to prototype we will be solving the problem for lead code 235 solving the problem for lead code 235 lowest common ancestor of a buy-in lowest common ancestor of a buy-in research tree this is another problem in research tree this is another problem in the lead code 75 study plan let's get to the lead code 75 study plan let's get to it so given a buy and research tree BST it so given a buy and research tree BST find the lowest common ancestor LCA node find the lowest common ancestor LCA node of two given nodes in the PST of two given nodes in the PST according to the definition of LCA on according to the definition of LCA on Wikipedia the lowest common ancestor is Wikipedia the lowest common ancestor is defined between two nodes p and Q as the defined between two nodes p and Q as the lowest node in the tree T that has both lowest node in the tree T that has both p and Q as descendants p and Q as descendants and they also allow a node to be a and they also allow a node to be a descendant of itself descendant of itself okay and so we're given an example with okay and so we're given an example with the tree with the root note 6 having the tree with the root note 6 having children 2 and 8 with child two having children 2 and 8 with child two having children 0 and 4 and with child four children 0 and 4 and with child four having children three and five and with having children three and five and with child eight having children seven and child eight having children seven and nine and if we're given P equal to and Q nine and if we're given P equal to and Q equal to eight so two and eight then it equal to eight so two and eight then it wants us to return six the root node wants us to return six the root node and in this case there's only one and in this case there's only one ancestor but let's just look at some ancestor but let's just look at some other uh potential examples with this other uh potential examples with this particular tree so if we were given particular tree so if we were given P0 and q9 then the lowest common P0 and q9 then the lowest common ancestor again there's only one it would ancestor again there's only one it would be the root node right couldn't be two be the root node right couldn't be two and it couldn't be eight because two and and it couldn't be eight because two and eight are not ancestors of both zero and eight are not ancestors of both zero and nine now if we were given three and five nine now if we were given three and five three and five have three ancestors four three and five have three ancestors four two and six but it wants us to return two and six but it wants us to return four because it's the lowest common four because it's the lowest common ancestor or if it's easier for you think ancestor or if it's easier for you think of this way the closest uh ancestor 2 3 of this way the closest uh ancestor 2 3 and 5. and 5. okay okay so the trick in this question is to so the trick in this question is to leverage the fact that this is a binary leverage the fact that this is a binary search tree in in a binary search tree search tree in in a binary search tree every child to the left of the node must every child to the left of the node must be smaller than the current node's value be smaller than the current node's value and every node on the right side or the and every node on the right side or the whole sub Tree on the right side has to whole sub Tree on the right side has to be larger than the current node as well be larger than the current node as well and both the left sub tree and the right and both the left sub tree and the right subtree must also be binary search trees subtree must also be binary search trees okay okay there's a couple other things that we there's a couple other things that we should keep in mind so all node values should keep in mind so all node values are unique P will not equal to q and are unique P will not equal to q and both p and Q are guaranteed to exist in both p and Q are guaranteed to exist in the binary search tree so things to keep the binary search tree so things to keep in mind as well in mind as well all right let's do a recursive solution all right let's do a recursive solution first first so let's create another function let's so let's create another function let's call it recursive call it recursive it's going to take a note and it's going it's going to take a note and it's going to take p and Q to take p and Q and so and so again the fact that this is a binary again the fact that this is a binary search tree means that everything to the search tree means that everything to the left of the current nodes every child on left of the current nodes every child on the left is going to be smaller and the left is going to be smaller and every child on the right will be larger every child on the right will be larger okay okay how do we find how do we find the closest or lowest common ancestor the closest or lowest common ancestor well well let's think about it without just let's think about it without just looking at the problem okay looking at the problem okay we're given the root notes we're given we're given the root notes we're given six six again let's say that we're given P3 and again let's say that we're given P3 and Q5 Q5 well both three and five well both three and five how do they relate to the current node how do they relate to the current node or the root node six both three and five or the root node six both three and five are smaller than six are smaller than six what does that mean that means that both what does that mean that means that both three and five three and five are on the left side of six they exist are on the left side of six they exist in the left subtree of six in the left subtree of six and because both values exist in the and because both values exist in the left subtree there must exist some other left subtree there must exist some other node that would be closer to the node that would be closer to the children three and five right so if both children three and five right so if both of the values p and Q are smaller than of the values p and Q are smaller than six then we Traverse the binary search six then we Traverse the binary search tree to the left and then we can compare tree to the left and then we can compare the next node again with p and Q all the next node again with p and Q all right then child node of six is two how right then child node of six is two how does three and five compare to two well does three and five compare to two well both three and five are larger than two both three and five are larger than two and therefore they must exist in the and therefore they must exist in the right sub tree of two and therefore right sub tree of two and therefore there must exist a closer or a lower there must exist a closer or a lower ancestor two three and five ancestor two three and five so because three and five are both so because three and five are both larger than two we Traverse again to the larger than two we Traverse again to the right child finally we get to four right child finally we get to four and we compare three and five to four and we compare three and five to four three is smaller than four and five is three is smaller than four and five is larger than four larger than four and in fact this means that or and in fact this means that or must be the closest ancestor or the must be the closest ancestor or the lowest common ancestor to P3 and Q5 lowest common ancestor to P3 and Q5 okay let's think of um okay let's think of um let's say five and seven okay just one let's say five and seven okay just one more example here five and seven five is less than six so it exists on the left sub tree and seven is greater than six so it exists in the right sub tree again because both children exist in different sub trees so again a five in the left subtree and seven in the right subtree there cannot be any lower or closer ancestors six is the closest ancestor so that's what we're going to leverage okay let's get to it so if the node value is let's say let's compare P so if the value of p is less than the current node's value and Q's value is less than the nodes value then what are we doing we're going to Traverse to the left so called node.left and then we just pass through and we'll return that and we'll return that otherwise if P dot value otherwise if P dot value is greater than no dot value and Q dot is greater than no dot value and Q dot value is greater than node.value value is greater than node.value then we will Traverse to the right and again pass through p and Q otherwise we must be at the lowest common ancestor so we return the current node and finally we can just return recursive and we call recursive on or the root p and Q and submit okay so beats 45.58 percent and just as a check let's just submit one more time see if it can be any better 99.5 percent there you go that's leap code from 45 to 99. okay so now we can leverage something very similar to do this iteratively and uh why don't we just do that so let's get rid of this get rid of this and iteratively let's use a trusty while loop okay we'll need a variable for the current node that we're at and here we can just say well the current node is not null and then otherwise we're going to be doing more or less this exact same thing if the Q value and the p-value is less than the current nodes value what are we doing we're going to Traverse to the left so Cur is going to be assigned assigned curve.lap is going to be signed occur and then similarly on the right side car dot right will be assigned to Cur and um and um to save some space we can just say else to save some space we can just say else we return we return the node because again if both the node because again if both values p and Q are smaller than the values p and Q are smaller than the current node then we Traverse left if current node then we Traverse left if both values are larger than or another both values are larger than or another introverse right otherwise we have found introverse right otherwise we have found the closest ancestor the closest ancestor now this is the most concise way to now this is the most concise way to write this I probably wouldn't write write this I probably wouldn't write this in in production this in in production um um but this does work because and we don't but this does work because and we don't even need to say return curve here even need to say return curve here because we know that there will always because we know that there will always be an answer be an answer but otherwise I would probably say wrap but otherwise I would probably say wrap this and wrap this in the Boolean this and wrap this in the Boolean expression right and then once neither expression right and then once neither of these are of these are uh pass then we know that we can break uh pass then we know that we can break out of the loop and return curve but out of the loop and return curve but anyway this is more concise so let's go anyway this is more concise so let's go with that submit okay 90.2 percent okay so that is the recursive and iterative solution to lead code 235 lowest common ancestor of a bind research tree subscribe to see more we'll be following up with the rest of the lead code 75 study plan questions in short order | 2024-03-22 11:24:45 | 235 | Lowest Common Ancestor of a Binary Search Tree - LeetCode 235 - JavaScript |
|
ds9ZKS8fUqw | lead code problem number seven reverse integer so this problem gives us a sign integer so this problem gives us a sign 32bit integer X and we have to return x 32bit integer X and we have to return x with its digits with its digits reversed and if reversing X causes the reversed and if reversing X causes the value to go outside the sin 32bit inte value to go outside the sin 32bit inte range basically in minan or in Max right range basically in minan or in Max right here I Jed down the values what is in here I Jed down the values what is in mean mean then we have to return zero and here is then we have to return zero and here is the important part we have to assume the the important part we have to assume the environment does not allow us to store environment does not allow us to store 64bit integers sign one side meaning 64bit integers sign one side meaning that we can't just use that we can't just use long and basically that's it right that long and basically that's it right that those are the rules so here you examples one two three we get three one so let's use that as an example let's say x is 1 2 3 so in this case result would be zero first thing I do is I check if X is not zero then we are good to go we can keep on dividing X by three right so basically the idea is to cut off the number from the back and then add the number to the front right I show you what I mean so now uh this me right now because result is obviously not more than INX by 10 and is lesser than mean 10 for now just ignore this we'll get back to this later we'll just uh look through this with the example with a simple example such as this first okay 1 two three equals to results time 10 so now results * 10 which is basically still zero plus X X modulus 10 so X modulus 10 1 2 3 modulus 10 will give us three right so result is now three for it will uh this x will divide by 10 so in integer since we can't have floats right we can't have pointers or we can't have decimals not pointers so what this three will just disappear right so now we are left with one and two so we do the same thing result time 10 this * 10 is 30 30 + x modulus 10 is 2 so 30 + 2 is 32 divide by 10 Again 1 * 10 + 1 right X modulus 10 will just give us one and result will be 51 after which if we were to divide it again X is is now zero right and since X is zero this for will end and we will return our result which is 321 right example okay so let's say so what is example okay so let's say so what is this if statement for so let's say we this if statement for so let's say we have a very big number let's go with something like this right PR is outside of INX it's good to check okay it's not so we'll add another nine here okay after which let's say we have this number right so we know what happens in the for Loop right so basically we will divide by 10 nine and 8 88 this nine and 8 88 this seven seven 6 6 5 5 4 4 3 two okay right at this point right right at this point if we were to run with this each statement right result is it more than inex divided by 10 okay let's see so inex is this number divided by 10 again we remove the last number right so let's remove it like this you can see our result is actually bigger than INX so what will happen is if we were to continue times 10 to this 32bit integer it will overflow right and we don't want that to happen instead we want to return zero so that's how we check right basically divide INX by 10 if it's if it's going to go above the integer Max or we compare it against the inmin see whether or not it's smaller than inmin ID by 10 right so if either of these condition is true we will want to return zero instead so for this case the result of this would be zero okay so yeah this question even though it's medium it's actually pretty simple not sure whether that's because it's cross pass but yeah to me it's pretty straightforward anyways that's | 2024-03-18 11:51:51 | 7 | Reverse Integer - LeetCode #7 - C++ |
|
1LkOrc-Le-Y | Hello hello guys welcome back to tech division in this video you will see media and in in this video you will see media and in no data stream problem something from the no data stream problem something from the list number to 9 500 latest reader list number to 9 500 latest reader problem statement no problem medium problem statement no problem medium size maintain value and order in to-do list size maintain value and order in to-do list play list play list play list of solid example element two three and the number of elements in the middle of elements have to the mid point mintu number from 2018 will be written in the media and of the elements which they have seen shopper stop this Statement Latest Example Statement Latest Example Statement Latest Example Media Media Can Only For All Elements Media Media Can Only For All Elements In This Is The Number Of Elements Which Will Be In This Is The Number Of Elements Which Will Be Plus One Element The Number Of Elements Of Elements And Will Be Divided Into Two I Know This Is Not Order In This Way Will Just after attending or morning to three four after doing now will take the middle element which is the number of elements in this elements of villages in ascending order will be The Video then subscribe to the Page if you liked The Video then -man Will -man Will -man Will Give Elements Are Not Give The Giver Element Give Elements Are Not Give The Giver Element Quizzes Number Five Know What is the Meaning of Quizzes Number Five Know What is the Meaning of the Singh Elements In Charge Jaswinder Singh the Singh Elements In Charge Jaswinder Singh Element Brand Value Will Be One and Some Element Brand Value Will Be One and Some Indian Will Win This Element Services Indian Will Win This Element Services From Pet Knowledge You Are Singer Element Witch 323 294 323 subscribe The Video then subscribe to the Page Ki no will be singh hai na der element which is this point fennel and this coming no this is not order will just after intelligence service three 500 to 1000 number of elements of which will be added subscribe to subscribe to the Page if you liked The subscribe to the Page if you liked The Video then subscribe to the Remind Me Indian Give Any Stream OK So You Can Be Easy Aaj To Find The Media And Any Given Freedom At Any Given Point OK And You Be Considering All Elements That You Will Be Be Considering All Elements That You Will Be Be Considering All Elements That You Will Be Keeping Elements In Order To Keeping Elements In Order To Be Able To Understand This Simple Solution In Order To Solve This Problem Will Be Be Able To Understand This Simple Solution In Order To Solve This Problem Will Be The First The First Most Important Veer Veer Veer Veer The Most Important Veer Veer Veer Veer The Element Servi Servi Elements In Order To Element Servi Servi Elements In Order To Give You Can Absorb Ki Element Servi Please instructions for this really use no weir wedding you element to give the interstate 1659 and streams having three elements 2.5 entertainment industry ministry less will be using instructions for insulting three and the current position latest that we can infer from the right and where moving Find the Proposition for Find the Proposition for Find the Proposition for Elementary Level Been Sorted in Between Two Elementary Level Been Sorted in Between Two 400g The Element Subscribe 12345 subscribe to the Page if you liked The Video then subscribe to the Number Operation Your Sorting Element Not Finding Media Is Nothing But Using Formula That Is It Of elements and Of elements and Of elements and a plus one element Dravid number two plus two a plus one element Dravid number two plus two plus one element subscribe this Video Total time complexity of way the solution Total time is it possible to improve the solution David possible to reduce 209 congress you must be now serving sea of things which are given In the problem solve india server only interested in finding them with the limit of dashrath ok and media ne revenue expenditure shoulder tanning god are number of elements and take of the question which comes to number of elements and take of the question which comes to mind e mind e mind e Elements In The Answer Is The Element Which Element Which Is The Number Of Elements Lord Who Will Just Be Having A Single Man Element Otherwise The Number Of Elements Of One Who Will Win Every Single Thing Which Element Is In Maintaining The Complexity And Element in search operation and subscribe and no one in this world can just reduce ho but is time taken to maintain doctorate you can reduce the number of soldiers where is it possible to reduce the time in this order Balance Tree Will Be Very Very Highly Balance Tree Will Be Very Very Highly Compressed 100 Gram Melt Paris Compressed 100 Gram Melt Paris Are Balance Binary Rate So They Can Make You Are Balance Binary Rate So They Can Make You Laugh And Just Give One Example If You Laugh And Just Give One Example If You Think About Using He And Use This Is The Think About Using He And Use This Is The Question How To Use This Problem Question How To Use This Problem Example2 Example2 6 Media In This Example2 Example2 6 Media In This Example2 Example2 6 Media In This element filter element with just a few such elements in to the it's your pocket and between number of elements and you will get the middle element shopping obtained by two number of elements In In In putting all the day in the two elements with putting all the day in the two elements with consumers huge amount of time and so consumers huge amount of time and so will consume one by two to log in time Sudhir will consume one by two to log in time Sudhir Vinati button log in time for each element in Vinati button log in time for each element in social forum will give one example social forum will give one example of obscurism subscribe elements citizen of obscurism subscribe elements citizen more solution which will Maximum and Minimum Element but Will Need a Number of Elements This Video Not Required to Maximum and Gum Investment of the Center Roy Ok and You Soe Important Observation in This Is It Say You Have Been Given Number of Elements Between you can Between you can Between you can create first half and sacrifice no create first half and sacrifice no effective want to find the meaning that you are doing this effective want to find the meaning that you are doing this you will take maximum difficult you will take maximum difficult absolutely minimum of the lambs maximum subscribe 2.5 this is the first half will be having one element extra divide All subscribe to All subscribe to All subscribe to quick with you want to find the media in the Indian and number of elements will only be single element and will be the maximum element in the first rate in the morning Maximum age limit for the first The Mean That The Mean That The Mean That In Order To Avoid Cold Water Will Be In Order To Avoid Cold Water Will Be Difficult For Media And Subscribe Difficult For Media And Subscribe Divided Into Two Elements In The First Divided Into Two Elements In The First Phase Of Poles Were Divided Into To Take Phase Of Poles Were Divided Into To Take Medicine For The First Time Medicine For The First Time Apni For The Second You Read So This Apni For The Second You Read So This Attractive Solution You Might Not Getting Attractive Solution You Might Not Getting Attractive Solution You Might Not Getting first time you can understand you can play in the problem in order to understand and subscribe our country the size of the subscribe and subscribe the difference between a ko suli charda points to remember no you can also azim directory element which Thum In His Words For Simplicity Is Taken For Thum In His Words For Simplicity Is Taken For Thum In His Words For Simplicity Is Taken For The Shape Of You Can Do It Is The Shape Of You Can Do It Is The Way Will Be As Well As Will Not See The The The The The The The Subscribe subscribe this Video this Video Website Is One Greater Than Thum In His Eyes Website Is One Greater Than Thum In His Eyes Additional Additional Additional The Maximum Will Be Getting Selected Navodaya Multiple Condition Of Insulting Istri You Will Have To Compare Doosri With The Top Of The Seat Debit The Series Who In The Forest Of Elements Of Women Are Divided Between The Is The Is The Is The Element Middle Order In This Element At The Element Middle Order In This Element At The Rate Of The Three Layer Pendant Three To The Other Rate Of The Three Layer Pendant Three To The Other Is This Element Which Will Be The In The The The The The The The Is This Element Which Will Be The In The The The The The The The The Robert Count 3152 Gather Cannot Be Vitamin Hips Vitamin Hips Vitamin Hips Having Zero Number Of Elements So They Want To Equally Having Zero Number Of Elements So They Want To Equally Distributed Elements Between Distributed Elements Between Maximum Minute Notification More Maximum Minute Notification More Divided Between Them Will Be Coming To The Divided Between Them Will Be Coming To The First He Will Be Coming Subscribe To The Number To The Self Plus Plus 382 34 Next Element Next Element Next Element Next Element Is Add 400 Want To Insert Next Element Is Add 400 Want To Insert 499 video.com Ine Bluetooth Of The Same 499 video.com Ine Bluetooth Of The Same Size Arvind 409 Subscribe Element Size Arvind 409 Subscribe Element Subscribe Top Of The The The The The The Subscribe Elements Present A Number Of Elements See All And The And The And The President Will Be No Want To See The President Will Be No Want To See The Element Only After Two Elements And Distribution 12345 Will Be Divided Into Three Four And A That Know How Do You Rearrange Desi So You Can See The Two So On This Day The Root Of The Match Fall Into The Fans Don't Miss The Fall Into The Fans Don't Miss The Fall Into The Fans Don't Miss The First And Subscribe One Element First And Subscribe One Element Extra The Video then subscribe to Extra The Video then subscribe to the Video then subscribe to the Page if the Video then subscribe to the Page if you liked The Video then subscribe to you liked The Video then subscribe to the Page if you liked The Video then subscribe to the Page To India the To India the To India the maximum in have reached its an order soegi friends this is the root of the the the the the the the the the the the the the subscribe to the Video then subscribe to the 4606 know Of the giving elements Of the giving elements Of the giving elements and and absolutely media remedies love because in the absolutely media remedies love because in the voice of printing element you can we are voice of printing element you can we are tourist inside medium ok sorry time tourist inside medium ok sorry time complexity and justice vr insulting and complexity and justice vr insulting and number of insulting element in two that is number of insulting element in two that is nothing but pushed into the best android login nothing but pushed into the best android login nothing but pushed into the best android login this video you will just total time complexity of time which is very simple but as we know you will find the sun dot co dot in quest train fare will be given no constructor which is medium finder here you can influence your data structures but it is Wishes Servi Servi Servi Servi Difficulty subscribe and subscribe the Difficulty subscribe and subscribe the Channel Will Be Channel Will Be Quote Get Into R Maximum Otherwise Maxi Quote Get Into R Maximum Otherwise Maxi Fee No Top 10 Days Maximum In For The Fee No Top 10 Days Maximum In For The Simpsons Day Obviously Mexico Will Give One This Simpsons Day Obviously Mexico Will Give One This Is It Maximum Per Of The Same Is It Maximum Per Of The Same Is It Maximum Per Of The Same all elements which will be having one element extra but due to which element which is the one which will be the top of the in voting to declare the match and again insulting this new element which is number Into them in his work Sudhir vich will recommend you to solve this problem subscribe and Share subscribe and subscribe and subscribe and Share subscribe and subscribe and subscribe the minutes ago subscribe the minutes ago Jai Hind is third case of minute size Jai Hind is third case of minute size aerobics exercise equal to one for office after adding this element aerobics exercise equal to one for office after adding this element maximum size maximum size Dhawan and minutes Dhawan and minutes Dhawan and minutes unexpected this number will be sent to withdraw the for this is the mean of the top element which for this is the mean of the top element which can increase the other is not through this can increase the other is not through this element which will push the number * Subscribe to element which will push the number * Subscribe to Only Maximizes One Medium Size Only Maximizes One Medium Size Only Maximizes One Medium Size Phone Know What Happens When There's No Rule Phone Know What Happens When There's No Rule subscribe and subscirbe In That's The subscribe and subscirbe In That's The Meaning Of This Number To The The The The The The The The The The The Meaning Of This Number To The The The The The The The The The The The The We'll Keep Watching This Is The The We'll Keep Watching This Is The Meaning Of This Meaning Of This Meaning Of This problem will be able to figure out which you need to eat cases will take some time it takes some extra time but while food and fuel and soul within you can just watch this video in order to figure No This No This No This Is The Indian Case Hair Dravidian Formula Will Is The Indian Case Hair Dravidian Formula Will Only Depend On What Will Be The Number Only Depend On What Will Be The Number Of Element And Rate So Busy These Days Subscribe To Of Element And Rate So Busy These Days Subscribe To Subscribe The Channel Subscribe The Channel And Subscribe The One That Will Be The Rebel To Do Do Do Do Help You Whenever Possible Help You Whenever Possible Help You Whenever Possible Din please try to donate which will help us bring more free quality content in future for everyone see you in next | 2024-03-22 14:29:54 | 295 | Find Median from Data Stream |
|
Jm5_-PvzM6g | [Music] foreign [Music] this is Larry this is day seven of the hit the like button hit the Subscribe hit the like button hit the Subscribe button join me on Discord let me know button join me on Discord let me know what you think about today's fun what you think about today's fun construction train from binary tree I'm construction train from binary tree I'm just oh yes so sometimes I click I don't just oh yes so sometimes I click I don't know if there are other Pages let me know if there are other Pages let me know in the comments if you know of the know in the comments if you know of the other pages but I sometimes check this other pages but I sometimes check this not because I'm I don't know obsessed or not because I'm I don't know obsessed or something maybe I am but but not be only something maybe I am but but not be only because of that but because of this because of that but because of this button on the upper left LC easy plus 10 button on the upper left LC easy plus 10 you click on it and it doesn't show up you click on it and it doesn't show up every day but you got 10 Bitcoin uh yeah every day but you got 10 Bitcoin uh yeah 10 Bitcoins so and you know you can 10 Bitcoins so and you know you can always have more lead coins for a always have more lead coins for a t-shirt or something I don't know right t-shirt or something I don't know right so anyway so anyway that's just something and also uh hope that's just something and also uh hope you like the intro I'm actually in you like the intro I'm actually in London right now London right now um so maybe some of this would be a um so maybe some of this would be a little bit uh you know uh from a couple little bit uh you know uh from a couple of whatever it goes so hope you enjoy it of whatever it goes so hope you enjoy it uh uh uh when I was in Italia and there's some uh when I was in Italia and there's some beautiful stuff so I want to show it off beautiful stuff so I want to show it off a little bit uh so indulge me in it even a little bit uh so indulge me in it even if you may not care about it I do need if you may not care about it I do need to make the music a little bit lower I to make the music a little bit lower I keep on editing the script but I don't keep on editing the script but I don't know let me know if you think about the know let me know if you think about the volume or whatever volume or whatever um okay um okay it uh it's 7 A.M in London so that's why it uh it's 7 A.M in London so that's why I'm like I'm like doing the waking up routine doing the waking up routine um cool um cool anyway today's Farm is construction from anyway today's Farm is construction from binary tree okay what does that mean binary tree okay what does that mean we're given a root of binary tree we're given a root of binary tree construct string friends pre-order okay construct string friends pre-order okay so just pre-order and so just pre-order and and uh yeah okay what does the prevent and uh yeah okay what does the prevent action mean so okay action mean so okay oh so basically left so okay so it's oh so basically left so okay so it's just pre-order and then every time you just pre-order and then every time you do a recursion you add friends right so do a recursion you add friends right so let's let's get started let's let's get started um um I think the thing that you might have to I think the thing that you might have to think about is to string can cat but think about is to string can cat but we'll go for it we'll go for it um so pre-order so we'll just write you um so pre-order so we'll just write you know pre-order right now and then we'll know pre-order right now and then we'll we'll write out the we'll write out the the sketch and then figure out how it is the sketch and then figure out how it is that we want to that we want to uh you know finish it or whatever so uh you know finish it or whatever so then pre-order is just you know you then pre-order is just you know you would process no and then we pre-order you know that left no that way right okay so that's the [Music] [Music] um um because the thing is that you do a lot because the thing is that you do a lot of string concatenations it may be a of string concatenations it may be a little bit messy so or like it could little bit messy so or like it could divulge in N Square which I guess for a divulge in N Square which I guess for a thousand no way ten to the fourth thousand no way ten to the fourth I don't know but I I rather not having I don't know but I I rather not having to think about whether that barely times to think about whether that barely times out especially on lead code where the out especially on lead code where the platform is a little bit platform is a little bit um um uh for python it's a little bit you know uh for python it's a little bit you know like where the time's out or not at like where the time's out or not at least for me I have a lot of uncertainty least for me I have a lot of uncertainty and that's kind of partially why I've and that's kind of partially why I've been doing that as well lately is been doing that as well lately is because I think I second guess myself a because I think I second guess myself a lot anyway this is an easy I'm not lot anyway this is an easy I'm not saying it's easy but it is an easy level saying it's easy but it is an easy level problem uh is what they say so problem uh is what they say so um so we should just let this you know um so we should just let this you know see like so for the current number we see like so for the current number we want to uh something like this right and then for the left um so if I also have to do like if if um and then here we go with the load um and then here we go with the load examples not none then we pre-order I'm examples not none then we pre-order I'm usually I don't need to do it because usually I don't need to do it because this one will get it but we want to wrap this one will get it but we want to wrap it around that's why I'm doing it this it around that's why I'm doing it this way way um and you can um and you can do it in a fancier for Loop so let's do it in a fancier for Loop so let's let's maybe do that let's maybe do that uh well let's write this first and then uh well let's write this first and then we write the open fluent oops we write the open fluent oops and then we do the course parents and I and then we do the course parents and I think that's pretty much it and then now think that's pretty much it and then now we can do maybe some funky for Loop we can do maybe some funky for Loop where like for a child and and no dot where like for a child and and no dot left go that way something like this right child is not none that will pre-order on it uh and then at the end we can return to do and of course we want to pre-order the that was a silly debugging but yeah um that was a silly debugging but yeah um okay so that's a little bit sad oh okay so that's a little bit sad oh because huh okay so I got the first one right but the second oh you cannot omit the first parenthesis because then now you have to do it left um foreign um let me think about I mean to be honest this is just like an if statement but uh and if I was in the contest I would just think I would just do the if statement but um it's still a cleaner way of doing it um it's still a cleaner way of doing it because you know look at look at this because you know look at look at this code right now it's very clean but that code right now it's very clean but that said clean code that is wrong is not said clean code that is wrong is not useful right useful right um messy code that is working is still um messy code that is working is still more useful than clean code that is more useful than clean code that is uh uh that doesn't work so but um okay I think the way that you can do it is Maybe but then this also May [Music] was extend is like not very great because then now you have the same issue with um actually I think we could fix it but but you might have the same issue with the n-square type thing which is maybe I shouldn't do it this way then maybe we should just do if statement okay fine because I think I'm trying too hard to be uh clever and cute um um yeah yeah okay foreign I'm trying very hard to save my for Loop I'm trying very hard to save my for Loop but I think maybe I just need to smash I but I think maybe I just need to smash I don't think that I can do it don't think that I can do it um so um so yeah so okay let's write it out back out yeah so okay let's write it out back out again again uh sorry friends let's unload the loop because they're let's unload the loop because they're not this is not the same as I thought not this is not the same as I thought they would be so yeah they would be so yeah thanks thanks I mean this isn't that bad it's just I mean this isn't that bad it's just that I was really trying hard to do it that I was really trying hard to do it and then here we go and then here we go and then maybe we could just do if no and then maybe we could just do if no dot left is none then we do I hope this is right let's try the empty note I've been missing that oh I guess we have at least one note but uh let's something like that some basic trees at least to show that I I tested small ones let's give it a submit have I not solved this before well yeah a new problem for me solved uh 890 day Street yay um so yeah this is gonna be linear time linear space I mean the the real tricky thing about this one is that it is easy and possible to to do genuine and square if you if you keep track of like um a string concatenation thing you can definitely if you keep on concatting because of immutable strings and stuff like this um it's going to create more instances and then you're gonna have that like one plus two plus three plus four dot dot which sums to n square right um or o of N squared I know it's not exactly n square but um and that's what you do not want to do so that's why I kind of do it in a funky way with this answer and uh and yeah and each um each character of the string will only be wizarded twice right once to append to the answer and then the second time by joining so that poops out all of n uh time and space um and time is just because we look at each node once but uh yeah uh that's pretty much all I have for this one let me know what you think uh I I know this is a very um last minute paying but if you're in London and uh you like to grab a drink um I think one of our uh Discord buddies uh what about fans are trying to uh uh uh we're grabbing a drink somewhere Friday night I know this is in like two days maybe depending on where you're watching it uh well we'll be in London then uh and you know hit me up we'll go with Discord and and we're organizing something I mean if not it's fine too um and if you're watching it from the future sorry you miss it but uh anyway that's all I have to I'll see y'all later stay good stay healthy take good mental health take care and hope to see you soon huh | 2024-03-20 12:21:21 | 606 | 606. Construct String from Binary Tree - Day 7/30 Leetcode September Challenge |
|
2rnpphMj0a8 | Hello Gas, today we are back again with Gyan Portal and Gas, now we are going to challenge the lead to solve the daily problems I come across and the The The target of 744 is to find the smallest letter. So basically, first of all we have to read the big part of this problem, what is the problem? The problem is to tell what is there in the problem. Which means Which means Which means in non-decreasing order, non-decreasing in non-decreasing order, non-decreasing order means in increasing order and one order means in increasing order and one character has been character has been given to us which is our target given to us which is our target character. There are two different characters which are mentioned in the letter. To return our The meaning of increasing order is that it The meaning of increasing order is that it The meaning of increasing order is that it gives anything lexicographically for serography, gives anything lexicographically for serography, like if we say that like if we say that C is the lassi of C, graphically greater, if C is the lassi of C, graphically greater, if we talk, then C is greater for lexicography, we talk, then C is greater for lexicography, what can happen if we talk. what can happen if we talk. what can happen if we talk. A may be but if Di and A we need two then C K lexicographically will be our Di [ Music] So in this way we have to tell the things as they are, we have also been given two examples in this, I'm given we've got I'm given we've got I'm given we've got C, we've got F, N, C, we've got F, N, G, and the target we've been given, we've been G, and the target we've been given, we've been given equals, [Music] Let's talk, first of all, if Let's talk, first of all, if Let's talk, first of all, if we talk about it, firstly, we talk about it, firstly, what can we do with a simple approach, what can we do by traversing all the letters given to us and traversing all the letters given to us and traveling through it, what can we do? traveling through it, what can we do? and store what we have and then we compare what we have and store what we have and then we compare what we have with the target to see whether that is with the target to see whether that is present or not and if it is present then present or not and if it is present then we input what is next to it we input what is next to it and if not then and if not then so let's see when the solution will work or so let's see when the solution will work or not, so let's start and what will we make in it Music] Music] We made him travel till the length of the letter We made him travel till the length of the letter we have the letter. What have we done to it and taken its input, what will happen from it, whatever characters are there in our alpha, that student means in a way we have made a frequency, its name is let's go, okay, so this is what we have, named this whatever is alpha. named this whatever is alpha. named this whatever is alpha. made it at but we have idea which is our idea, we have seen it with zero, is it our alphabet, is it our present, is it not our present, if it is not present then what will we do, We will simply We will simply We will simply increase it okay and then after we have done this we will return it then you can see [music] music] [music] If you want to If you want to If you want to understand the approach, whether binary search approach will be used in this understand the approach, whether binary search approach will be used in this or not, then its basic is that or not, then its basic is that one target will be given to you and one will be done from Ara, one target will be given to you and one will be done from Ara, then whenever something like this is seen, then there is no story or story and you can get the idea that Binary search can be done there. Okay, so what is the benefit of binary search? You also know like till now I have told you what happens in search. In binary search, what we lose becomes more, [Music] We have taken this L and then our and letter else if then else if if the target is ours, letter else if then else if if the target is ours, what will happen to us, the target should be bigger or what will happen to us, the target should be bigger or equal, the equal, the letter else -1 has letter else -1 has traveled through all the letters, but the traveled through all the letters, but the target target target we can't do anything big then what will we do, we will simply [Music] [ So what will we do, [Music] [Music] What will we do, let's meet ours one by one What will we do, let's meet ours one by one Who knows, if something bigger than this is Who knows, if something bigger than this is already present, because we have to already present, because we have to extract it lexicographically, so extract it lexicographically, so if not, if we come to know that this is if not, if we come to know that this is ours, which is later, mid, which is smaller than the ours, which is later, mid, which is smaller than the target, then what do we have to do, we have to target, then what do we have to do, we have to travel further. travel further. travel further. what will we do, simply do mid plus one and what will we do in return, we will do our return and let's not only by doing gas, but something like this is okay not only by doing gas, but something like this is okay [Music] Our Our Our problem has been submitted. I hope you have problem has been submitted. I hope you have understood how we have understood how we have solved it. Find out, | 2024-03-21 12:16:46 | 744 | Leetcode 744: Find Smallest Letter Greater Than Target | Binary Search Explained |
|
m10NAXnEn1w | hey hey everybody this is larry this is day fourth of the august nicole dairy day fourth of the august nicole dairy challenge hit the like button to challenge hit the like button to subscribe and join my discord subscribe and join my discord let me know what you think about taste let me know what you think about taste problem have some too um so i usually problem have some too um so i usually solve this live solve this live so if it's a little bit slow just fast so if it's a little bit slow just fast forward forward move ahead whatever you need to do uh move ahead whatever you need to do uh okay okay so given a rule and talking somebody so given a rule and talking somebody don't would to leave with some don't would to leave with some each half sum is equal to target some each half sum is equal to target some aliens okay okay this should be straightforward in that uh the key difference between this and maybe a similar problem that i was looking for is that each path is from root to leave right and that means that you can kind of um implement things in the stack because yeah uh at an implicit stack where um a different search or an auto traversal type thing or an explicit stack because the idea is that every time you see a node you push it you check and then you you um pop it right so this is going to be linear time and and knowing that this is linear time because it is essentially an order traversal or a choice of the tree um you know that i don't have to really look at the constraints because linear time is probably gonna be fast enough uh the only thing that may like a variation that may change that is for example if there are a number of target sums then you might have to play around with some ideas but at least in this case because of those two things you can do it in linear time relatively straightforward and it becomes uh an implementation problem uh and here there are a couple of kind of pitfalls but in general i think this should be pretty um pretty good there are a couple of ways you can think about this problem but oh and in this case it's actually root to leave i think that was the other thing that i i was actually double checking was whether for example intermediate nodes is good for example if if it's five if the target sum is nine it's five plus four you know it's not a rounded path in this case this is actually not because you have to go all the way to the leaf so that that's you know with that let's go all together um and in this case even though i said it's an all traversal um it is kind of a variation of proof force uh and on that end because you're trying every route to to leave paths um it just turns out that they're at most um because they are most n leaves right um because they are most n leaves right which is not even possible but which is not even possible but now that in some you could do some math now that in some you could do some math around that um around that um but anyway okay um but anyway okay um okay so n is at most five thousand so okay so n is at most five thousand so like i said it doesn't even matter so like i said it doesn't even matter so let's go around it so here let's go around it so here naming things is hard but i'm going to naming things is hard but i'm going to go let's just call it go let's just call it recurse now you just call things go recurse now you just call things go as my default value want to be a little as my default value want to be a little bit better here so bit better here so let's just call it partial half sum or let's just call it partial half sum or something like that something like that um and then you keep track of the node um and then you keep track of the node the current path the current path and the current target sum and the current target sum well i just you can do it either way you well i just you can do it either way you could either could either return the current somewhere the targets return the current somewhere the targets or the current or the current targets some left by keep on subtracting targets some left by keep on subtracting it right so it doesn't really matter it right so it doesn't really matter um yeah and then here if node is none we um yeah and then here if node is none we just return just return i don't know you shouldn't get through i don't know you shouldn't get through that if no it's not none in this case that if no it's not none in this case and we won't check it where there's a and we won't check it where there's a leaf one thing that i tried to be leaf one thing that i tried to be too clever in the past is is um but now i'm trying i just be explicit about it uh because it's just just do it it's you know it's a symbol and anyway if this is a leaf then if current sum is you go to target sum then we do some magic with the path right so current path let's just say we have a list of answers or paths then we just do path start append current path and one thing that's got a caveat here especially for python users might depend on other you depend on your language um and you'll go into this a little bit but depending how you construct this current path um you may be copying the pointer instead of the actual list content so the thing that i would do here is just do this and what this does is is just do this and what this does is that it creates a new slice of a list in that it creates a new slice of a list in python anyway python anyway a new slice of list that starts from the a new slice of list that starts from the beginning to the end beginning to the end essentially making a copy of the list essentially making a copy of the list anyway and then we anyway and then we uh well we return in in both cases uh well we return in in both cases and then now if it is not a leave then and then now if it is not a leave then we just do a recursion on the left and we just do a recursion on the left and the right the right um yeah so partial path um yeah so partial path sum in this case you have node.left sum in this case you have node.left current path plus um let's see oh yeah right or that value i suppose there's a couple you can do it in two different ways and you could for example do something like this uh where is it know that value and then you do current path or you could just do current path and this i think this actually creates a new list anyway so i don't know how you feel about that per se it does create a lot more space so let's just do it the responsible way and then here we have current sum plus note that value and then here we have to pop off the thing that we just added um and now we go to the right oh actually well you could do it i guess they're actually you can prematurely optimize a little bit which is the same except for it's this right so in this case obviously these things canceled out so let's just do this yeah i think we're good here so now we yeah i think we're good here so now we just have to kick it off with power just have to kick it off with power sum of uh sum of uh root target root target sum oh no this is zero sum oh no this is zero and then we return paths so there are and then we return paths so there are actually also a couple of alternate ways actually also a couple of alternate ways to do it as well to do it as well you can make it so that this actually you can make it so that this actually returns a list and but then you have to returns a list and but then you have to go through it every time to go through it every time to um but as you go up to kind of um but as you go up to kind of reconstruct the path reconstruct the path maybe that's better i don't know you you maybe that's better i don't know you you let me know how you feel about it let me know how you feel about it but they're just different ways of doing but they're just different ways of doing it uh okay well that's not promising perhaps some mistakes were made now i can't imagine this well i mean this actually would be right because it doesn't have any answers but this is discerning hmm did i miss something that's weird that's weird trying to do this maybe trying to do this maybe so you i would imagine it complains if so you i would imagine it complains if it doesn't but uh but if you have a it doesn't but uh but if you have a silly silly some minus silly thing here but okay i mean i don't think i spot anything obvious in my silliness so yeah let's print our current path here let's see if we at least get to the end um okay so we don't do that at all do i try at least get two leaves okay so i do get two leaves for x oh oh i'm just being silly basically if i get to the leaf i do not consider the current node value okay i this is a an okay i this is a an edge case but on the tree variety where edge case but on the tree variety where i actually start from zero instead of i actually start from zero instead of the root note the root note you can actually do this in a couple of you can actually do this in a couple of ways i think i did it this way for ways i think i did it this way for whatever reason whatever reason and yeah um oh yeah and yeah um oh yeah just being very silly uh just being very silly uh because then here because we added the because then here because we added the sum so now sum so now it's good but then now we also want to it's good but then now we also want to add to the current path add to the current path as well uh so if this is good then let's as well uh so if this is good then let's just say on path dot just say on path dot append and then currentpath.pop okay so this should be good a lot of a little bit sloppy here maybe we could have done it in a way that has better base cases but um but let's let's give us a minute i'm well totally confident about it every time i say that you should get one but this time it is accepted um as we said this is going to be linear time because the actual expensive part of this and i the actual expensive part of this and i don't know don't know that there's any easy way to avoid it is that there's any easy way to avoid it is actually actually like we said this is the number of like we said this is the number of current paths um i think in a given a current paths um i think in a given a full yeah given a full binary full yeah given a full binary tree you can imagine this log tree you can imagine this log no no that means that there's n over two no no that means that there's n over two leaves and we reconstruct leaves and we reconstruct n over two leaves and each path n over two leaves and each path is locked and i suppose in that case is locked and i suppose in that case five thousand five thousand like out of five thousand is uh like like out of five thousand is uh like what twenty what twenty no not twenty uh 12 guys no not twenty uh 12 guys so 12 times 2500 i guess that so 12 times 2500 i guess that so that's the only thing that i worry so that's the only thing that i worry about uh and i'm trying to kind of be a about uh and i'm trying to kind of be a little bit tighter about it little bit tighter about it i mean i already got accepted but if you i mean i already got accepted but if you want to consider because this is the want to consider because this is the expensive part expensive part um and that's also the space as well um and that's also the space as well it's that in the worst case in a full it's that in the worst case in a full tree tree then you have n over two leaves is anal then you have n over two leaves is anal beliefs the worst case yeah i think so i'm also trying to think about the other one where it is not binary but and in that case you can have a weird amount of space issue in that case it'll be five dollars i think you can actually get it to a case where memories actually end square ish um you know the time i think should still be no i think the answer is n square and the the case that i have here maybe just visualize it will help a little bit is that in the worst case i don't have a full binary tree maybe the worst case but actually i think the worst case is actually something like um let's see if this works i don't know if this is the right format but yeah so you have something like this oops [Music] i don't know if i'm doing it right let's see okay so something like this um okay well okay well uh so now one two nope okay so something like this right so okay so something like this right so the idea behind this input set the idea behind this input set uh okay is that well uh okay is that well they're gonna be n over two leaves but they're gonna be n over two leaves but the space is gonna be the space is gonna be um and you can actually do this in a i um and you can actually do this in a i actually think i messed up with the actually think i messed up with the target um actually target um actually well if you put it always zero i think well if you put it always zero i think that would because i think this is yeah that would because i think this is yeah so if this is all zero then this can so if this is all zero then this can actually happen right where actually happen right where then now your path is gonna be n over then now your path is gonna be n over two two and then n over two minus two n over two and then n over two minus two n over two minus four and dot dot dot minus four and dot dot dot and it becomes n squared essentially and it becomes n squared essentially right so in that case right so in that case the worst case scenario for this is the worst case scenario for this is actually n squared actually n squared um and n and um um and n and um n squared time and square space so the n squared time and square space so the nuance here is that the current path nuance here is that the current path matters matters if you did not have to care about if you did not have to care about current pattern let's say you're trying current pattern let's say you're trying to return only to return only the num the count of the number the num the count of the number of um paths then it actually is linear of um paths then it actually is linear time time but because you have to do this copy to but because you have to do this copy to kind of copy into extra space and you kind of copy into extra space and you cannot be cannot be do better than n square space in this do better than n square space in this case because case because that is the number of like you have to that is the number of like you have to allocate the space for n squared allocate the space for n squared space anyway because that's the size of space anyway because that's the size of your solution your solution so that is that is the lower bound for so that is that is the lower bound for this problem in that case right this problem in that case right so so yeah so it's linear time plus so so yeah so it's linear time plus the output sensitivity which is um the output sensitivity which is um average and square quadratic average and square quadratic anyway um yeah that's all i have for anyway um yeah that's all i have for this one let me know what you think hit this one let me know what you think hit the like button to subscribe and join me the like button to subscribe and join me in discord in discord happy wednesday or whatever stay good happy wednesday or whatever stay good stay healthy to good mental health i'll stay healthy to good mental health i'll see you later see you later bye | 2024-03-21 10:47:59 | 113 | 113. Path Sum II - Day 4/31 Leetcode August Challenge |
|
cTPXc1aUWYY | homes [Music] baby baby | 2024-03-19 18:25:34 | 27 | Leetcode: Remove Element #coding #leetcode #shorts #code #youtubeshorts #youtuber #interview #job |
|
E8qWNmYj8Ko | okay kids we're here for insertion sort lists now first of all insertion sort lists now first of all before beginning before beginning whenever you want to deal with linked whenever you want to deal with linked lists lists or sorry when you want to learn about or sorry when you want to learn about them i recommend them i recommend going here at this particular address going here at this particular address link list problems link list problems and linked list basics over here as well and linked list basics over here as well and this is from stanford as well as and this is from stanford as well as all the associated lessons on binary all the associated lessons on binary trees and pointers trees and pointers you start off with pointers then you you start off with pointers then you move on to linked lists move on to linked lists and then you move on to binary trees and and then you move on to binary trees and you're golden you're golden this tells you everything you need to this tells you everything you need to know in so far as know in so far as linked lists and binary trees and it's linked lists and binary trees and it's actually explained actually explained in english okay in english okay let's get going so given the head of a let's get going so given the head of a singly linked list singly linked list sort the list using insertion short sort the list using insertion short insertion sort insertion sort and returned the sorted list as head the and returned the sorted list as head the steps over steps over of an insertion sort algorithm are of an insertion sort algorithm are so the insertion sort iterates consuming so the insertion sort iterates consuming one one input element each repetition and input element each repetition and growing a sorted growing a sorted output list well let's just see what it output list well let's just see what it does here okay does here okay so they have the little image um which so they have the little image um which is moving at a stale is moving at a stale snail's pace but essentially you take an snail's pace but essentially you take an unsorted list unsorted list and you create a new one that's sorted and you create a new one that's sorted that's it okay let's uh let's do that so that's it okay let's uh let's do that so that's what it tells you to do that's what it tells you to do you return the node pointing to you return the node pointing to the head of the new list that's all you the head of the new list that's all you want to do want to do so how do we get started here so how do we get started here first thing we do is um first thing we do is um we create we want to iterate through we create we want to iterate through and they actually tell you what to do so and they actually tell you what to do so you iterate through you iterate through the current list which is what they give the current list which is what they give you and you and at each at each iteration you remove at each at each iteration you remove one element from the list and then you one element from the list and then you just insert into just insert into into the new list in its sorted order so into the new list in its sorted order so okay so we'll come up with a current okay so we'll come up with a current pointer that points to pointer that points to so we don't lose the the head pointer so we don't lose the the head pointer that's one thing we don't want to lose that's one thing we don't want to lose over here um over here um we don't lose the head pointer but we don't lose the head pointer but actually actually that wasn't necessary here but in most that wasn't necessary here but in most cases cases it is we also want to create it is we also want to create a new list and set it to null a new list and set it to null right now that new list has nothing um right now that new list has nothing um now while current now while current not equal null and this is kind of not equal null and this is kind of standard standard standard nomenclature to iterate standard nomenclature to iterate this is your format this is how you move this is your format this is how you move from from one node to the next each time you one node to the next each time you iterate you just go to the next one and iterate you just go to the next one and if it's ever null it gets out of this if it's ever null it gets out of this loop loop that's it um so that's it um so we want to identify the we want to identify the list node what do we we're going to call list node what do we we're going to call it my insert node it my insert node and this is the current node that we're and this is the current node that we're going to remove from going to remove from the all list and place into the news the all list and place into the news list so list so that's going to be equal to current then that's going to be equal to current then current current um then current um then current will already be equal to current.next um we actually don't need our current.next over here since we we just went there okay so we just went there and that's how we do it now we're dealing with we want to know how to deal with this my insert node over here so we want to take this my insert note that we removed and put in the new list well the first thing we want to do is make it kind of um we want its next pointer to point to um we want its next pointer to point to nothing nothing so so far we don't know where that next so so far we don't know where that next pointer is going to pointer is going to oh sorry it's my insert node and then we're we're going to have to create some sort of magic function here which is going to to take the new list as a parameter and that's it as we iterate through the and that's it as we iterate through the list list as we iterate through the list we as we iterate through the list we identify the current node we remove it identify the current node we remove it so we set its next pointer equal to so we set its next pointer equal to nothing nothing so at this point this is an individual so at this point this is an individual node and nothing's pointing to it node and nothing's pointing to it uh and then we insert into the new list uh and then we insert into the new list okay okay so let's come up with that insert so let's come up with that insert node method node method which we said would take a list which we said would take a list node star and it's important to put this node star and it's important to put this ampersand ampersand y because we might modify the head of y because we might modify the head of the new list the new list not only might we will so we're going to not only might we will so we're going to call this new list call this new list and we want to pass and we want to pass in the um in the um the insert node by uh the insert node by uh by value actually so that's my by value actually so that's my insert node over here um yeah insert node over here um yeah or yeah we could just stay or yeah we could just stay phone ringing i'll just interrupt good lord where were we oh yeah well that call was actually from facebook go figure um let's get on with this we're doing this insert node type of function which which works with this thing over here as we're iterating through all of the nodes from our original list we're going to split them from that list and insert them into the new one so the first thing that you might want to this is well if if the new list is null then you um then new list equals um equals inst my insert node that's it because if there's nothing then the first element will be that first insert node um now let's see now else if now if you want to check well where to insert this before the head or after the head somewhere down else if else if my insert node val smaller or equal to new list dot val so remember that when you talk about the new list it's always the first element if that's the case then you just want to take your my insert node and have it point to uh to the new list then you want your due list to become my insert node again all of this is made much easier if you read those stanford problems which will grill you with this type of you could say this type of nomenclature um else so if it doesn't come before it necessarily comes after the first node in the new list uh you have to iterate within the new uh you have to iterate within the new list and um list and um and see where exactly you want to place and see where exactly you want to place this thing this thing so we use our our little model so we use our our little model while current not equal to null while current not equal to null and we immediately write our current and we immediately write our current equals equals current.next again this is our model for current.next again this is our model for how to iterate how to iterate down a list we say down a list we say well we say okay so what we're checking well we say okay so what we're checking for for is is um is is um okay we want to check whether there's a okay we want to check whether there's a pointer after pointer after meaning if is there a node after the one meaning if is there a node after the one we're currently on within the new list we're currently on within the new list and if so uh and if so uh if so or actually let's check if it's if so or actually let's check if it's null null and if it's not null then necessarily and if it's not null then necessarily our insert node would be our insert node would be bigger than the current one so if that's bigger than the current one so if that's true then true then we send the next node of the current one we send the next node of the current one that we're on that we're on to the insert node and then we just to the insert node and then we just return so let's just write that down return so let's just write that down if current dot next if current dot next equals null so if there's nothing after equals null so if there's nothing after and and our my insert our my insert node bigger node bigger or equal to current.val if that's the case then then we could just then we could just how would we do this oh yeah we sent current dot next equals my insert node so there's nothing after so we don't need to worry about the one that comes next and then we just return so we didn't affect the head pointer we could just return [Music] if we could put an elsif but since we have the return here it would never hit this if in any case so we could just do another if here so if insert i'm sorry if my insert node val bigger equal to current the val and so now we and my insert node node.val and my insert node node.val smaller or equal to current.next.val okay don't try this at home kids then you set my insert node dot next equals current dot next okay so you're saying we want to place this in between your cur in between our current node and our next node suddenly it's the new node that's going to be pointing to the next node our current node will be pointing to my our current node will be pointing to my insert insert node so that's all we do we set our node so that's all we do we set our current one to point to current one to point to the one that we want to insert and the the one that we want to insert and the insert node pointing to insert node pointing to what's our current next node what's our current next node and then we could return um and then we could return um i think we're all set let's see what i think we're all set let's see what happens if we run the code happens if we run the code error expected and qualified id what's error expected and qualified id what's its problem here its problem here 50. well current oh while current not equal null what am oh while current not equal null what am i doing i doing okay non-void function okay non-void function line 57 oh yeah well we just created a new list so we want to return and we okay looks like it worked here and we okay looks like it worked here what if we do submit what if we do submit and we have a winner thanks a lot and we have a winner thanks a lot everyone | 2024-03-21 12:55:35 | 147 | LeetCode 147: Insertion Sort List C++ In Plain English (Apple Interview) |
|
CWTjs46kl5U | all right let's take a look at leak code 1406 stone game three at leak code 1406 stone game three i think this is an incredibly good i think this is an incredibly good problem it's a dp problem problem it's a dp problem and i think it's uh it's a golden and i think it's uh it's a golden standard of dp standard of dp problems to be honest with you you know problems to be honest with you you know you can start with a naive you can start with a naive backtracking approach and then you can backtracking approach and then you can create a create a cache to to cache your results and then cache to to cache your results and then you can turn it into you can turn it into you know a dp memorization you know you know a dp memorization you know still top down and then from the still top down and then from the recursive top down you can recursive top down you can optimize that even more and turn it into optimize that even more and turn it into a a iterative bottom-up dp so this is just a iterative bottom-up dp so this is just a great great full application of dp full application of dp and yeah i want to walk you through the and yeah i want to walk you through the english algorithm english algorithm and help you understand how to uh how to and help you understand how to uh how to how to uh see the recurrence relation how to uh see the recurrence relation and be able to and be able to understand the the dp aspect understand the the dp aspect i have both the answers to the recursive i have both the answers to the recursive solution and the iterative solution solution and the iterative solution you can see that later and you can check you can see that later and you can check my github for that as well in the my github for that as well in the description description but um yeah so the problem is as follows but um yeah so the problem is as follows so we're given a list of values so we're given a list of values you know stones and so there's two you know stones and so there's two players alice and bob players alice and bob alice goes first always and then it's alice goes first always and then it's bob and then it's alice bob and then it's alice and they they just keep alternating and they they just keep alternating after that so we want to see who after that so we want to see who is the winner here and so uh is the winner here and so uh so they tell us how the scoring works so so they tell us how the scoring works so at each turn at each turn you know alice or bob's turn that player you know alice or bob's turn that player can can has three choices they can either take has three choices they can either take one stone one stone they can take two stones or they can they can take two stones or they can take three stones and the score of that take three stones and the score of that turn is just turn is just the sum of the stones that they take the sum of the stones that they take right so if they take just one stone right so if they take just one stone they have they have one point if they take these two stones one point if they take these two stones then they'll have three points if they then they'll have three points if they take take all three if they take three stones then all three if they take three stones then they'll have six points they'll have six points right so we want to um at the end we right so we want to um at the end we want to see who is going to win want to see who is going to win and it tells us that both players are and it tells us that both players are going to play optimally so going to play optimally so um basically what that means is each um basically what that means is each players is players is you know going to try to maximize their you know going to try to maximize their their possible score at each turn their possible score at each turn yeah so i guess it's pretty yeah so i guess it's pretty straightforward if if all the numbers straightforward if if all the numbers are positive are positive um because then we can just greedily you um because then we can just greedily you know know you know the best choice at each turn is you know the best choice at each turn is always just to take always just to take all three stones you know take as many all three stones you know take as many stones stones as there are possible right let's just as there are possible right let's just do this first example here and see do this first example here and see um how this plays out so alice goes um how this plays out so alice goes first so first so you know her best choice is to take all you know her best choice is to take all three stones here and she'll get a three stones here and she'll get a a total score of six and then bob will a total score of six and then bob will be left with just this one stone here be left with just this one stone here and he'll take that and get seven so bob and he'll take that and get seven so bob wins in that situation wins in that situation what are the other choices that alice what are the other choices that alice has alice could have also has alice could have also just taken one stone and then bob just taken one stone and then bob probably would have just taken the rest probably would have just taken the rest of them and won by a crushing margin of them and won by a crushing margin or alice could have started off by or alice could have started off by taking these two and then bob would taking these two and then bob would probably just end up probably just end up you know taking these two as well and you know taking these two as well and then winning by a crushing margin then winning by a crushing margin so um in all these situations bob is the so um in all these situations bob is the winner winner so um but it does tell us that alice and so um but it does tell us that alice and bob bob play optimally right so so out of these play optimally right so so out of these three options three options that alice has she's going to choose the that alice has she's going to choose the option which option which um you know benefits her the most right um you know benefits her the most right so she's going to so she's going to we know for a fact that she's going to we know for a fact that she's going to take three stones take three stones and then bob will be left with just the and then bob will be left with just the seven so so even when alice plays seven so so even when alice plays optimally optimally by taking these first three stones she by taking these first three stones she still loses still loses um yeah so let's also let's look at um yeah so let's also let's look at another example with with negative so another example with with negative so this is a case where we can't just do a this is a case where we can't just do a greedy approach and greedy approach and and take the first three stones um right and take the first three stones um right because let's let's see because let's let's see what happens if alice takes the first what happens if alice takes the first all three stones right all three stones right if she takes all three stones at once if she takes all three stones at once then she'll have negative six then she'll have negative six and bob will be left with zero bob's and bob will be left with zero bob's score will have not score will have not changed bob will be at zero and alice changed bob will be at zero and alice will be at negative six will be at negative six so bob wins let's see let's see so bob wins let's see let's see how alice can optimize this first turn how alice can optimize this first turn she can actually she can actually just take the first two stones and be just take the first two stones and be left with a negative three score left with a negative three score and then bob will also pick up the last and then bob will also pick up the last stone which is negative three stone which is negative three so in this scenario when alice takes so in this scenario when alice takes just the first two stones just the first two stones then they they have a tie let's let's then they they have a tie let's let's check the last option if alice takes check the last option if alice takes um the negative one then bob will um the negative one then bob will just take the negative two and then just take the negative two and then alice will be forced to take the alice will be forced to take the negative three in the last turn negative three in the last turn so this situation alice loses because so this situation alice loses because alice has negative four and bob has alice has negative four and bob has negative two negative two so the optimal turn for so the optimal turn for alice is to take the two stones right so alice is to take the two stones right so that's how we end up with the answer of that's how we end up with the answer of a tie a tie so we can see that greedy won't work so we can see that greedy won't work because because you can't just you know blindly take you you can't just you know blindly take you know all three stones know all three stones at every given turn right because at every given turn right because there's negative values and it could be there's negative values and it could be worse for you worse for you um and yeah um and yeah so and also you can't necessarily just so and also you can't necessarily just take take the the least amount if it's all the the least amount if it's all negatives right negatives right right because the best option here it right because the best option here it looks like it would be negative one looks like it would be negative one but then bob could also just only take but then bob could also just only take one one stone and then force alice to take the stone and then force alice to take the last stone last stone right so we have to we have to explore right so we have to we have to explore every every path to the end so so that's why dynamic path to the end so so that's why dynamic programming is the approach here we programming is the approach here we can't just greedily can't just greedily you know compare these stones and say oh you know compare these stones and say oh we're going to take we're going to take the stone piles that add up to the the the stone piles that add up to the the most most the max value that that doesn't work the max value that that doesn't work because we have to alternate turns and because we have to alternate turns and we have to we have to yeah i mean there's too many paths to yeah i mean there's too many paths to explore and explore and dynamic programming is the only way to dynamic programming is the only way to do this so do this so let's uh yeah so let's uh yeah so okay let me think about where to even okay let me think about where to even start with this so let's first start with this so let's first um kind of visualize this as a tree um kind of visualize this as a tree right so right so basically at any given um basically at any given um at any given turn that player has three at any given turn that player has three choices choices like i said they can take just the first like i said they can take just the first stone stone um they can take just the second they um they can take just the second they can take the first two stones or they can take the first two stones or they can take the first three stones can take the first three stones and um the reason you see this minus and um the reason you see this minus you know this minus f of 237 what this you know this minus f of 237 what this is expressing is basically the sub is expressing is basically the sub problem of problem of 237 so pretty much 237 so pretty much if alice were to just take the first if alice were to just take the first stone stone then the way that you would account for then the way that you would account for what bob is going to take what bob is going to take is by subtracting the sub problem at 237 is by subtracting the sub problem at 237 and um yeah and um yeah okay so let's let's first kind of define okay so let's let's first kind of define the dp the dp um table and it's just going to be an um table and it's just going to be an array it's not a table but let's define array it's not a table but let's define what dp of i what dp of i represents so at each dp index dp of i represents so at each dp index dp of i is going to store the best difference is going to store the best difference aka alice minus bob and uh the reason we aka alice minus bob and uh the reason we do alice minus bob is because alice do alice minus bob is because alice always goes first always goes first and um yeah it's uh and um yeah it's uh yeah i guess that's the only reason you yeah i guess that's the only reason you would store alice versus would store alice versus minus bomb as opposed to the other way minus bomb as opposed to the other way around around and if you did the other way around i and if you did the other way around i don't there's no way it would work so don't there's no way it would work so um yeah and what the i stands for is um yeah and what the i stands for is if if the list of stones were to start if if the list of stones were to start at that index at that index um so if we started that index um so if we started that index uh let's say this is this is an x3 right uh let's say this is this is an x3 right so the answer to dp of three so the answer to dp of three um dpf3 is representing um dpf3 is representing the list of stones from three until the the list of stones from three until the end of the list end of the list so it would just be seven so dp of two so it would just be seven so dp of two would represent the list of stones from would represent the list of stones from three to the end and then you know yada three to the end and then you know yada yada like yada like dp of one would represent the best dp of one would represent the best answer for answer for um the stone two three and seven um the stone two three and seven okay so let's take a look at um let's take a look at an example here and then i think i'll try to um kind of revisit this recursive tree and show you uh you'll have a better understanding of this tree once i go through this quick example here so um right so like i said dp of 2 is going to represent the best answer if the list of stones was just 7 to the end right and that's just the stone seven so um let's write this out right so so what's the best score that alice can get you know the best difference between alice and bob's score if the list of stones was just seven right alice only has one choice in this situation she she has to take this one stone right you know her three options at every turn are either take one stone take two stones or take three stones and if there's only one stone then she has to take it so alice has a score of alice has seven and bob has zero um yeah if bob doesn't take anything then his score is just zero so the difference is so the best difference between them is seven and um that's why for this dp and um yeah so now let's move on to and um yeah so now let's move on to um if the if the list of stones was six um if the if the list of stones was six seven so let's see the uh different seven so let's see the uh different choices choices so alice can either take the first stone so alice can either take the first stone and then bob takes the seven and then bob takes the seven or alice can take both stones at the or alice can take both stones at the same time and then bob has zero same time and then bob has zero so let's write these two options out so so let's write these two options out so alice can take alice can take so alice takes six and then bob takes so alice takes six and then bob takes seven so that difference is negative one seven so that difference is negative one right because alice has a score of six right because alice has a score of six bob has a score of seven bob has a score of seven so alice minus bob is negative one let's so alice minus bob is negative one let's see the other situation see the other situation alice takes six plus seven so so alice takes six plus seven so so alice has 16 or 13 and then bob has alice has 16 or 13 and then bob has zero so then the difference is 13 right zero so then the difference is 13 right 13 minus 0 is 13. 13 minus 0 is 13. so at each given turn right we want to so at each given turn right we want to play optimally play optimally so alice is going to choose the option so alice is going to choose the option that gives her the best difference that gives her the best difference the maximum difference so she's going to the maximum difference so she's going to choose this second option so she's going choose this second option so she's going to take to take these two stones at the same time and these two stones at the same time and her difference is 13. her difference is 13. so the answer to this sub problem is 13. so the answer to this sub problem is 13. so dp of 1 is 13. and then let's see so dp of 1 is 13. and then let's see if the list of stones was five six seven if the list of stones was five six seven then how would we express this so alice then how would we express this so alice can take just the first stone so so can take just the first stone so so alice has a score of five alice has a score of five and then um so then bob is left with six and then um so then bob is left with six seven right so what what is bob's best seven right so what what is bob's best choice here well we actually just choice here well we actually just calculated the best calculated the best you know answer for um if you know answer for um if the list of stones was six seven right the list of stones was six seven right that was our previous sub problem that that was our previous sub problem that we just solved we just solved so we already know from the previous sub so we already know from the previous sub problem that the best answer problem that the best answer the the back the max score for for a the the back the max score for for a list list of six seven is 13 so bob is going to of six seven is 13 so bob is going to have 13 have 13 and so the difference between these two and so the difference between these two is negative eight so 5 minus 13 is is negative eight so 5 minus 13 is negative 8. negative 8. so let's look at the other option alice so let's look at the other option alice can take 2 stones can take 2 stones so 5 plus 6 is 11 so she has 11 so 5 plus 6 is 11 so she has 11 and then bob is left with just this 7 so and then bob is left with just this 7 so bob is going to take that bob is going to take that so then bob has 7 and the difference so then bob has 7 and the difference between them is four between them is four right so then let's look at the third right so then let's look at the third option so alice can take all three option so alice can take all three and if alice takes all three she has 18 and if alice takes all three she has 18 and then bob has zero so then the and then bob has zero so then the difference is difference is 18. so you can see here that out of 18. so you can see here that out of these three choices these three choices alice is going to choose the best one alice is going to choose the best one for her and that's for her and that's the one which gives her the difference the one which gives her the difference of 18. of 18. so she's going to choose that and her so she's going to choose that and her answer at gp of 0 is 18. answer at gp of 0 is 18. so you can kind of see now going back to so you can kind of see now going back to this tree why we have to do this tree why we have to do one minus the sub problem here right one minus the sub problem here right because uh because uh um like i said earlier like in this um like i said earlier like in this example when alice example when alice takes just the five then um takes just the five then um the best option for bob is the best option for bob is uh you know you know the best option uh you know you know the best option for the list of just six seven is uh for the list of just six seven is uh the is stored in the dp that we just the is stored in the dp that we just calculated before that calculated before that so yeah so that's what this expression so yeah so that's what this expression here here is basically uh you know it's going to is basically uh you know it's going to return return the answer of the best possible the answer of the best possible difference difference if the list of stones is two three seven if the list of stones is two three seven and then same here and then same here if alice takes one and two the the first if alice takes one and two the the first two stones then two stones then she has to subtract the best answer she has to subtract the best answer at three and seven and the same here if at three and seven and the same here if she takes the first three stones that's she takes the first three stones that's just to subtract just to subtract the best answer for the sub problem of the best answer for the sub problem of just seven just seven and um yeah so you can kind of see how and um yeah so you can kind of see how this recursive branching happens this recursive branching happens um there's three three different options um there's three three different options at each at each turn and then we can follow this path turn and then we can follow this path down so then down so then um for the sub problem of two three um for the sub problem of two three seven the seven the the three different options are we can the three different options are we can take just the two and then we have to take just the two and then we have to subtract subtract the sub problem of three seven or we can the sub problem of three seven or we can take the first two take the first two and then subtract the sub problem of and then subtract the sub problem of seven and then we can take seven and then we can take or we can take the first three stones or we can take the first three stones and then subtract and then subtract um nothing um yeah um nothing um yeah so as you can see we're doing a lot of so as you can see we're doing a lot of repetitive work here like we have repetitive work here like we have f of 7 here we have f of 7 here then we f of 7 here we have f of 7 here then we have f have f of 3 7 here we have f of 3 7 here of 3 7 here we have f of 3 7 here so that's why we need we need to cache so that's why we need we need to cache our answers and our answers and at each recursive call we can just store at each recursive call we can just store our answer in a cache our answer in a cache and then check later if we've already and then check later if we've already come across that come across that so basically you know in a dfs you know so basically you know in a dfs you know this this this call would get hit before um this this call would get hit before um this call here call here so once we find the answer so once we find the answer to this three seven sub problem then to this three seven sub problem then later on later on once we hit it again we can just find it once we hit it again we can just find it in our cache instead of having to in our cache instead of having to you know you know do another recursive you know you know do another recursive call call and and keep going down so yeah that is and and keep going down so yeah that is uh uh the recursive um structure and uh the recursive um structure and uh pretty much the recurrent relation here pretty much the recurrent relation here and um and um yeah i guess like um yeah i guess like um it's pretty straightforward if you know it's pretty straightforward if you know there's there's pretty much like there's there's pretty much like you can kind of categorize the you can kind of categorize the situations into three different situations into three different situations right situations right if if if list of stones if if there's if if if list of stones if if there's only one stone then obviously the answer only one stone then obviously the answer to that sub problem is just that stone's to that sub problem is just that stone's value right value right like if we just have seven then like if we just have seven then obviously the best difference obviously the best difference is just seven um so then the the second is just seven um so then the the second situation situation is if there's two stones is if there's two stones actually wait i have all this written actually wait i have all this written out up here so um yeah out up here so um yeah when there's one stone alice's scourge when there's one stone alice's scourge is just that stone is just that stone um it doesn't matter whose it is it's um it doesn't matter whose it is it's just the best score just the best score the best score is just that stone so the best score is just that stone so when there's two stones when there's two stones alice's score is either um take alice's score is either um take both stones or it's stone one minus both stones or it's stone one minus stone two stone two um right um right when we had the uh when we had the when when we had the uh when we had the when we had the we had the six seven it was either we we take six seven it was either we we take just one and subtract um the seven right just one and subtract um the seven right like we showed earlier so it's either like we showed earlier so it's either six minus seven six minus seven or it's six plus seven um or it's six plus seven um yeah so if there's two stones those are yeah so if there's two stones those are your two options that you have to your two options that you have to consider if you have three or more consider if you have three or more stones then stones then then you consider either you know either then you consider either you know either taking one stone taking one stone which is just the five and then you which is just the five and then you minus the minus the sub problem of six seven or sub problem of six seven or you can do five plus six and then you can do five plus six and then subtract the sub problem subtract the sub problem of um seven or you can take of um seven or you can take five plus six plus seven and subtract an five plus six plus seven and subtract an empty sub problem right empty sub problem right so hopefully you can kind of see the so hopefully you can kind of see the recurrence relation now and i hope that recurrence relation now and i hope that explanation is um helping you explanation is um helping you and then um yeah so i guess and then um yeah so i guess a couple of things you might need to a couple of things you might need to note are that when you create the dp note are that when you create the dp you will have to allocate one extra you will have to allocate one extra space at the end space at the end um and that way you know when you're at um and that way you know when you're at an an empty um um so let's say you you have six seven um you're you're looking at six seven and then you can either okay forget that i don't know how to okay forget that i don't know how to explain that but just just know that explain that but just just know that you'll have to allocate one extra spot you'll have to allocate one extra spot for the dp i can't really think of how for the dp i can't really think of how to explain that on the spot now to explain that on the spot now but um yeah play around with that play but um yeah play around with that play around the dp around the dp um let me think is there anything i'm um let me think is there anything i'm missing missing this is a a pretty heavy problem and this is a a pretty heavy problem and yeah so so at the end you will have to yeah so so at the end you will have to actually actually right so so dp of zero is going to store right so so dp of zero is going to store our best answer our best answer you know the best difference if the list you know the best difference if the list of stones started at index zero of stones started at index zero which it does right so then which it does right so then if our dp if our gp of zero if our dp if our gp of zero is greater than zero then that means is greater than zero then that means alice minus bob alice minus bob was you know a positive number so that was you know a positive number so that means alice had more points than bob means alice had more points than bob if dp of zero is less than zero then if dp of zero is less than zero then that means that means you know bob won if dp of zero is equal you know bob won if dp of zero is equal to zero then it's a time to zero then it's a time so yeah hopefully uh hopefully you can so yeah hopefully uh hopefully you can understand that understand that um yeah i think um yeah i think i think i did as best i can as best i i think i did as best i can as best i could to explain that hopefully could to explain that hopefully hopefully you guys understood that hope hopefully you guys understood that hope you guys you guys learned something from that all right um learned something from that all right um i guess i guess um yeah so also the um yeah so also the with with dp the uh with with dp the uh the um run time will be o n you'll just the um run time will be o n you'll just be looking at uh be looking at uh each number once i believe i believe i each number once i believe i believe i mean it's just a single for loop and mean it's just a single for loop and then you're reference referencing your then you're reference referencing your your gp table each time your gp table each time um yeah so so of n um yeah so so of n runtime and space also of n because you runtime and space also of n because you just have a dp just have a dp allocated yeah that was a that wasn't a half decent explanation hopefully hopefully it was good please give me some feedback i really appreciate all feedback um | 2024-03-21 01:12:18 | 1,406 | Stone Game III: Leetcode 1406 |
|
nS5nxVFFMVs | hey hey everybody this is larry this is day 23 of the august leco daily day 23 of the august leco daily challenge hit the like button to challenge hit the like button to subscribe and join me on discord how was subscribe and join me on discord how was your weekend let me know how everything your weekend let me know how everything went and went and come join me on discord chat about it come join me on discord chat about it anyway today's problem is two sum four anyway today's problem is two sum four input is a binary search tree given the input is a binary search tree given the root of a binary search tree and a root of a binary search tree and a target k returns true if there exists target k returns true if there exists two elements in a binary search tree two elements in a binary search tree such that the sum is equal to the given such that the sum is equal to the given target target um and and i was just checking to see if there any i was just checking to see if there any fun constraints because this is a little bit awkward um this is a little bit awkward um because there's a couple of ways you can because there's a couple of ways you can do it you can do it you can basically basically what you what you ideally what you want what you what you ideally what you want to do is implement like two pointers and to do is implement like two pointers and then kind of slowly merge toward the then kind of slowly merge toward the middle to see kind of thing um middle to see kind of thing um [Music] yeah and then you can do that in in a linear time um and you can and depend on how ambit uh how yeah it depends on how you want to do it yeah it depends on how you want to do it you can definitely do it that way um but because i think i mean i know that there are other ways to do it as well for example you could traverse the tree and then put everything in the hash table or something like that right but that i feel like that isn't in the spirit of i feel like that isn't in the spirit of things but things but you know uh and me using python maybe the most popular way is to use two iterators to be uh to kind of keep it kind of cool and you can kind of do two that first and you can kind of do two that first search with search with um with two stacks instead to kind of um with two stacks instead to kind of pop one another but a lot of that is pop one another but a lot of that is just so contrived and so like weird and just so contrived and so like weird and so tough i don't know if i'm gonna go so tough i don't know if i'm gonna go around and do that today uh it is sunday around and do that today uh it is sunday or monday so i'm a little bit tired it's or monday so i'm a little bit tired it's not a weekend anymore for me to kind of not a weekend anymore for me to kind of do that kind of involved but i would do that kind of involved but i would recommend maybe maybe i think for up recommend maybe maybe i think for up solving what i would recommend you do solving what i would recommend you do especially if you're not using python um especially if you're not using python um just implementing two stacks and then just implementing two stacks and then implement that first search that way um implement that first search that way um and then and then kind of just you know and then and then kind of just you know migrate toward the middle uh to get the migrate toward the middle uh to get the target uh but but yeah because the reason why you can do that it is that it is a binary search tree so you know where to search for the other one and if you do it like in a smart way you and if you do it like in a smart way you can do a linear time if you do it in a can do a linear time if you do it in a more naive way of doing a depth research more naive way of doing a depth research and then search for the other number in and then search for the other number in a tree that's going to be n log a tree that's going to be n log um yeah um yeah so it's kind of weird in that way i'm so it's kind of weird in that way i'm gonna do it the lazy way today to be gonna do it the lazy way today to be frank i'm sorry to disappoint viewers i frank i'm sorry to disappoint viewers i i'm usually starting this live i'm a i'm usually starting this live i'm a little bit slow but but today i'm just a little bit slow but but today i'm just a little bit tired and little bit tired and uh maybe that's my excuse but definitely uh maybe that's my excuse but definitely what i would recommend is try to do it what i would recommend is try to do it uh uh with two different searches with two different searches uh in a very uh in a very kind of tricky kind of way but yeah kind of tricky kind of way but yeah um um okay so let okay so let yeah i'm just gonna do or i'm just gonna yeah i'm just gonna do or i'm just gonna do one definite search to an away and do one definite search to an away and then do it to someone in a way i know then do it to someone in a way i know that this is a binary search tree and that this is a binary search tree and doesn't take advantage of that but it doesn't take advantage of that but it does have over end complexity so so does have over end complexity so so that's my story i'm sticking to it uh that's my story i'm sticking to it uh cool uh let's do that then cool uh let's do that then uh was it inorder no the other one in uh was it inorder no the other one in order now i know this right yeah so this is just typical in order i set so this is just typical in order i set up an array here up an array here and and then we can do this i mean i'm just gonna four one three yeah and then now of course when you do it in order everything is going to be in order but yeah and now okay so then now you have a pointer to the left pointer to the right and then you just do the two sum that way yeah you could do two pointers yeah you could do two pointers back and forth or you could do a hash back and forth or you could do a hash table it doesn't really matter i think i'm i'm well you know what i'm feeling a little bit lazy so i am gonna go lazy the entire way and yeah just use another hash table so and yeah just use another hash table so maybe i'm doing a very competitive maybe i'm doing a very competitive programming way where i just ignore all programming way where i just ignore all the parameters and do it but for an the parameters and do it but for an interview i would definitely definitely interview i would definitely definitely at least talk about these things uh and at least talk about these things uh and do it wherever you can but yeah do it wherever you can but yeah this is already sorted by this is already sorted by i'm a little bit lazy if k minus x and c return true uh i mean this should be good but i uh i mean this should be good but i do feel like i'm cheating today maybe i do feel like i'm cheating today maybe i am cheating today i maybe i need a day am cheating today i maybe i need a day off off mentally a little bit i mean i think mentally a little bit i mean i think this is my like 500 and something day this is my like 500 and something day streak so i'm a little bit tired today i streak so i'm a little bit tired today i think i just didn't sleep well to be think i just didn't sleep well to be honest i have a lot of excuses but honest i have a lot of excuses but but yeah so i think that that's all i but yeah so i think that that's all i have i think i talked about it already have i think i talked about it already uh this is linear time linear space uh this is linear time linear space so it is optimal-ish so it is optimal-ish um like i said you can um like i said you can i don't i think you could reduce this of i don't i think you could reduce this of h space where h is the height of the h space where h is the height of the tree tree so so so that would be more optimal but this so that would be more optimal but this is roughly optimal so that's um you know is roughly optimal so that's um you know yeah that's all i have for this one yeah that's all i have for this one sorry to keep it short quick i hope sorry to keep it short quick i hope y'all have a great day have a y'all have a great day have a great week i will see you later i'm great week i will see you later i'm gonna try to get some sleep bye | 2024-03-20 14:49:06 | 653 | 653. Two Sum IV - Input is a BST - Day 23/31 Leetcode August Challenge |
|
hJZuYCBRm3M | hello friends so today in this video we'll go through the first two problems we'll go through the first two problems from the latest lead code weekly contest from the latest lead code weekly contest to 55 so let's start the first problem to 55 so let's start the first problem is not too difficult it states that is not too difficult it states that you're given and you have to find out you're given and you have to find out the greatest common divisor of an array the greatest common divisor of an array so the problem is asking you that you so the problem is asking you that you are given an array nums okay and you are given an array nums okay and you have to find out the gcd have to find out the gcd of the smallest number and the largest of the smallest number and the largest number in that edit so you just have to number in that edit so you just have to what you can do that you have to first what you can do that you have to first find out the smallest number and the find out the smallest number and the largest number in that area and just largest number in that area and just find out the gcd using c plus plus s2 find out the gcd using c plus plus s2 so that's what i've done here uh first so that's what i've done here uh first find out the maximum number and the find out the maximum number and the minimum number using these functions and minimum number using these functions and then just do a gcd of the maximum and then just do a gcd of the maximum and minimum number so it's not too difficult minimum number so it's not too difficult it's just a very simple problem the next it's just a very simple problem the next problem is find unique binary strings it problem is find unique binary strings it states that you are given an array of states that you are given an array of strings nums and it contain n unique strings nums and it contain n unique binary strings of length n binary strings of length n so all the strings are of length n and so all the strings are of length n and they are binary strings now return a they are binary strings now return a binary string of length n as well that binary string of length n as well that does not appears in that numbers area does not appears in that numbers area okay then there can be multiple answers okay then there can be multiple answers then you have to return the answer uh then you have to return the answer uh any of them any of them now what you can see here is that there now what you can see here is that there are two strings this zero one and one are two strings this zero one and one zero and you have to again find out a zero and you have to again find out a binary string which is not here but it binary string which is not here but it is also of length two is also of length two now what you can simply see here is that now what you can simply see here is that n length is only 16 so if you just do 2 n length is only 16 so if you just do 2 to the power 16 because how many total to the power 16 because how many total number of binary strings are there so if number of binary strings are there so if you just find out that 2 to the power 16 you just find out that 2 to the power 16 is around 65 000 and it can be easily is around 65 000 and it can be easily done in a brute force way also so what done in a brute force way also so what you can simply do here is just try to you can simply do here is just try to generate all the possible strings of generate all the possible strings of length n length n and then and then just check that whether that particular just check that whether that particular string s is in this particular area or string s is in this particular area or not so before that what you can do here not so before that what you can do here is uh is uh you just store all these strings in some you just store all these strings in some set because then to find out any string set because then to find out any string it becomes easier it will become o of it becomes easier it will become o of log n instead of log n log n instead of log n like log n instead of n and then what like log n instead of n and then what you can simply do here is just try to you can simply do here is just try to form all the binary strings of length n form all the binary strings of length n now how you can do that they can have now how you can do that they can have multiple ways uh you can but the multiple ways uh you can but the simplest way is like using some sort of simplest way is like using some sort of dfs sort of thing so in which means that dfs sort of thing so in which means that i have an empty string i have an empty string and maybe i want a string of length two and maybe i want a string of length two in which in which binary strings of length two because binary strings of length two because it's empty now so i have two option i it's empty now so i have two option i can fill the first position with zero can fill the first position with zero and the first position with one and the first position with one so it's like a string with only zero so it's like a string with only zero and i want that the total end should be and i want that the total end should be two it's like a function call and two it's like a function call and the string is of length one only or like the string is of length one only or like the string is having only one character the string is having only one character one and we want actually the length two one and we want actually the length two then we again call this then we again call this and it will become like zero one and one zero zero here actually for every string till that string becomes equal to n the length of that you keep on iterating or like keep on adding 0 1 0 1 and calling that function again forming like a binary tree just like 1 0 and now as you can see here is that the now as you can see here is that the string length has become equal to 2 string length has become equal to 2 okay now at this point what you will see okay now at this point what you will see you will just match that whether this you will just match that whether this particular string is in that set or not particular string is in that set or not if it is not just stored that particular if it is not just stored that particular answer and you just return on that answer and you just return on that answer so that's the logic for this answer so that's the logic for this problem as well i'll show the code part problem as well i'll show the code part now so now so the code is yeah here so we'll first the code is yeah here so we'll first insert all the particular nums actually insert all the particular nums actually all the strings into some set this is all the strings into some set this is some global set some global set and then what we'll do we'll iterate and then what we'll do we'll iterate over over and find out the length of one of the and find out the length of one of the strings which is n strings which is n then do a dfs call with an empty string then do a dfs call with an empty string and total length of the string finally and total length of the string finally should be n should be n and return out the answer which is a and return out the answer which is a global global uh string also in this gfs call we'll uh string also in this gfs call we'll stop when stop when our actual my call our actual my call or my total string becomes length n at or my total string becomes length n at that case what we'll do here is we'll that case what we'll do here is we'll check that whether that string is not in check that whether that string is not in the set the set and also and also that whether that string is not empty that whether that string is not empty what we'll do here is we'll check that what we'll do here is we'll check that whether that global string should not be whether that global string should not be empty if it is already holding some empty if it is already holding some string why to insert one more string i string why to insert one more string i just want one answer because they can be just want one answer because they can be multiple answers i just want one answer multiple answers i just want one answer so the string so the string which is answer variable if that is which is answer variable if that is empty and also that particular string empty and also that particular string which we have found out is which we have found out is actually not in the set just make your actually not in the set just make your answer equal to that particular string answer equal to that particular string of length n and return out else of length n and return out else call that dfs function again adding 0 call that dfs function again adding 0 and adding 1 and that's the logic for and adding 1 and that's the logic for this problem uh it's just a recursive this problem uh it's just a recursive problem uh brute force requires a problem uh brute force requires a problem i hope you understand the logic problem i hope you understand the logic and the good part for this problem if and the good part for this problem if you still have any doubts you can you still have any doubts you can mention now i will say this one and they mention now i will say this one and they keep coding and bye | 2024-03-25 13:06:40 | 1,979 | Leetcode Weekly Contest 255 | LEETCODE PROBLEM 1979 , 1980 | LEETCODE |
|
bpDsg8OGcs0 | hey hey everybody this is larry this is me going over q4 me going over q4 of the uh weekly contest 242 of the uh weekly contest 242 stone game eight so hit the like button stone game eight so hit the like button hit the subscribe button join me on hit the subscribe button join me on discord let me know what you think about discord let me know what you think about this problem this problem so this one i actually spent way too so this one i actually spent way too long long on the greedy solution and the greedy on the greedy solution and the greedy was that i always just was that i always just take the maximum score and the prefix take the maximum score and the prefix sum um and sum um and that was just wrong so it doesn't you that was just wrong so it doesn't you know you don't have to worry about that know you don't have to worry about that one one uh or what that means but you you uh or what that means but you you you should note um the prefix sum for you should note um the prefix sum for this one and there's this one and there's there's a really weird uh this is the there's a really weird uh this is the first observation you need to make about first observation you need to make about this problem this problem which is that and don't look at solution which is that and don't look at solution to oops don't peek at the solution to oops don't peek at the solution quite yet i'm just using this as scratch quite yet i'm just using this as scratch pad but the idea is that okay pad but the idea is that okay you know let's say i make a move and i you know let's say i make a move and i make take the first four numbers right make take the first four numbers right and in this case four numbers is going and in this case four numbers is going to be 7 5 to be 7 5 10 and negative 6 which is what 10 and negative 6 which is what 16 say so let's say you know 16 say so let's say you know going up to here the numbers are 16 going up to here the numbers are 16 right the sum as right the sum as a 16 and then the next time the a 16 and then the next time the um and then now you put 16 in the list um and then now you put 16 in the list instead and then the next person when instead and then the next person when they go they go um they will get to put in you know 16 um they will get to put in you know 16 so their new list is this right but so their new list is this right but and they have to take at least two and they have to take at least two numbers and so forth so numbers and so forth so for example they could take these three for example they could take these three numbers and and now they have numbers and and now they have you know 16 plus 5 minus 2 which is 19 you know 16 plus 5 minus 2 which is 19 uh and negative 6 right but so the key uh and negative 6 right but so the key observation here is using prefix sum observation here is using prefix sum because because you notice that the sum of these three you notice that the sum of these three numbers is just numbers is just the sum of the first seven numbers right the sum of the first seven numbers right so that's the key observation for me on so that's the key observation for me on this one um and it took me a little bit this one um and it took me a little bit of mental thinking to prove myself that of mental thinking to prove myself that this is right you know you know if this is right you know you know if you're you're good in these kind of um good in these kind of um manipulations then this is actually manipulations then this is actually relatively straightforward but i'm not relatively straightforward but i'm not so it took a while so it took a while um but yeah so now now that you have um but yeah so now now that you have this now you know how you can use prefix this now you know how you can use prefix sum which is sum which is um you know i'm not gonna go over prefix um you know i'm not gonna go over prefix some some uh properties that detail in this one uh properties that detail in this one because there's a lot of problems on it because there's a lot of problems on it but you know this is how i did the but you know this is how i did the prefix sum i just calculated prefix sum i just calculated the what it does is that um the index the what it does is that um the index of um yeah the index i of um yeah the index i is equal to the sum of the numbers from is equal to the sum of the numbers from zero to i minus one or something like zero to i minus one or something like that maybe it's off by one but you get that maybe it's off by one but you get the idea the idea and i actually had an off buy one during and i actually had an off buy one during this contest so this contest so so that was probably why but yeah um so that was probably why but yeah um so then now we construct so then now we construct um a dynamic programming solution where um a dynamic programming solution where i do it top down i do it top down and here i name it terribly go but and here i name it terribly go but but it's just okay what is the but it's just okay what is the maximum score which is the delta maximum score which is the delta uh starting on this index uh starting on this index and that's basically how you would solve and that's basically how you would solve this problem this problem um and okay and i'm going to kick it off um and okay and i'm going to kick it off by by you know the first person atlas you know the first person atlas has to always take the first two piles has to always take the first two piles um and then on the third pile she has a um and then on the third pile she has a decision right decision right um and this is kind of um like instead um and this is kind of um like instead of writing a for if you do it naively of writing a for if you do it naively you may say okay i'll try taking two you may say okay i'll try taking two stones i tried taking three stones and stones i tried taking three stones and so forth so forth but that's going to run in n squared and but that's going to run in n squared and n in this case n in this case is 10 to the uh is 10 to the uh fifth and 10 to the 10 is really big so fifth and 10 to the 10 is really big so we try to do this in linear time we try to do this in linear time and instead you you do this thing where and instead you you do this thing where you cache the loops you cache the loops and and the idea is that okay you know um let's say you already took the first two stones right and then what happens what are your decisions your decision here is now either to take the dirt stone and then keep going and then maybe keep going or let the opponent take uh you know you end your turn here and let your opponent take starting from and and in this case what happens right and and in this case what happens right well your score is now well your score is now your current score minus your opponent your current score minus your opponent score score and your opponent score is just gonna be and your opponent score is just gonna be you know this recursive thing you know this recursive thing plus the entire prefix because this is plus the entire prefix because this is basically basically um this is basically you know taking um this is basically you know taking all the numbers including this one all the numbers including this one and the next one right um and the next one right um [Music] [Music] yeah so basically this is taking the yeah so basically this is taking the prefix which is prefix which is um because this is basically like um because this is basically like i know i said the same thing a couple i know i said the same thing a couple times sorry i'm trying to figure out a times sorry i'm trying to figure out a cool way to say this cool way to say this but this is the but this is the pile that you created by ending pile that you created by ending at index so that's basically what at index so that's basically what this represent and this is what you're this represent and this is what you're forcing forcing your opponent to take right and then now your opponent to take right and then now they have a they have a you know recursive decision to make in you know recursive decision to make in the future whether they take the future whether they take you know this is this is at least two you know this is this is at least two piles piles um so this is this is you know your um so this is this is you know your combined pile combined pile and one more pile at least and then they and one more pile at least and then they could take either two piles could take either two piles or three piles by doing this or or three piles by doing this or they n or you know more powers and so they n or you know more powers and so forth forth so that's basically the idea behind this so that's basically the idea behind this one um one um [Music] [Music] it's it's i know that i say very you it's it's i know that i say very you know that's the thing with these dynamic know that's the thing with these dynamic programming problems programming problems uh and i use lru cash to cache this uh and i use lru cash to cache this um because for every for every um because for every for every uh for every same index uh for every same index you get the same answer um and in this you get the same answer um and in this case this is just a decorator in python case this is just a decorator in python that'll let us that'll let us uh cache the input uh cache the input and the output for that answer so that and the output for that answer so that we see the same input it'll give the we see the same input it'll give the same output um same output um but yeah so this code is like you know but yeah so this code is like you know 10 lines of code 10 lines of code or this particular chunk with comments or this particular chunk with comments or whatever and spaces or whatever and spaces um so it looks easy and my explanation um so it looks easy and my explanation maybe maybe depending how you want to go about it depending how you want to go about it like it could be easy or not but it's a like it could be easy or not but it's a really hard problem i spent about half really hard problem i spent about half an hour on this i spend an hour on this i spend a lot of time debugging and getting uh a lot of time debugging and getting uh the wrong index and also the wrong index and also just uh what's my card just uh what's my card also just like messing up uh with a also just like messing up uh with a greedy solution but it's really hard greedy solution but it's really hard so take your time to really understand so take your time to really understand it and really draw it out it and really draw it out um i think the this part is okay um i think the this part is okay i think the hard part is this part and i think the hard part is this part and really draw out what it means to take really draw out what it means to take to end taking a pile and try to figure to end taking a pile and try to figure that out that out um because this is just combining um because this is just combining combining two piles combining two piles and then forcing the opponent to take um and then forcing the opponent to take um that that those piles plus plus one more pile and those piles plus plus one more pile and then they get that decision right then they get that decision right so because the actual decision is so because the actual decision is whether you keep on going piles whether you keep on going piles or you stop going to powers and then or you stop going to powers and then pass the turn um pass the turn um cool that's all i have for this problem cool that's all i have for this problem uh you could watch me stop it live in uh you could watch me stop it live in the contest and the contest and kind of see where i kind of struggle and kind of see where i kind of struggle and yeah yeah um cool see ya dumb i'm dumb today dumb today okay let's [Music] hmm this might take the entire time probably this might take the entire time probably wow people solved this very quickly so i wow people solved this very quickly so i gotta gotta do it i mean huh this one was just a do it i mean huh this one was just a silly problem though silly problem though do i also took a long time to cute way i do i also took a long time to cute way i don't know why don't know why okay that's where problem 10 to the fifth so that's where problem 10 to the fifth so you can't really iterate you can't really iterate testing it except for that this has always been prefix sum so you can do the math on but what i mean is that your sum is also but what i mean is that your sum is also going to be some of the going to be some of the thing so the delta is a little bit one of the numbers on the list they one of the numbers on the list they don't tell you that but is it i mean not necessarily one of the numbers on this but something like as a function yikes okay and then what happens let's say this force all positive numbers what happens then you just take all the numbers let's say there's a negative number at the end you stick them with it or if there's a positive number in the end let's see well it was something like 12 negative 105 then and you know what whatever then we take this thing so please say you took the biggest so please say you took the biggest number the prefix number the prefix so your turn will always start with the so your turn will always start with the big swing so greatly you always take the biggest so greatly you always take the biggest number in the prefix array so you just have to keep on going from okay so that's a youtube query so you take the biggest number into the and then there's just a heap done right so we want the biggest number so we want the biggest number let's just use this again what happens if we have thai burger do we want and that depends on the parody of it and that depends on the parody of it doesn't it positive if they're all zeros what do you do can't be convinced that that's the right can't be convinced that that's the right answer now you take all of it because the invariant is that if otherwise the next person would just take the or the the same value and your delta is zero where if it's because of the monotonic uh yeah you could do this with monotonic arrays but i don't i don't want to so okay so then in that case we want to sort it by the max index okay that's fine [Music] maybe that doesn't matter maybe i'll fix hmm hmm until you take the largest value no just keep it cheap with don't keep it no just keep it cheap with don't keep it simple if i is less do you need to take at least two two is what i don't even know what i'm thinking what i don't even know what i'm thinking about anymore just ahead and i'm blanking it sort of just ahead and i'm blanking it sort of continuous continuous okay fine that's fine oh yeah okay that's that's fine oh yeah okay that's that's good too okay that's good too okay continue otherwise is equal to i and then oh delta something like that yeah it's gonna be messy but and for the first one you that's to two and that's why that puts a little bit so the last person has to take so the last person has to take no i mean that's it then right let's see so zero and one so club currently start at zero so you want to go at least one so one is fine maybe i don't know that's right i mean it's so for number two how did i get 15 [Music] so this one takes 221 so this one takes 221 which because they're not greedy oh i see no that's not um 16 i don't get it though isn't that optimal i don't get it though isn't that optimal if um alice and i take is this one right because that's 21 and then so that's two oh no maybe not now this is right because then bob would actually take because then bob would actually take all of it and get 13 points all of it and get 13 points so then the delta is actually 6. okay so then the delta is actually 6. okay so my greedy isn't right agree isn't right which is good that we agree isn't right which is good that we resolve it here but then how do you do resolve it here but then how do you do it it how do you do how do you do how do you do that is an n square hmm is it just tp maybe it's just tp and i made it too hard but then it's also like a really messy that so basically so it's my turn i if it's my turn i might have to change this bottoms up but okay if it's my turn then bottoms up but okay if it's my turn then i either keep taking one more number score is oh there you go test number because that's just me taking this stone oh we go from to now we end our turn here so our score is set and then the prefix of so this is the score for the opponent it's a little bit off i think but let's it's a little bit off i think but let's see see you have to take at least one number [Music] that's the score that's the scored that's the score that's the scored opponent opponent what's my score to get the delta what's my score to get the delta i'm not doing the delta right i'm just i'm not doing the delta right i'm just getting the score so this is the delta maybe i'm just being silly so it can't so we take and we add to the minus i just have the science one minus i just have the science one nope [Music] this entire prefix okay i think we're good here except for this why is it where do you so we have to take at least one number so we have to take at least one number so that okay if so this is at least two okay if so this is at least two so this should should be good maybe but so this should should be good maybe but not worry about performance okay go so just try something like it's slow but not that it seems okay with respect to the time let's just give it a try okay oh this is hard hey hey uh yeah thanks for watching hit the like button hit the subscribe button join me in discord let me know how you did on this contest i did okay but uh yeah and also on this problem what do you feel about resolution um yeah uh you know stay good stay healthy to good mental health and i will see you later | 2024-03-25 11:33:56 | 1,872 | 1872. Stone Game VIII (Leetcode Hard) |
|
kr-9aAw8Cxk | welcome to algo simplified let's solve today's lead code challenge that is today's lead code challenge that is non-decreasing subsequences non-decreasing subsequences let's start with the problem statement let's start with the problem statement in this problem we are given an array of in this problem we are given an array of nums nums return all different possible known return all different possible known decreasing subsequences of the given decreasing subsequences of the given array with at least two elements so in array with at least two elements so in this problem we are given an integer this problem we are given an integer array nums and we have to return all the array nums and we have to return all the possible possible non decreasing subsequences that have at non decreasing subsequences that have at least two elements basically this is least two elements basically this is asking us to return all the possible asking us to return all the possible subsequences subsequences with with at least two elements and all the at least two elements and all the subsequences are in non-decreasing order subsequences are in non-decreasing order it means we just need to find the it means we just need to find the subsequences it's a backtracking problem subsequences it's a backtracking problem you can say it's kind of a DFS like we you can say it's kind of a DFS like we choose this four then we can choose any choose this four then we can choose any of the number which is either equal or of the number which is either equal or greater than this number greater than this number and then if we choose that number then and then if we choose that number then we can choose like if we let me just we can choose like if we let me just explain you this problem explain you this problem we have we have an array like this and now we are supposed to choose like make a subsequence so if we choose this element at index I okay like index 0. then we can choose any other number from this index I equal to 1 to I equal to n minus 1. we are free to choose and then from up from 1 to n minus 1 after we choose a number then again we are free to choose a number and while we are choosing the moment we reach and choose a number or we can say that like if it's 1 5 2 1 1 8 1 3 1 let's see now we are choosing this one okay and we just okay after choosing from out of all these numbers we see we will choose next will be 2 like from I equal to 1 to n minus 1 we choose two so before choosing to we can put consider this as a subsequence like yeah this is also a subsequence of this array now after coming at 2 what we can do we will just choose these two and we can say okay this is also a subsequence now at 2 now we have to move ahead as we have made the subsequences with these numbers till here now we will move ahead and we will choose another number let's say it's three so we'll choose three and now one two three will be a subsequence after three we don't have any element so we will just return so in this way like we will be using we will be iterating through the like index icon index I to n minus 1 and we will choose a number after that choosing that number we will put this in a sub in in our array result array and we will move ahead like if we we have chosen a number at index I then we will again choose from index I plus 1 to n minus 1. so to get all the possible subsequences we have to choose every number that's simple like just to get a single subsequence like I just wanted to get one two three or any random subsequence then I could have chosen but in this way but we have to deal with all the subsequences so we will basically basically generate all the subsequences between these numbers and since we are generating all the possible subsequences the time complexity of the solution will 2 raised to the power n where n is the 2 raised to the power n where n is the size of the array size of the array why because in subsequence either we why because in subsequence either we will be choosing one or we will not be will be choosing one or we will not be choosing one for every subsequence if we choosing one for every subsequence if we choose one okay otherwise we don't choose one okay otherwise we don't choose this one and move ahead for all choose this one and move ahead for all these numbers so we are not choosing these numbers so we are not choosing this one then moving ahead if maybe we this one then moving ahead if maybe we choose 5 or we don't choose 5 oh we choose 5 or we don't choose 5 oh we choose any other number so there are two choose any other number so there are two possibility of choosing five that is possibility of choosing five that is either choose 5 or either neglect five either choose 5 or either neglect five so in this way the number of so in this way the number of subsequence is made will be 2 raised to subsequence is made will be 2 raised to the power n the power n and similarly the space complexity we and similarly the space complexity we will be storing all the subsequences in will be storing all the subsequences in a array of array so we will be requiring a array of array so we will be requiring a space of Big O 2 raised to the power n okay and let's let's code it up like this is a simple backtracking problem so first I will generate all the it will store a particular subsequence it will store a particular subsequence and this will store the result go through it like this go through it like this call a function and deal everything in call a function and deal everything in the function the function and return the result and return the result now everything is now everything is on this function now as we want to generate all the subsequences what we will do we will iterate from this index till the last index end we will put subsequent we will put this number subsequent we will put this number into the subsequence into the subsequence and then again like either we will and then again like either we will choose this number or not choose not to choose this number or not choose not to choose this number so like when we come choose this number so like when we come at index I equal to IND so we will at index I equal to IND so we will choose this this particular number and choose this this particular number and otherwise otherwise if we don't choose it means like we have if we don't choose it means like we have moved to index I equal to I and D plus 1 moved to index I equal to I and D plus 1 like as we are iterating this for Loop like as we are iterating this for Loop so basically we are choosing that number so basically we are choosing that number instead of this number for the very instead of this number for the very first element of the subsequence for first element of the subsequence for that particular subsequence and now we that particular subsequence and now we are again calling that function are again calling that function now we are calling this function for now we are calling this function for like since we have chosen this I index like since we have chosen this I index so we can call this function for the so we can call this function for the next element that is I plus 1 so that we next element that is I plus 1 so that we can choose from the I plus 1 element to can choose from the I plus 1 element to the last element of the array and now since we will be iterating through this for Loop so if I we are at particular index I then if we move ahead to index I plus 1 then we can't keep this nums I in that subsequence so we have to pop that one like we have to pop it out from the array like this and since whenever we call this function we will move ahead so like we have taken 4 and we move ahead to consider all the remaining numbers so we can say that this 4 is also a subsequence so when whenever we call and whenever we check for the next possible numbers to be considered for the subsequence we will put this thing into our and if we reach at the end element so and if we reach at the end element so this for Loop will won't be working this for Loop will won't be working since I should be less than the size of since I should be less than the size of the array so we don't need to add any the array so we don't need to add any condition so this code is basically to condition so this code is basically to generate all the possible subsequences generate all the possible subsequences and if I just run the test cases you and if I just run the test cases you will find that will find that we have generated all the possible we have generated all the possible subsequences like you can see here even subsequences like you can see here even empty set single element all the empty set single element all the elements are here so this is the code to elements are here so this is the code to generate all the possible subsequences generate all the possible subsequences but now we have just two condition the but now we have just two condition the first one is that first one is that it should be non-decreasing and the it should be non-decreasing and the second one is that at least two elements second one is that at least two elements should be there so for at least two should be there so for at least two element we can just element we can just put a condition over here like if the put a condition over here like if the sub dot size is greater than one if the sub dot size is greater than one if the size is greater than one only then we size is greater than one only then we will put this in our result and for the will put this in our result and for the second condition uh it's saying that at second condition uh it's saying that at least and it should be non-decreasing least and it should be non-decreasing means the previous element should not be means the previous element should not be greater than means greater than means non decreasing it should be non decreasing it should be non-decreasing so if we find a condition where this sub Dot like this thing is not and and the last element is greater than the particle of this element then we will continue we won't go in and add this number to our subsequence because it's smaller than the previous number which is basically not going according to the condition if we just don't add this condition then it would be decreasing array it's decreasing subsequence so now basically we have deal with everything we have deal with the condition known decreasing subsequence and the size should be greater than 2 but now the you can also see that in this what will happen is we are generating all the possible subsequences so in this example like Force four four six in this example like Force four four six seven seven four six seven seven seven seven four six seven seven now you can see that now you can see that we we they are considering like all the they are considering like all the subsequences is unique like subsequences is unique like they are not considering four seven and they are not considering four seven and four seven as different subsequences four seven as different subsequences like this this particular seven that is like this this particular seven that is let this 7 be 0 and the 7v1 so if this let this 7 be 0 and the 7v1 so if this is z this one is z this one this is different seven this is this is different seven this is different seven then these two will be different seven then these two will be considered as the same subsequence but considered as the same subsequence but in our in our code what we are doing we are code what we are doing we are considering four and then we consider 7. considering four and then we consider 7. out of all these we consider all the out of all these we consider all the numbers so we are considering six then numbers so we are considering six then four six okay then we are considering four six okay then we are considering four seven and then we are again four seven and then we are again considering four seven that's why we can considering four seven that's why we can if there are like the number of sevens if there are like the number of sevens are four then we are the count of four are four then we are the count of four seven will be four so we are having seven will be four so we are having duplicate subsequences in our result in order to avoid that since we are at this particular element at this particular index now we are going to call the function for all for the rest of the elements like we are at this particular element and now we are iterating through the rest of the elements which are ahead of this element now while iterating if we just encounter 7. and we just if we just encounter 7f and if it's just greater than 4 or equal to 4 then we will add it in a set so that if we again encounter 7 while I trading 4 in that for Loop then we won't call this the DFS function and won't insert the subsequence into our result so this is the one thing we are going to going to do we will add one more condition here if we find in the in the set then we will continue we want and we let's create a set I haven't defined it let's create a set I haven't defined it yet so now in this way what we are doing like we have four and six or I mean we have a 4 then for this particular 4 we are going to iterate from I equal to 1 2 till the last 3 so 1 2 till 3 so 1 2 3 will be called 3 so 1 2 till 3 so 1 2 3 will be called so if we get go to one then we will put so if we get go to one then we will put this 6 into our set and then we will this 6 into our set and then we will call this function call this function and we will and we will put we we have just put the six into our put we we have just put the six into our set now we come at seven we will see set now we come at seven we will see okay 7 is not present we will okay 7 is not present we will insert the 7 into the subsequence and insert the 7 into the subsequence and then call it for then call it for further adding the subsequences and then further adding the subsequences and then we will add that 7 into our set then we we will add that 7 into our set then we again come at 7 so we have a subsequence again come at 7 so we have a subsequence 4 comma 7 as we have 4 comma 7 as a 4 comma 7 as we have 4 comma 7 as a subsequence till now but when we again subsequence till now but when we again come at 7 we see oh it's already present come at 7 we see oh it's already present in the set so we won't just go into the in the set so we won't just go into the these core the these line of codes these core the these line of codes and we will just continue and move ahead and we will just continue and move ahead so in this way we will save from save us so in this way we will save from save us from getting duplicate subsequences from getting duplicate subsequences let us run the code so basically it's accepted yeah so this so basically it's accepted yeah so this was the code thanks for watching I'll go was the code thanks for watching I'll go simplified do like share comment simplified do like share comment and I hope you enjoyed the video and I hope you enjoyed the video thank you | 2024-03-22 15:40:49 | 491 | 491. Non-decreasing Subsequences || LEETCODE DAILY CHALLENGE || ALGOSimplified |
|
oU-roqyp_Hs | [Music] hello everyone welcome to another hello everyone welcome to another episode of coding decoded my name is episode of coding decoded my name is ancha rodeja i'm working as technical ancha rodeja i'm working as technical architect sd4 at adobe and here i architect sd4 at adobe and here i present russian doll envelopes problem present russian doll envelopes problem and apologies i couldn't solve it in the and apologies i couldn't solve it in the morning and provide you with the morning and provide you with the solution as i was quite occupied with my solution as i was quite occupied with my professional commitments i just got some professional commitments i just got some buffer time and now let's shoot for buffer time and now let's shoot for solving this question solving this question or to your surprise we have already or to your surprise we have already solved this question in the month of solved this question in the month of march 2021 this problem is based on the march 2021 this problem is based on the concept of longest increasing concept of longest increasing subsequence subsequence longest increasing subsequence problems longest increasing subsequence problems can be solved using two approaches one can be solved using two approaches one in time complexity of order of n square in time complexity of order of n square one in time complexity of order n log n one in time complexity of order n log n using patient sort using patient sort for all those who are not aware of these for all those who are not aware of these two techniques don't worry we already two techniques don't worry we already have another tutorial wherein i have have another tutorial wherein i have explained both these approaches in explained both these approaches in detail detail and in the past solution of russian and in the past solution of russian dolls i talked about order of n square dolls i talked about order of n square approach which is no more accepted on approach which is no more accepted on lead code so if you go and check this lead code so if you go and check this code up code up you will see that you will see that out of 87 test cases only 85 pass so let me just comment that up and show it to you guys and then we will go on improving it using the patient sort approach and it will fail and it will fail with the error of time limit exceeded if with the error of time limit exceeded if you go and check the details then 85 test case passed out of 87 and if you go and check this video uh it here the solution passed an year back they added two more test cases in order to make sure that all the solutions are of time complexity order of n log n now comes the question how can you actually solve this up first and the foremost thing is to check out the longest increasing subsequence video where i have explained and taught patient sort once you get good hold of the concept of patient sort then move back to the rusty and all envelopes problem because most of the test cases are still getting solved by this approach and it's very important how long is increasing subsequence algorithm is getting applied over here once these two things are done now come back to this solution where we will try to improvise it in time complexity of order of n log n so a few things remain the same the first and the foremost thing is that we are sorting the envelopes on the basis of width then followed by height so width in increasing order height in decreasing order height in decreasing order so remember this point this is very so remember this point this is very important important uh why we are doing this i'll talk about uh why we are doing this i'll talk about it later in the it later in the solution so here i've created a db array solution so here i've created a db array and this dpra will actually store the and this dpra will actually store the maximum height seen so far we have maximum height seen so far we have initialized this dpra with maximum value initialized this dpra with maximum value of integer and by default dp of zero is of integer and by default dp of zero is initialized to zero so let's consider initialized to zero so let's consider the case where the first envelope comes the case where the first envelope comes is of height seven so what we will do is of height seven so what we will do we'll apply binary search over a dp we'll apply binary search over a dp array where in all the elements so far array where in all the elements so far are maximum and we are basically keeping are maximum and we are basically keeping track of the track of the maximum height of envelopes that we have maximum height of envelopes that we have seen so far seen so far so the first one comes our seven what do so the first one comes our seven what do we do we apply binary search we do we apply binary search algorithm and look out for the algorithm and look out for the appropriate position for seven what is appropriate position for seven what is the appropriate position for seven it the appropriate position for seven it comes out as zero so we go ahead and add comes out as zero so we go ahead and add seven at the zeroth index so it gets seven at the zeroth index so it gets added so how many envelopes have we added so how many envelopes have we added so far we have added only one added so far we have added only one envelope so the answer becomes one now envelope so the answer becomes one now consider two cases in the first one consider two cases in the first one three comes and in the second one eight three comes and in the second one eight comes so let's assume comes so let's assume that we treat the second envelope as that we treat the second envelope as three and what do we do we three and what do we do we check what is the appropriate position check what is the appropriate position for this for this three so we we get three so we we get again zero so in this case it will be again zero so in this case it will be replaced the zeroth index will be replaced the zeroth index will be replaced by three replaced by three we will simply go ahead and replace this we will simply go ahead and replace this seven by three and the answer still seven by three and the answer still remains one so this is exactly same what remains one so this is exactly same what i taught in the patient sort algorithm i taught in the patient sort algorithm if you have not gone through it you will if you have not gone through it you will not be able to get it otherwise in case not be able to get it otherwise in case in the second case if we get an eight so in the second case if we get an eight so we'll look out for the upper update we'll look out for the upper update position for eight it will come as the position for eight it will come as the first index and the first index and the envelope width dpra will get updated to envelope width dpra will get updated to seven comma eight and the rest of them seven comma eight and the rest of them will set remain as maximum will set remain as maximum so far how many envelopes have we added so far how many envelopes have we added we have added two envelopes and the we have added two envelopes and the answer becomes two answer becomes two let's treat another case let's treat another case where from seven comma eight we get the where from seven comma eight we get the next height of the envelope that we get next height of the envelope that we get is of one unit so what do we do we check is of one unit so what do we do we check it's after great position the it's after great position the appropriate composition comes at the appropriate composition comes at the zeroth index so in case one comes up uh zeroth index so in case one comes up uh the envelopes will be updated in the dp the envelopes will be updated in the dp array as one comma eight this is exactly array as one comma eight this is exactly same as i taught in the patient sort so same as i taught in the patient sort so guys i i urge you guys to go through it guys i i urge you guys to go through it first first and uh the dpr is updated to this and uh the dpr is updated to this however the total number of envelopes however the total number of envelopes added still remains the same that is added still remains the same that is true so the answer still remains two true so the answer still remains two in the other case let's assume 10 came in the other case let's assume 10 came instead of one so what is the instead of one so what is the appropriate position for 10 it is the appropriate position for 10 it is the second index therefore the dpra gets second index therefore the dpra gets updated to 7 comma 8 comma 10 and the updated to 7 comma 8 comma 10 and the rest of the fields remains the same the rest of the fields remains the same the answer gets updated to 3 because here we answer gets updated to 3 because here we have added three envelopes so far have added three envelopes so far and this is what and this is what has been done over here using the binary has been done over here using the binary search technique search technique so here we iterate over the envelopes so here we iterate over the envelopes array and remember the envelopes are array and remember the envelopes are already sorted in increasing width so we already sorted in increasing width so we are not concerned about the weights of are not concerned about the weights of the envelopes but the area of concern is the envelopes but the area of concern is only height and in order to provide only height and in order to provide unnecessary manipulation we have sorted unnecessary manipulation we have sorted them in decreasing order of height them in decreasing order of height whenever there is a conflict so that the whenever there is a conflict so that the one with the higher height and same one with the higher height and same width gets precedence width gets precedence uh so what do we do we search for the uh so what do we do we search for the appropriate position for the current appropriate position for the current envelopes height in the dpra we when we envelopes height in the dpra we when we get its index we update dp of that get its index we update dp of that particular index to the height of that particular index to the height of that envelope and we keep track of the length envelope and we keep track of the length variable as we are progressing in the variable as we are progressing in the dpra so this is pretty much it and this dpra so this is pretty much it and this corner case that they have written is corner case that they have written is because when the binaries in while because when the binaries in while searching in the binary search that searching in the binary search that element is not present so if you go and element is not present so if you go and check the check the documentation for binary search you will documentation for binary search you will see that whenever the element is not see that whenever the element is not present it returns the insertion point present it returns the insertion point -1 -1 so this method returns the index of the so this method returns the index of the search key if it is contained in the search key if it is contained in the array else it returns insertion point -1 array else it returns insertion point -1 so in order to counter this up so in order to counter this up we have added negative signs over here we have added negative signs over here so that's pretty much it in the end we so that's pretty much it in the end we simply return the length that we have simply return the length that we have computed so far computed so far the time complexity as i initially told the time complexity as i initially told is order of n log n same as that of the is order of n log n same as that of the patient sort patient sort with this let's wrap up today's session with this let's wrap up today's session and i hope you got some idea on how to and i hope you got some idea on how to apply patients or patient sort on to a apply patients or patient sort on to a russian doll envelope problem russian doll envelope problem thank you thank you [Music] | 2024-03-24 11:21:02 | 354 | Russian Doll Envelopes | Leetcode 354 | Patience Sort🔥🔥🔥 | O(nlogn) | Live coding session |
|
w7u9sMlx7zc | o learn and this approach is very similar we have operations reduce These are comma three, right is one in the left most, there is you in the right most, so in this we have picked up you. Okay, how many if we take this minimum, this is the minimum. You will not be able to get a smaller answer than this. Look, pay attention here, if you had comes but here A came in only two times. Okay, so you have to do the electrical thing. Is it left most or right mass approach? That brother, will I take this Salman this time or will I not take it like mother takes here, here and then you thought that no, this too. You can take it, okay, so this is what I thought, first of all, it is okay, but find it in the description, I have written the recognition code, that arrow will definitely give it. I but first let me tell you this. Okay, so you take it like mother, till now you have the option, you either and how many elements of yours have you taken you have taken the value of count one okay and 1st element, this time the of If I took two on Ratna, then two, I two became zero, so as soon as it became zero, starting infinity was kept in it. Now I have updated the value of the account, it is okay, maybe from here, I keep updating the minimum when I get it, okay? This would have been a very simple code of Rickson, okay Rickson, we have learned so much and what do you have to do in a simple way. Look mine in What can happen is that you have taken the Jeth element, Jai is taken then you will remove the name of all from it is okay then it is okay to call Krishna twice and what is put in the above base, in the calculation, brother, Minimum of Minimum which is the already value and the The gate is in the link, it is given in the description, the link is given in the description, sorry, the link is given in the friend, I am giving it, so what is better now. The approach is searching for one, we try to see it. Okay, Will come and before that, some things should be compromised so that your engine can be built. Okay, like, let's take our mother, this okay, this might have picked up some of our elements from the left and You must have picked up some of your elements from the right, meaning you have to pick at least elements from the left and right and you have to bring all of them equal to X. least you have to pick up elements from the left and right and you have to bring it equal so now because of mother, whatever elements you picked up on the left, whatever elements Plus Right Bill B will be equal, will be whether it is left or right or left right. Now the elements that you will pick should be minimum number of filaments so that get I am looking for the longest are right, the relation is equal to this, then the children who are hiss in the left boundary and Rawat are in the right boundary, Left is right. Let's take the sum of the elements in the boundary. Right is okay I have taken the value of all the accesses and taken the sum of all these. So it will not be equal to even, meaning the sum of this whole D is the minimum element, this is what I am saying, don't make it as big as you can, but everything. but the bigger it is, the less space will be left on the right side, less space will be left on the left side, less elements will be The value _ , now I didn't have to pay attention to these two, DK, I sometimes you will choose the left, sometimes you will choose the right, okay So it is obvious that if you have the option, then you will pay attention to reading two things. I am paying attention to one thing, brother, whatever is in between. picking on the left side and the right side is should be equal to the longest. This means that we take its length, how much I took out, I took out L, whose the elements on the left and the elements on the right. Okay, so N minus L will be my answer. Then okay, you total number of elements is L, okay if the length is L, then how many children are there N - L and can pick, the minimum whose value should be equal on easy map and by doing it, they will also understand it, they will also understand it by instinct, I will not it was necessary how I reached here, now let us solve it. Then let's find out the sum, x. Okay, so what will be the value of sum minus target and store it how much will be submins submins so this is the special thing about this question, see another separate question embedded in it, this one you will learn this question and this question has also been asked separately many times. It is okay that it is the longest. Look, because You have to take out the patience, don't you take out the sabre, whose sum is equal to man sex, then you you take out everything all the morning, even we There are three till now, there are five swear words, sum of any sabri, then now you can tell me, if I tell you, brother, you want the sum of this sabri, where is the time from till here, it's all nine, but we only need this much, we need this much oath, right, if we want this much, okay then till 9 - 0, how much kasam is reduced to three. Look at its sum which is equal to six. Here is that we take out the prefix, you can take out any oath very easily, even in constant time, it will you steal, you can store it in the map, so what did I do? You have created a map, okay, and it will be even till the date index, okay, so how much has come till index number zero, how much has come We have stored in our map how much is the prefix till which index. Now tell me the sum from index number one to five. Okay, sum from one to five. If you want then see what you will do, you will see pehle tak kasam, how much is that, look at induction number tu se just pehle tak kasam, how much is now how do we get the longest sum by giving this information, see that mother let you go this much Do you know the index number till date? Do you know the index number? minus Tell me one thing, on the story, now I am standing at 10, okay, you have to find this target, 7 is right, so mine both of them, mines after , that means the time till the index number zero was three, which means that it must the index number till zero I swear it is 3, how did we find it from the map, we went right till here, will I know will have to store the index number here . sum and index here will have to be done, so I will update it. Look once, also found here, it is fine in the index, so remember now , okay, okay, so how much is the length, let's see, look, So I have come to the mother 's advice that this is the to Let's reduce one, now let's move ahead, let's take I, go ahead, okay, will be 13, here I will keep coming out all together as I keep increasing the sum. Yours is mine. Okay Do 6 A. So it means that if the last time on the story, I must have seen six. Let's see okay, understand its meaning till this point, and the sum till this point is 13, which means for sure till 20, 13 will be where the saint is yours and mine is not where the even is 13 index number is seven ok if you did 13 - 7 then 6 came then where was the number on this index is you But where did I get it from the map here? If I did 7 - 2 then I got 5, that is, the so I have to get the biggest one. I will not update, okay, so this is what I am able to get it bigger than this, now you will dry iron further also, otherwise you will not get bigger than this, this is clear, who is that? Look, two-three, four-five-six-seven, this Okay , the time was - , then we will be ready to code, here is a small question about how and even if you are not able to catch it, then there how is the smallest? Look, here the Its balance is all I have sex all I have here how much is 6 so we have to find the longest take the sum is one okay Then here is the even, you came here, then you came here, took the mother, reached here, is six, okay, what did you do for 6 months, so what would you do? Where have I seen this zero is the last, this is what I was seven, then you used to find 6, whatever six i value Where did you see six last time, so looking at the minuses and zero, last time I made zero, so it is in my sum. Not only, Okay, so now here it is not there in my map, its value is zero, I till here . I swear there was 6 till here, I swear there was 6 till now, have got two -1, how much will there be three, of N because we only did the driver once. The gesture is fine and And let's finish it, so let's code it with the exact approach that was told which sum came at which index, the right, what is its less, that too. You had come to know the string in the map okay and to solve this one corner what I told you told you all this, now let us see what will be the remaining time remaining sum, so what will I see, Then after this we used to see whether we have seen this remaining sum nearby and MP on the story and find this remaining sum. out its index. In Idea Okay, now let's update the length of the longest surgery. Will do the last time run and see So look here, I came to know about this only after I made a mistake, this is a check, we can enter so now here already. You than | 2024-03-19 18:41:45 | 1,658 | Minimum Operations to Reduce X to Zero | 2 Approaches | Recursion | Hashmap | Leetcode - 1658 |
|
XcY9aUlLP_s | hello guys welcome to deep codes and in today's video we will discuss lead code today's video we will discuss lead code question 226 that says invert binary question 226 that says invert binary tree so here you are given one binary tree so here you are given one binary tray uh you are given the root of the tray uh you are given the root of the binary tree and you need to invert the binary tree and you need to invert the tree and return its root okay so here tree and return its root okay so here what does the invert word mean invert what does the invert word mean invert the binary what does that mean so let us the binary what does that mean so let us understand that with this first example understand that with this first example so here you are given this binary tree so here you are given this binary tree and you need to invert it so yeah as you and you need to invert it so yeah as you see that this ah root note 4 has left see that this ah root note 4 has left Child 2 and right L7 so in inverted Child 2 and right L7 so in inverted binary you just Swap this child that binary you just Swap this child that means that the right child become the means that the right child become the left left becomes right simple as it is left left becomes right simple as it is see if the 7 becomes the left chair and see if the 7 becomes the left chair and Two Become the right chain Two Become the right chain now again for the node 7 it's left elbow now again for the node 7 it's left elbow six NHL was nine but we swipe it we swap six NHL was nine but we swipe it we swap so so that the left shell of 7 becomes 9 so so that the left shell of 7 becomes 9 and right shall become six similarly the and right shall become six similarly the left child become 3 and right should left child become 3 and right should become 1 after inverting or you can become 1 after inverting or you can swapping we're simply swapping the left swapping we're simply swapping the left child as well as the right side for each child as well as the right side for each node as you can see here from this node as you can see here from this example got it now here 2 is our root example got it now here 2 is our root node and one and one is the left shell 3 node and one and one is the left shell 3 is the right chain so what does invert is the right chain so what does invert mean invert mean to swap the left and mean invert mean to swap the left and right chair thus unswapping the left right chair thus unswapping the left side became three and the right side side became three and the right side becomes one becomes one the third example we have nothing in the the third example we have nothing in the root so we written null or empty correct root so we written null or empty correct now let's take a look at this example so now let's take a look at this example so suppose you have this type of example suppose you have this type of example and you need to invert it so tell me the and you need to invert it so tell me the the root be the root remain as it is the root be the root remain as it is correct now what we do not in in order correct now what we do not in in order to invert this tree what we are doing we to invert this tree what we are doing we are simply doing ah swapping off the are simply doing ah swapping off the left chair with the writer correct so left chair with the writer correct so here comes two and here comes one okay here comes two and here comes one okay we just swap them now internally for two we just swap them now internally for two also we are swiping the left and right also we are swiping the left and right here so the two is left here big will here so the two is left here big will become six and each side will become Phi become six and each side will become Phi and once left child will become 4 and and once left child will become 4 and here it will be three okay here it will be three okay now for three also we need to swap now for three also we need to swap so here it would become h so here it would become h and here it would be 7 and here it would be 7 first four uh its left side was nine but first four uh its left side was nine but it's now its right side will become nine it's now its right side will become nine okay everything here would be null this okay everything here would be null this would be also null null null null would be also null null null null so yeah this is how we invert the binary so yeah this is how we invert the binary tree okay this is how the inverted tree okay this is how the inverted binary tree looks like binary tree looks like so now uh I hope you guys understood the so now uh I hope you guys understood the question it is simple as it is but now question it is simple as it is but now in order to invert this how much you can in order to invert this how much you can do see as you can see here that we are do see as you can see here that we are just traversing all the nodes and doing just traversing all the nodes and doing some operation okay for each root node some operation okay for each root node or each parent node we are outperforming or each parent node we are outperforming some operation on the child node here we some operation on the child node here we are swiping that are swiping that so ah in order to Traverse all the nodes so ah in order to Traverse all the nodes what do we need to do we need to do what do we need to do we need to do something like BFS or DFS Towers okay something like BFS or DFS Towers okay simple like we need to do some type of simple like we need to do some type of flowers in order to invert this string flowers in order to invert this string okay and what another thing we are doing okay and what another thing we are doing is for each root node like that for each is for each root node like that for each root what we do swap left and right child this is the only thing that we are doing to invert the binary we are swapping the left child with the right child and the right childhood we're just swapping them left and right side okay yeah this is all this is our approach we will either do PFS or DFS traversal and we will swap each each side correct now let's move on to the coding part where we will look that how we are actually performing this so first let me show show you the DFS approach so yes this is the DFS approach see guys as you can see here that here uh these two lines uh these three lines actually here what we are doing we are performing so we have swap of left child with the right shell and right shell with the left chain correct and then we are again doing DFS on the left shell and then DFS on the right track similarly it means uh similarly to perform the swaps honest children Okay so ah so yeah let me show you by drawing these that uh if you have a show three four if you have something like this okay so initially it will check if the root is empty no it is not empty for the root zero so for the root zero what we are doing we are swapping is LifeWay right so it will be two and one here okay this would be your answer now what we are doing we are traveling for its left so our left is two okay so now we are traveling again now what is the root root is to for this and then again uh we are checking if the rule is not no root is not null then we are swapping left and right so yeah but both is now left and right so it doesn't make sense okay now your travels again so this is second time traversal uh for with what here the root is now like this is not and this is also known so either you do both of this it is none so so in that case we return we return and Traverse its right right child okay right child of node zero so this right side of the node zero has two children three and four so we will swap them okay four and three when whenever we travel so the solve function whenever the solve function uh will call for one at that time we will Traverse the node 3 and node 4 as per this correct so yeah this is how DFS traversal works that each time we are traveling traversing for some non not null root then we are just swapping its nodes correct left and child nodes left hand side child nodes and in the end we are simply returning no root node so I hope you guys understood the the DFS approach now let me let us also discuss the BFS approach BFS approaches also similarly similar as to DFS so here in as we know in the BFS we use one Cube and initially we push the root right and the and then for every root with ah that is present in the front of the queue we just store it in the current and yeah we swap the left child in the right shell of the current as you can see here and we check that if the current Uh current left is not empty then we push to the queue and if the current right is not empty then we push to the queue correct so yeah and in the nvd term so we are not talking about the time and space complexity so the time complexity here would be big open right as we are traversing all the nodes present in the tree so the time complexity here it would be big of N and for the space complexity uh it would be also almost too big of a in the worst cases uh and this is for both the approach DFS as well as BFS regardless of approach it would be the same yeah the time competition is bigger fan is very traversing all the nodes in the space complexities bigger friend see it is somewhere bigger of H H is the height of the tree but in the worst situation when all the nodes are present in the queue or in the recursive stack of DFS then in that case our space complexity would be because so yeah in the worst case it is big of an ins is the time complexity is also bigger so I hope you guys understood the question the approach part as well as the coding for both the approaches and if you have still doubles then do let me know in the comment section also do check the community section of this channel uh where you will found the job posting so I am regularly uh updating the section as well so yeah that's all from this for this video from my site today make sure you like this video And subscribe to our | 2024-03-22 11:02:42 | 226 | 226. Invert Binary Tree | LeetCode Daily Challenge | Beginner Friendly Solution | BFS | DFS |
|
0do2734xhnU | Jhal Hello Hi Guys, this question in this video we will Hello Hi Guys, this question in this video we will discuss our largest this is this discuss our largest this is this grinder solution so see I told you that grinder solution so see I told you that you have got a bar chart of Lal Singh, you have got a bar chart of Lal Singh, this is the chart inside which you have these six heights this is the chart inside which you have these six heights that you have once. that you have once. that you have once. promotion of light on the fifth of a child 's telling you that the biggest rectangle inside it which has the most area, then I had wiped only one of you, it should have cried that you look at six sites If every one If every one If every one is a one-time scholar, then just consider one side as is a one-time scholar, then just consider one side as your base, then this time will not be your base, then this time will not be available in the office, if it is of boot lights, then it will be considered as flirting, otherwise by making available in the office, if it is of boot lights, then it will be considered as flirting, otherwise by making six as the base, I will six as the base, I will make you the title of Sector-21 by making you in me, I will make make you the title of Sector-21 by making you in me, I will make wide speculation. wide speculation. wide speculation. find, how much is the 15 minute tarpan 510 by making 25 comments 521 There is not enough time to prevent the war from spreading, the sight will bear fruit, the hydraulic triangle of four will go here till here, either the point of the first, two, three, well, If you take this triangle rectangle from war to If you take this triangle rectangle from war to If you take this triangle rectangle from war to Nandvansh, then it will take 5215 vitamins. If you Nandvansh, then it will take 5215 vitamins. If you look carefully, then from here to here, the olive look carefully, then from here to here, the olive oil will spread till here. If you take Hazare's made oil will spread till here. If you take Hazare's made elements along with it, then it will give 127 or elements along with it, then it will give 127 or six and the tiger will not fall, okay then? six and the tiger will not fall, okay then? What we are saying is that What we are saying is that you should consider each and every bar as height you should consider each and every bar as height and spread it on both sides and see and spread it on both sides and see it can spread as far as it can spread, then it it can spread as far as it can spread, then it will increase till that height and will increase till that height and width. width. width. asking is, if we did this on the element, then think once and see what the first limit was, I will show you in full, if on the element, we decided how far it can spread, then Will you decide for doing it, Will you decide for doing it, Will you decide for doing it, how far can it spread, here can spread till here, how far can it spread, here can spread till here, after this it cannot be after this it cannot be changed by the hands of this place, then at least one person will changed by the hands of this place, then at least one person will start to find out how far can it spread, start to find out how far can it spread, then it will be limited, then every one of us then it will be limited, then every one of us then it will be limited, then every one of us try to spread the base value, then it is okay, then our century will become more possible. If you want to do that then it is very important to think carefully about the birthday, you will understand that when it spreads, the goalless draw takes care of it Next model Next model Next model is mutton kofta Next9 element As long as he keeps is mutton kofta Next9 element As long as he keeps getting elements bigger than that, he getting elements bigger than that, he is like the one gets in Chota, then it was is like the one gets in Chota, then it was that yes mummy, I will not be able to come in the boundary and Sahib, the that yes mummy, I will not be able to come in the boundary and Sahib, the maximum limit is under-right, his maximum limit is under-right, his height is the country Next9 limit inside height is the country Next9 limit inside height is the country Next9 limit inside becoming his left. Okay, if you are not happy seeing this thing, then let me take another example like this, I don't take values, okay, like we are like this brother. okay, like we are like this brother. okay, like we are like this brother. talk or can talk about getting married to someone, then see how far will this person on the right side play, this brother on the right side will be able to get a cell, will be able to play this game, will be able to walk till this point, No, we will No, we will No, we will not do this because beyond this, not do this because beyond this, it is a small element, so till there it is it is a small element, so till there it is going to look like a festival and the website will going to look like a festival and the website will not be able to proof that the element is headed by me, it is not be able to proof that the element is headed by me, it is small, okay, so if I small, okay, so if I change the court a little, change it to the picture times. change the court a little, change it to the picture times. Let me do this so that you will see that your style will change, then you will be able to play it here on the website, you will be able to play it from inside also, for this they will come here and stop where they stopped because now there is element, so the next model is based on the And the Italian And the Italian And the Italian right is able to spread towards his height. right is able to spread towards his height. Okay, so for this you need Okay, so for this you need his Next9 Element All Dual app for every element his Next9 Element All Dual app for every element and want college without height. and want college without height. After getting that, now you will be able to get rid of anyone who After getting that, now you will be able to get rid of anyone who was our son with him. was our son with him. was our son with him. dad I think you are six 5451 that sex is fine PM Noida sec-62 5216 element Kaliyug smaller element inside I want to remove left and next flight mode now I will explain a lot to him no I will write that wicket quickly so you will see That I am making a right boundary, now I am not talking about this big thing, so listen carefully A Right Boundaries Basically next 9 A Right Boundaries Basically next 9 elements on the right and one is always to be made elements on the right and one is always to be made like this after a while we will write like this after a while we will write play list boundary play list boundary that will take some logic and fill it that will take some logic and fill it that will take some logic and fill it filled then do you know what I am not going to keep family values, I am not going to maintain that the next 9 element of four is one, I am going to be among those keeping this, Pooja, what is the index of Next 9 Judgment and I am going to excavate the left side of If I If I If I contact Messenger, what will I see? If I contact contact Messenger, what will I see? If I contact Intex Ultra, Intex Ultra, I will see an increase. 6254 5160 I will see an increase. 6254 5160 12345 6 If you want to know with more keys, 12345 6 If you want to know with more keys, keep in mind Pooja, the index of the next9 element on the keep in mind Pooja, the index of the next9 element on the right is f5 and the index of the next9 element on the right is f5 and the index of the next9 element on the left is 15054. left is 15054. left is 15054. so right dongri m re dongri minus one his increase will be that from this I am going to do this next to you MSC maths model Mr. Right 100 index inside right an essay in this if I have both of these then if I have both of these then see the maths area see the maths area so so so road length is I plus plus, okay, then how will it come, the right boundary will come - the left boundary will come - 110, and how will it come, as per his height, he is More then A, you a message. Okay, now we have removed the war you a message. Okay, now we have removed the war rider definitive, which is a rider definitive, which is a small problem of its own. Next 9 And it's on the right. Okay, inside for small problem of its own. Next 9 And it's on the right. Okay, inside for you, you you, you drive right to left, inside left. drive right to left, inside left. drive right to left, inside left. work, this is absolutely ours, that's why we did it, Next Great Element, right from right to left clock, so I will do the same, stock monitor, festival to new Kabir, now this should not be that drink, start, happy, not It's okay, It's okay, It's okay, so I will give that also to the person with tears, so I will give that also to the person with tears, Torch Light Dongri, the last one, Torch Light Dongri, the last one, what is the maximum volume Tubelight of yours, whose next 9 judgments should be on the right side of water, take these, I am saying this so If there is any element If there is any element If there is any element like caffeine and Sainik School like caffeine and Sainik School Admit or Grade is very small or zero, its Admit or Grade is very small or zero, its maximum limit is not there then there maximum limit is not there then there is no malware on its right side, that point is the is no malware on its right side, that point is the next 9 judgment eye which you get on the next 9 judgment eye which you get on the left side connect channel bhandar. left side connect channel bhandar. left side connect channel bhandar. here you hit that Anshul, I talk to you twice in the morning. If you have n't understood, then if an element does not get the next 9 elements on the right, like it is zero instead of throw, then it has a maximum limit and the type is not there. In this edit this post, consider it as the smallest element in Muskarah and same for left minus one as the smallest element, Patna. Okay, but consider that there is a very big gap on this side of this whole, there is a very small one, there You will be able to expand everyone's boundary You will be able to expand everyone's boundary You will be able to expand everyone's boundary only between here and here, the only between here and here, the boundary of which is to be said that it is not mixed in this oil, boundary of which is to be said that it is not mixed in this oil, as if the forest will not come on this side, as if the forest will not come on this side, then the forest will be considered external and there will be then the forest will be considered external and there will be little from the deprived side. little from the deprived side. little from the deprived side. body will not come, then their horoscope will be considered as this, then it will be given brightness and youth, all of them will be found in it, like the side of the bun too, think, we are going to get offspring from you, two friends, there is a friend, think of the clitoris, we are going to Seven - - Verb - By making Seven - - Verb - By making Seven - - Verb - By making I will either I will get along with I will either I will get along with Jogi All of them together get along with Jogi All of them together get along with Okay so my deposits are kept like this Right Okay so my deposits are kept like this Right Side Effects Academy for Lips Side Effects Academy for Lips Keep your report - If it happens then right for the last ODI Keep your report - If it happens then right for the last ODI Keep your report - If it happens then right for the last ODI not small then its right side and left hand side will be considered as your length. Now I run it reverse edit link - second run I move it towards zero, I run it for the fans, now it Used to wild Used to wild Used to wild wild stock dot size grade vacancy phone wild stock dot size grade vacancy phone and and that as long as they are closed in stock and there are that as long as they are closed in stock and there are five is small so that five is small so that in the research related to arv specific them infidelity small will in the research related to arv specific them infidelity small will pause all the elders he will his home then we him pause all the elders he will his home then we him smaller than our smaller than our smaller than our some small guru because he is a small guy because of his body, it is okay, he started the pick in the neighborhood and he took the answers on the small ones, but it happens that the distance came out, both can be, the size of this type has become zero. Or I am a younger person than you. If you are a younger person then the answer is the same and if the stock is empty then ra.ng Ankit Kushwaha will go. Do Pizza Bread entry that you have got in the last place. It will be a very Pizza Bread entry that you have got in the last place. It will be a very beautiful code. beautiful code. beautiful code. very beautiful, it is for Roka or electronic but it will start from here, it will be like this, but it will start from here, it will be like this, you do 200 and zero's leg you do 200 and zero's leg boundary boundary 2013 - I will get it, it is not for anyone only, 2013 - I will get it, it is not for anyone only, okay, so deposit New Delhi okay, so deposit New Delhi - - you will walk in the forest, you will walk in the forest, this plus plus from Red Lips, so don't worry, I will this plus plus from Red Lips, so don't worry, I will do it in schools and show you in some time, if you do it in schools and show you in some time, if you top it, you will get the water on the left, top it, you will get the water on the left, which you - closed which you - closed which you - closed today I am going to rub for 2 minutes from school, so there is no need to explain to her, there is a huge possibility of explaining pregnancy to her, okay, so when I brought it and started it, it said something like not finding symbol is coming, it was not found because I have If it has been named, if it has been done then it is being If it has been named, if it has been done then it is being accepted and I run the website because I am clever so it has worked. Bring it once, I am drawing you how it was done this year so Brother, Brother, Brother, first everyone's left side lottery was drawn, first everyone's left side lottery was drawn, then the right side was drawn from here to here. then the right side was drawn from here to here. What did I say What did I say that keep this 6 that keep this 6 inductance outside, show its value, I inductance outside, show its value, I put this one. put this one. Okay, whatever you have put and Okay, whatever you have put and called it yours. called it yours. called it yours. one you are the one saying, the next big one returns to the small one and is not able to make it pop, then the one lying on 125 index became happy, 1958 became happy, okay and he could not get it to pop, okay, So we did not get that pop, So we did not get that pop, So we did not get that pop, we have that arrow where there is app and then there is we have that arrow where there is app and then there is answer, then there is Pushya. Okay, so try to wrap it, we could answer, then there is Pushya. Okay, so try to wrap it, we could not get it to pop, the not get it to pop, the name here is the index, so we will name here is the index, so we will show it like this, here we click. show it like this, here we click. show it like this, here we click. just do something, his height boundary was seventh, I could not make it to the top, the same right side effect happened, so I am excited, list more here and five has come and the younger ones have been put to a standstill, the elders We have to keep in mind that they come after We have to keep in mind that they come after We have to keep in mind that they come after pausing the elders. As long as the elders keep pausing the elders. As long as the elders keep meeting you and the meeting you and the topic is you are small and soft, he is the topic is you are small and soft, he is the elder, till then we salute the grandchildren and the elders, we leave the elder, till then we salute the grandchildren and the elders, we leave the younger ones and leave the younger ones. younger ones and leave the younger ones. I am again saying this is a mistake in the universe, the first element is 6, its recovery has been first element is 6, its recovery has been made strict, it will appoint the elders, it will shift, the made strict, it will appoint the elders, it will shift, the stock will be empty till then, stock will be empty till then, then the intake is considered to be your right to the airlines, then the intake is considered to be your right to the airlines, it has been completed. it has been completed. it has been completed. younger one will not get much done, his customer will come and answer that he has one, his mobile number is right, collect this true value fund of Rs 120, let's start friends and something has happened and he has cooked the elders and Brother, you have done Brother, you have done Brother, you have done exactly the right thing, one has been unleashed, Anvi has been released, exactly the right thing, one has been unleashed, Anvi has been released, its next 9 element has come inside, its next 9 element has come inside, no, but here we will take its index, we are no, but here we will take its index, we are mixing it even in SMS time, mixing it even in SMS time, but there is difficulty in explaining it, so I am but there is difficulty in explaining it, so I am showing you the value of the gift. showing you the value of the gift. showing you the value of the gift. something else happened here, five came, but the neighbor does the small one, you do not pipe, you could not do it, and if you could not do it, then that time is next9, this model Bank of the Light accepted, viewers welcome inch neck and He is the same and was asked, you came to the elders, He is the same and was asked, you came to the elders, He is the same and was asked, you came to the elders, Bakayan to Bakayan, you could not Bakayan to Bakayan, you could not tube, did not understand, huge inequality, paused it tube, did not understand, huge inequality, paused it and turned it off, could not talk to the band, and turned it off, could not talk to the band, Whisker Actress 154 Bakayan, Whisker Actress 154 Bakayan, it is small, you became the answer. it is small, you became the answer. it is small, you became the answer. give one or 165 in front of two and then it will be asked, if six comes then it is the morning for the younger ones supporting the elders, but stop doing it, you will be the answer to this conduct dynasty, then subscribe points, Do Do Do because reminder is phoenix topic 5.33 because reminder is phoenix topic 5.33 Decrease flight mode is going friend Decrease flight mode is going friend mix cider is there message again that mix cider is there message again that shutdown is recovery samsung is a strange shutdown is recovery samsung is a strange express border do seventh measure express border do seventh measure now now will make play list powder similarly deposit in it - will make play list powder similarly deposit in it - tied from here tied from here tied from here then there is a doctor for it on this platform - slaughter and it has been paused. 6 to come in the stock, the elders do the lesson, they have shrunk, if the tea is over, has it become empty, then it will be If you are If you are not able to pop the pipe and that then you became his co-mix model whose index is 54 and then left him complete or handing him over to the elders, the younger one was yours, you paused the pot, the younger one I took I took I took note of the fact that you will break down and when asked, if you are note of the fact that you will break down and when asked, if you are not able to get the younger one to talk, then only you not able to get the younger one to talk, then only you and he had become his and he had become his left country, left country, now that there is a garden, now that there is a garden, it will be a problem for the elders, if the it will be a problem for the elders, if the vote has become vacant, April has become vacant, then on that side. vote has become vacant, April has become vacant, then on that side. On his platform - Minister Baban Kushwaha On his platform - Minister Baban Kushwaha Six, if you are not able to do this, then his Six, if you are not able to do this, then his height will increase, all white and your work is height will increase, all white and your work is over, in the end he will be a teacher, over, in the end he will be a teacher, on whom it does not matter, now you on whom it does not matter, now you fight on this platform, there is also a border, first fight on this platform, there is also a border, first try making it, six. try making it, six. try making it, six. platform - but means from here till here on Friday it is the same bed as the pot - which pot minus one is in this - if its one minus minus one is two then it is two Alarm is for 6a how to Alarm is for 6a how to Alarm is for 6a how to Congress party leaders Congress party leaders minus one circle how many 5 - - one means left minus one circle how many 5 - - one means left is our sea increases is our sea increases right - select - one to 5 - - 16 - 215 right - select - one to 5 - - 16 - 215 2125 05 only host is grease 2125 05 only host is grease laptop green laptop green laptop green 12615 so Basically, for the former, for four, that face is on this side and one is on that side, so for 514 finance ministry laptop, this one is on this side, 5353 2101, this one is on this side for them - 08 That That That this weight has become now Monday do 62162 * this weight has become now Monday do 62162 * 50 515 points 12512 Balance 512 7766 50 515 points 12512 Balance 512 7766 Biggest Railways Basically you took Biggest Railways Basically you took out the lift of the high school and replied its height at the right time. out the lift of the high school and replied its height at the right time. Right one to the life management man, you had Right one to the life management man, you had got the weight. All these areas on the side are yours. got the weight. All these areas on the side are yours. Don't take it out, he is the biggest one Don't take it out, he is the biggest one who has become yours. I hope you have understood this. who has become yours. I hope you have understood this. Okay, so we will get questions from the sites, that too Okay, so we will get questions from the sites, that too on that topic. Define on that topic. Define question-01 There will be question-01 There will be no tricks in dance choreography. no tricks in dance choreography. no tricks in dance choreography. it is easily gone, the stocks are able to be kept there only for a year because the Next 9 limit has been used, if it happens then all the 9 is written, the second correction has been made within time but in the largest area Instagram question, so What was the dried dongri and used to take What was the dried dongri and used to take What was the dried dongri and used to take out the left and to take out the right out the left and to take out the right we were the next small element we were the next small element and to take out the right we did not do next 9 limit and to take out the right we did not do next 9 limit and laddus which used to pop, and laddus which used to pop, we were all yellow when the big one was big in the stock. Here the equals will also have to chop and come to see Here the equals will also have to chop and come to see that you are actually present in the tree. If you are that you are actually present in the tree. If you are not looking for maximum and oil, then the not looking for maximum and oil, then the equals will also have to pause if there equals will also have to pause if there is a big value in the tag or the platform for the sacrificial ritual and is a big value in the tag or the platform for the sacrificial ritual and Kayan Tower. Kayan Tower. Kayan Tower. Pure Correction Ride Made in the Question Vidyapeeth and It Means and Ability Test Case Solved Was Appointed New Destinations Thank You Very Much See You in Next Video | 2024-03-20 12:33:28 | 84 | Largest Area Histogram | Solution |
|
lf9c-3Ld_jU | hey everyone welcome back and today we'll be doing another lead code 409 we'll be doing another lead code 409 longest palindrome and easy one given a longest palindrome and easy one given a string gas which consists of a lowercase string gas which consists of a lowercase and uppercase letter written the length and uppercase letter written the length of the longest palindrome that can be of the longest palindrome that can be built with those latter letters are case built with those latter letters are case sensitive for example a a is not sensitive for example a a is not considered a palindrome here considered a palindrome here so they want us to just return the so they want us to just return the palindrome length you can say and but palindrome length you can say and but they do not want us to return the they do not want us to return the palindrome itself so it is easy but we palindrome itself so it is easy but we can do if can do if account of a certain character is account of a certain character is positive we are definitely adding it to positive we are definitely adding it to our palindrome why because we can put it our palindrome why because we can put it at one at the very end one at the very at one at the very end one at the very first first so so but it all boils down to is the middle but it all boils down to is the middle character character like if we can add we can add one like if we can add we can add one odd character or not or bus stop just uh odd character or not or bus stop just uh one one so we will be adding one character which so we will be adding one character which is a single in its uh string to the is a single in its uh string to the middle and that's it so we can carry b b middle and that's it so we can carry b b uh b b single and four C's and D that uh b b single and four C's and D that will make the seven so at the first time will make the seven so at the first time you'll be carrying DD and then we will you'll be carrying DD and then we will be carrying CC and we have a one space be carrying CC and we have a one space for our middle element so we'll be for our middle element so we'll be carrying B and if we make a palindrome carrying B and if we make a palindrome by this we are not going to make a by this we are not going to make a palindrome but for just understanding palindrome but for just understanding like this the palindrome will be like like this the palindrome will be like this uh reading from the left it is the this uh reading from the left it is the same reading from the right is it is the same reading from the right is it is the same same so let's get started with we can do it so let's get started with we can do it from a hashmap but we can also use in from a hashmap but we can also use in the python at least a counter which will the python at least a counter which will count count the values for us the yes the count the values for us the yes the count values for us how many times it is being values for us how many times it is being repeated so and also our output will be repeated so and also our output will be 0 for I in 0 for I in so for not I in rent but for every character in you can say you can count let's call it count so every count in C dot values which will give us the values so output we are going to append it to our output like this and what we'll be doing in this case is just dividing our count by 2 and then multiplying by 2 so we can the neck the odd ones you can say like the neck the odd ones you can say like if it is clear so now we'll be checking if it is clear so now we'll be checking if output is if output is equal if output is divisible by 2 okay equal if output is divisible by 2 okay and at the same time our count should be and at the same time our count should be this is for the middle middle character this is for the middle middle character all of this if condition is so count at 2 if it is equal to 1 which means it is an odd character what we will be doing in this case is just appending our output adding one to our output because it is a single character or an odd character we do not want to take if it is a three we do not know we will be taking the three but if it is uh you can say a single graduate yes A Single Character but uh yes if it it is a single character like B will be appending it our output and after doing all of this we can just return our output and this should work fine let's see if this works yeah this works and yeah this works and that's it that's it yeah that's it | 2024-03-22 10:43:40 | 409 | 409. Longest Palindrome | Leetcode | Python |
|
7jDS9KQEDbI | That the country's most important question recording interview is in this point in recording interview is in this point in a lot of this interview solution I want to see what a lot of this interview solution I want to see what fiber skin coat 19 grower of fiber skin coat 19 grower of solution but today the tell you about this method you solution but today the tell you about this method you for watching and using Hello friends for watching and using Hello friends welcome back to welcome back to welcome back to programming with that today problem problem asked the but tried to simplify the problem statement for you to give in the role of a teacher name and target value2 Half a minute on the rumor number Half a minute on the rumor number Half a minute on the rumor number that in when you are giving and that in when you are giving and derivatives called them at market value now derivatives called them at market value now second has committee of light and give in this second has committee of light and give in this question is that can be finger to do the return of subscribe 602 and slowly 217 one day them 229 Can feed in there element dec29 in Can feed in there element dec29 in Can feed in there element dec29 in oneplus 1526 711 good also 80 211 1431 and font oneplus 1526 711 good also 80 211 1431 and font in this answer buddhi viron ka 12780 in this answer buddhi viron ka 12780 and tight number to three do for you to give the and tight number to three do for you to give the volume to give good gifts on volume to give good gifts on 100 you can see but you will only one 100 you can see but you will only one 100 you can see but you will only one Tears Into And Four Days After Adding Up To Give The River Target 69 Way History Winters Like 0210 Hai Winters 120 Answer To In This Case One To During S That In This Case Which Can Define APS And And And staff at least 60 unit certificate to in this staff at least 60 unit certificate to in this case Agnewesh indexing and once again case Agnewesh indexing and once again this answer 200 ka mobile this answer 200 ka mobile a special yadav problem statement looks like a special yadav problem statement looks like you refuse in the role of a teacher and at you refuse in the role of a teacher and at market value and its guarantee daughter market value and its guarantee daughter of interior donkeys now in its of interior donkeys now in its of interior donkeys now in its defense of elements that now left for this video and tribes problem on so for the solution Liquid developer problem solution first now to-do list problem how to find the phone the walking into a AC you can try to find The Elements One by One Co What Do You Can The Elements One by One Co What Do You Can The Elements One by One Co What Do You Can Start Weather for Element 16.81 1623 Length 64 Ki Entrance 1615 Light and Swear Food Be Co Mute Behave Entries Co Target Volume Mute Find It Anywhere Light Co England Voted Against the Number 8 Try And in this point And in this point And in this point out some water food also out some water food also hello viewers penal code na target shanidev what hello viewers penal code na target shanidev what does not write down the mission impossible rukh something like does not write down the mission impossible rukh something like oo hai to ashwin scene shoot down all the some possible of all the combination ultimately to find the Fall in the industry Fall in the industry Fall in the industry and of course to MP3 for this solution is and of course to MP3 for this solution is very well at bottom problem which is my is very well at bottom problem which is my is very large no key very large no key side is that mini element and would have made side is that mini element and would have made combination over her tight combination combination over her tight combination silk calculate distance silk calculate distance notification approach to law and approach in notification approach to law and approach in About that About that in problems Jhantu basically search for in problems Jhantu basically search for two number light win the race for watching in two number light win the race for watching in built for this beneficial and come to mind to built for this beneficial and come to mind to think what is the guide channel thank you can think what is the guide channel thank you can find something for searching for its find something for searching for its elements meaning water tis its original elements meaning water tis its original volume volume That a original added 8 elements and dark That a original added 8 elements and dark stretch is not but previous report and stretch is not but previous report and right down the you are right down the you are so now up my is potter and the first so now up my is potter and the first elements play list element and the last elements play list element and the last element style object element nine to element style object element nine to find the number black list number find the number black list number find the number black list number One Number One And Slept For 2nd Are The Number Number Number Number Three Larger Than Life In A How To Draw A Number Smiled And One Night But You Number Set Up Small Wooden Floor Three In This Approach Drove The Motor Try to Point One Step Back And Point One Step Back And Point One Step Back And Resort And Right The Avengers Model Number 23 Resort And Right The Avengers Model Number 23 Is So I Last For Entering In The Is So I Last For Entering In The Twentieth Reel 101 Shades Co Spun More 09 Twentieth Reel 101 Shades Co Spun More 09 2012 Ine More Number This Time I 2012 Ine More Number This Time I Tried To 6 And Leave One Step Back To One Tried To 6 And Leave One Step Back To One And 600099 Inter College And 600099 Inter College And 600099 Inter College Name Attracted 2016 2016 2019 MP3 Yakin Existen Target Was Not Show My Point 824 This Time 809 Some Come To Be Edited 500 Target Value To What We Do This Who Reduced Last Point A I Give Give Give element no that and element no that and yes matches after get married that now yes matches after get married that now value is 82.80 app and and this is value is 82.80 app and and this is 15212 is you can look up in the original 15212 is you can look up in the original affidavit for 108 number 108 number 4 inches affidavit for 108 number 108 number 4 inches that answer is B-1 and B-2 coach number s- that answer is B-1 and B-2 coach number s- that answer is B-1 and B-2 coach number s- Not The First Time Complexity After Log In Do Subscribe And Difficult Time Complexity Interview Lokp Hello Viewers Pointing Problem You Think Multiple Base Light Off Shifting Problem In Reverse Direction What Is The Mean 2.2 Elements Straight Light this Video not Lo Solution of Chapter Number 9 0 0 Answers In Every Time You Work Harder Time Right To Improve The Time Of Not Even You Temple Them At A Place For Elements 600 800 Implement Food 9 - 60 2223 Lut Pati Table You Can Find The To you two and six number index in the To you two and six number index in the To you two and six number index in the festival 6 and going ahead number 493 494 festival 6 and going ahead number 493 494 3215 again play list number 2 3 3215 again play list number 2 3 that complement of 2319 dubai a pun skin same note point - for annual festival you simply quantity 3 and Struggle Struggle Struggle A Moving Ahead High Court Number 8 A Moving Ahead High Court Number 8 A Complement Of 819 Dubai 1111 Also Did A Complement Of 819 Dubai 1111 Also Did Not Accept Hindu Festival To Not Accept Hindu Festival To Adapt Eleventh And Its Index Adapt Eleventh And Its Index Na Now Why Bed Mute The Number 15th Na Now Why Bed Mute The Number 15th Complaint 1519 Guddi That Former Tried To Look For In The Is Find over here right down there Find over here right down there Find over here right down there uses for notification you have an uses for notification you have an index for this during Sarovar Hair and other index for this during Sarovar Hair and other index in Indian History Bal So in this index in Indian History Bal So in this case 101 Answer Comfort to be given news on this very much similar to case 101 Answer Comfort to be given news on this very much similar to the answer is yes the answer is yes Pandey and these Pandey and these Pandey and these complexity of this refer chilli powder of in that is pair finger scan dark once on the right side this solution you piece complexity of order of benefit these table date maximum clear number of elements nine today latest to the river Understand this code allot limitless Understand this code allot limitless Understand this code allot limitless examples paste to left side of the examples paste to left side of the court to implement right to edu is this court to implement right to edu is this your name target person has parameter in a your name target person has parameter in a big way Shri Govind head start allu ki agri hydration what does not confident volume Confident Confident Confident In Difficulty Target - Number Set In Difficulty Target - Number Set Identification Loot Ko Dali Complement Identification Loot Ko Dali Complement 19603 19603 Is Next That Time To Complement To Find It Is Next That Time To Complement To Find It Means Quarter Solution But You Can Find The Right To Avoid Simply Put This Value Along With Index In The Huntsman Index In The Huntsman Ko Mahatma Half Inch 60 Ko Mahatma Half Inch 60 K K K were appointing ad number 410 also appoint compliment time till medium to be 9 - on date this thing pain phase map swift volume civil defense loot's cutting and you have no value 23.28 waist three layer is later Limit for b 9045 york Limit for b 9045 york Limit for b 9045 york and thus will return to contacts and and thus will return to contacts and induction time crop induction time crop jai hind is case weight come office canceled to i hope life is the problem and solution for u left early years of famous problem benefits of lord of 10th prime On What They Think Subscribe Can Improve The Way Give Some Subscribe Can Improve The Way Give Some Thoughts In This Problem In To-Do List Channel Thoughts In This Problem In To-Do List Channel Subscribe To Subscribe To That Man Criminal Intimidation Milo In That Man Criminal Intimidation Milo In Case You Want To Share That Might Interest You This Case You Want To Share That Might Interest You This Code With All The Elements And Code With All The Elements And Code With All The Elements And available free profile subscribe my channel | 2024-03-15 16:45:40 | 1 | Two Sum (LeetCode #1) | 3 Solutions with animations | Study Algorithms |
|
ISir207RuKQ | Share Guys Welcome To Your Comments In This Video You Will See The Question Designing Subscribe Now To Receive New Updates And To The Giver And - Note Content For The Giver Not Question Is The Beginning Library Simple Solution Question Is The Beginning Library Simple Solution Used Oil The The The The Ko Ek To Instructor Beating Up Map And Instructor Vilas Length 10.30 am Validator And Civil Line - 1090 Value Currently And Forget Wick In The Street Vendor And Forget Wick In The Street Vendor Index Index That In Remove Method Which Can Just Set The That In Remove Method Which Can Just Set The Volume To Minus One Pour Reference No Volume To Minus One Pour Reference No Value Currency Value Currency Value Currency Is The President Work Pura Network Test Cases Where To Give Not Difficult Do Do Do Do Do Do Do Do Do Do Do That Use Jitendra Sweater 205 Waqt The Self Respecting And Submit The Values Into This Channel Must Subscribe Button Which Will Work List because in this situation different List because in this situation different List because in this situation different key entry in class entry key entry in class entry combination decide what is the number of the day ki combination decide what is the number of the day ki asli shirt dress code and creator asli shirt dress code and creator entry class 9 ki entry class 9 ki jis class monitor akki and wali hai ki jis class monitor akki and wali hai ki and constructive and setting its and constructive and setting its volume so let's make a public volume so let's make a public volume so let's make a public return home entry class work will be return home entry class work will be making this mean that nothing but a to improve marriage are off list content pendry in and construct new to take off that even today discuss 2769 and now you can just say map equal to a That penis left side open president mike sudhir vibration of knowledge and see the value so they do others will get number canteen and so they do others will get number canteen and junior research in the and but at least to the junior research in the and but at least to the giver is 16000 for sister calculator but oh To-do list To-do list To-do list Play list A key Play list A key in the entries Neetu Search for the giver's in the entries Neetu Search for the giver's needle extract is over the entries needle extract is over the entries And here this entry Nautanki And here this entry Nautanki Hu is equal to my key name I love you love you love you Hu is equal to my key name I love you love you love you love you to Iss Point Mintu Iss Point Mintu Iss Point Mintu Returns The Association Volume Otherwise - Subscribe - 2 Mein Knowledge To Hide And Seek Another Method Input Method Its Value And Dissenty Insider Map Online News Current Entry Entry Entry Entry Be That Hanuman Sihag And Bucket A Need To Check Weather Pressed Creativity And List Tweet A List Tweet A List Tweet A Aap Is Tawa Katnal-1 To Create New Link Aap Is Tawa Katnal-1 To Create New Link List And The Current Entry Antonyms Hai To 10:00 Buzz Take Care Tips Number Twenty Knowledge C Is But Not A Tomorrow Morning Need To Attract Over Each And Every Ajay Ko Ajay Ko 200M setting this mic that is equal to the key 200M setting this mic that is equal to the key drama present president updating drama present president updating divine current but I am safe about method knowledge to remove this Creativity and field on who is that was Creativity and field on who is that was Creativity and field on who is that was a team which can simply retail price presents you need to remove is otherwise Vineet to straight and reddy how to where is that these are equity linked to how to where is that these are equity linked to remove remove that I will take the particular entry in that I will take the particular entry in that I will take the particular entry in Temporary Variable Hello Friends Defined Serial Usage 210 Will Help In Removing From Pearl This Channel Otherwise Remove From The Meaning That Surdas All About Remove Method Sunao Let's Go Ahead And Scored And Its All the All the All the numbers of the day numbers of the day that a | 2024-03-21 10:24:40 | 706 | Design HashMap | Live Coding with Explanation | Leetcode - 706 |
|
TocZS1bPae8 | welcome ladies and gentlemen boys and girls today we are going to solve girls today we are going to solve unschooled problem which is must do unschooled problem which is must do binary tree so this is the binary binary tree so this is the binary problem see as simple like you get from problem see as simple like you get from the title idea okay so ladies and the title idea okay so ladies and gentlemen let's just see like what the gentlemen let's just see like what the question is in the questions having been question is in the questions having been given a 2 by 3 is root 1 and root 2 and given a 2 by 3 is root 1 and root 2 and we have to written their sum so we have to written their sum so you know simple like root 1 you know simple like root 1 plus root 2 you have to give root 3 like plus root 2 you have to give root 3 like that the complete complete value okay so that the complete complete value okay so what did i mean by saying this if you what did i mean by saying this if you see over here then you're saying add 1 see over here then you're saying add 1 plus 2 give us 3 3 plus 1 give us 4 2 plus 2 give us 3 3 plus 1 give us 4 2 plus 3 give us 5 and 5 plus 3 give us 5 and 5 plus no give us plus no give us 5 5 no plus 4 give us 4 no plus 4 give us 4 empty plus 7 give us 7 that's impressive empty plus 7 give us 7 that's impressive so that's how we we have to uh tackle so that's how we we have to uh tackle this problem so ladies and gentlemen uh this problem so ladies and gentlemen uh now you will ask like okay how we gonna now you will ask like okay how we gonna do this then i will say like we will do this then i will say like we will traverse recursively in this one traverse recursively in this one okay so we will there was a recursive okay so we will there was a recursive way way all right and what else we can do so all right and what else we can do so what i'm thinking is like as you're what i'm thinking is like as you're developing vehicles then i will add the developing vehicles then i will add the tree value in in one tree let's say like tree value in in one tree let's say like i will use root root uh this root one i will use root root uh this root one tree t1 then let's go to t1 so i will tree t1 then let's go to t1 so i will add my all the values of the t2 into t1 add my all the values of the t2 into t1 and i finally written my t1 that's what and i finally written my t1 that's what i'm thinking about so i'm thinking about so if you still don't understand don't if you still don't understand don't worry as you write because the code is worry as you write because the code is very simple as you write the code you'll very simple as you write the code you'll definitely want to understand so ladies definitely want to understand so ladies and gentlemen without any further ado and gentlemen without any further ado let's just start writing this problem let's just start writing this problem and here we go and here we go so my first job is i will just simply so my first job is i will just simply say okay do one thing check if my root say okay do one thing check if my root one is null then what you have to do if one is null then what you have to do if my root one is completely null then my root one is completely null then simply just written root two simply just written root two now you are like why not root one now you are like why not root one because like might be root 2 as well because like might be root 2 as well value present we don't know so i will value present we don't know so i will simply say written root 2 as simple as simply say written root 2 as simple as that if the another condition will say that if the another condition will say if my root 2 is null if my root 2 is null then i will written my root 1 value if then i will written my root 1 value if let's say if something 8k has something let's say if something 8k has something present there is important by root 1 present there is important by root 1 complete tree the simply returned it complete tree the simply returned it okay okay now you can say like okay dude okay okay now you can say like okay dude we have what uh root one tree and the we have what uh root one tree and the root two three as well then what we're root two three as well then what we're gonna do i'll just simply say okay do gonna do i'll just simply say okay do one thing add root one root value one thing add root one root value into my add root one value with root two into my add root one value with root two value okay and finally return rule one that's what i'm thinking to do but before that i have to traverse in the complete tree so for that one i will just simply uh use mercury function to traverse in that one so i will say root one dot left so i will go for the next one using my mastery uh pole okay guys so i will go for my root one dot left similarly to the root two dot left okay as we are using root one tree so i will simply enter over here as well root one don't write nodes to two okay with my merge please function i hopefully rejected the sixth floor i hopefully rejected the sixth floor like what i'm doing over here so that's like what i'm doing over here so that's all the core is ladies and gentlemen so all the core is ladies and gentlemen so yeah that's what the code is let me just yeah that's what the code is let me just give a quick run it and i will give a quick run it and i will take you a quick walk to the code like take you a quick walk to the code like what we did over here and here we go what we did over here and here we go gentlemen is accepting very well so gentlemen is accepting very well so let's talk about like what we are doing let's talk about like what we are doing so these are our two base conditions the so these are our two base conditions the base condition is saying like let's say base condition is saying like let's say if one is present it is not present then if one is present it is not present then written the root two three if the two is written the root two three if the two is not written then simply return the root not written then simply return the root one tree over here what i'm doing i'm one tree over here what i'm doing i'm adding the value adding the value of one adding the value adding the value of one plus two which will give us three like plus two which will give us three like this one i'm doing over here and over this one i'm doing over here and over here what i'm doing i'm trying to here what i'm doing i'm trying to traversing uh first time it's left side traversing uh first time it's left side then second time i'm traversing the t then second time i'm traversing the t root one three right side okay so stable root one three right side okay so stable thing and it's uh putting the putting thing and it's uh putting the putting the value over here and we are finally the value over here and we are finally entering our root one either you can go entering our root one either you can go for the root two three so what do you for the root two three so what do you have to do you just have to simply have to do you just have to simply change over here like okay we are going change over here like okay we are going for the root two we are going for the for the root two we are going for the root two but if you want to go for the root two but if you want to go for the root two okay if you are going for the root two okay if you are going for the root one then root one then go go like the similar like like i did go go like the similar like like i did okay ladies and gentlemen without any okay ladies and gentlemen without any further let me just submit this code to further let me just submit this code to see anytime complexity complexity like see anytime complexity complexity like i will talk about time complexity and i will talk about time complexity and all over here so let me just sum in this all over here so let me just sum in this code code to see all the test cases are passing or to see all the test cases are passing or not not so so here we go ladies and gentlemen the code here we go ladies and gentlemen the code is accepting very well okay now let's is accepting very well okay now let's talk about the time complexity in this talk about the time complexity in this one we are dealing with the time one we are dealing with the time complexity in this one we are dealing complexity in this one we are dealing with big o of n and for that as we are with big o of n and for that as we are traversing n numbers of nodes that in traversing n numbers of nodes that in the worst case the time was the big of n the worst case the time was the big of n okay and what this phase complexity in okay and what this phase complexity in this one we are dealing with leading this one we are dealing with leading generator space complexity in this one generator space complexity in this one we are dealing with this big of n we are dealing with this big of n for the worst case for the worst case for the worst case for the worst case and you know like we are putting the and you know like we are putting the value so kind of like is using the stack value so kind of like is using the stack but let's say for the like average case but let's say for the like average case the tank conversity we will gonna deal the tank conversity we will gonna deal with low of n so this is for the worse with low of n so this is for the worse let me just write it clearly for the let me just write it clearly for the verse verse and this for the average okay so houston and this for the average okay so houston legion when this score is very clear legion when this score is very clear like what we are doing over here so like what we are doing over here so ladies and gentlemen if you still have ladies and gentlemen if you still have any doubt just do let me know in the any doubt just do let me know in the comment section i will definitely comment section i will definitely release to you and thank you very much release to you and thank you very much ladies and gentlemen for watching this ladies and gentlemen for watching this video i will see you in the next one video i will see you in the next one till then take care bye bye and i love till then take care bye bye and i love you guys believe me i love you take care you guys believe me i love you take care bye-bye | 2024-03-20 12:30:17 | 617 | Merge Two Binary Trees | LEETCODE - 617 | Easy solution |
|
j5DDF7zlpz8 | [Music] in December uh time is 12:24 a.m. uh the in December uh time is 12:24 a.m. uh the match is about to start and the match is about to start and the motivation for solving this lead code motivation for solving this lead code problem is the first one is we haven't problem is the first one is we haven't solved it in the past it's a fresh solved it in the past it's a fresh question so after a very long time I got question so after a very long time I got a fresh question I thought let's do it a fresh question I thought let's do it the second motivation is actually the the second motivation is actually the main motivation I met rajat today rajat main motivation I met rajat today rajat is one of the subscriber of coding is one of the subscriber of coding decoded he has been following coding decoded he has been following coding decoded channel from quite some time now decoded channel from quite some time now and he just joined Adobe today so in the and he just joined Adobe today so in the morning he messaged me personally on the morning he messaged me personally on the telegram group stating that he has telegram group stating that he has joined adob and would like to meet me in joined adob and would like to meet me in office I clicked a photograph with him office I clicked a photograph with him I'll be sharing the entire details of I'll be sharing the entire details of the incident on LinkedIn very soon so the incident on LinkedIn very soon so stay tuned and I was super excited to stay tuned and I was super excited to see that even in this time of lay off see that even in this time of lay off this recession time where everyone is this recession time where everyone is struggling with their jobs quoting struggling with their jobs quoting decoded could contribute to others life decoded could contribute to others life and I'm super pleased about it now let's and I'm super pleased about it now let's get back to the question given an array get back to the question given an array of size n cross n of size n cross n wherein uh all the numbers are of type wherein uh all the numbers are of type integers what do you need to do you need integers what do you need to do you need to return the minimum sum of any falling to return the minimum sum of any falling path to the Matrix so the path starts path to the Matrix so the path starts from the top row goes up to the bottom from the top row goes up to the bottom row and at each cell there are three row and at each cell there are three options to take either you can go in the options to take either you can go in the immediate lower Direction immediate left immediate lower Direction immediate left Direction immediate right direction so Direction immediate right direction so out of the three possibilities you want out of the three possibilities you want to select the one that gives you the to select the one that gives you the least cost so I'll be talking more about least cost so I'll be talking more about the solution by the presentation so the solution by the presentation so let's Qui hop on to let's Qui hop on to it here in this question you given a it here in this question you given a matrix size n cross n and what you need matrix size n cross n and what you need to do you need to move from the topmost to do you need to move from the topmost row to the bottommost row which is this row to the bottommost row which is this one and while moving from the topmost one and while moving from the topmost row to the bottommost row you need to row to the bottommost row you need to keep in mind that you have to always keep in mind that you have to always select the minimum path minimum weighted select the minimum path minimum weighted path so you given weight for each cell path so you given weight for each cell and as per the question while moving and as per the question while moving onto the next cell for example if you onto the next cell for example if you are over here if you want to move over are over here if you want to move over here then there are three parts possible here then there are three parts possible you can come from this route you can you can come from this route you can come from this route and you can come come from this route and you can come from this route which one are you going from this route which one are you going to select you will select the one that to select you will select the one that gives you least weight so for reaching gives you least weight so for reaching this particular node the cost would be 1 this particular node the cost would be 1 + 5 which is six so let's write six over + 5 which is six so let's write six over here the cost for reaching this here the cost for reaching this particular node would be equal to a particular node would be equal to a minimum of 2 and one so because one minimum of 2 and one so because one route is this other route is this so route is this other route is this so minimum of two and one gives you 1 1 minimum of two and one gives you 1 1 plus 6 gives 7 so let's write 7 over plus 6 gives 7 so let's write 7 over here the cost for reaching this here the cost for reaching this particular cell would be minimum of 1 particular cell would be minimum of 1 and 3 which is 1 + 4 which gives you and 3 which is 1 + 4 which gives you five so let's write five over here and five so let's write five over here and let's repeat the same thing for these let's repeat the same thing for these three cells as well so here let's write three cells as well so here let's write seven over here let's write 8 over here seven over here let's write 8 over here let's write 9 over here these are not let's write 9 over here these are not the actual minimum path these are the the actual minimum path these are the current values for these particular current values for these particular nodes so the actual minimum paths would nodes so the actual minimum paths would be equal to minimum of 7A 6 which is 6 6 be equal to minimum of 7A 6 which is 6 6 + 7 gives you 13 so the answer here + 7 gives you 13 so the answer here would be would be 13 for reaching this particular cell 13 for reaching this particular cell three parts are possible 1 2 and three three parts are possible 1 2 and three the minimum of these three values five the minimum of these three values five six and 5 6 and 7 would be five 5 + 8 six and 5 6 and 7 would be five 5 + 8 gives you 13 so the answer here would be gives you 13 so the answer here would be 13 let's proceed ahead the next cell 13 let's proceed ahead the next cell that we have happens to be this one so that we have happens to be this one so uh there are two parts possible one is uh there are two parts possible one is this one other one is this one minimum this one other one is this one minimum of 5 and 6 is 5 5 + 9 gives you 14 so of 5 and 6 is 5 5 + 9 gives you 14 so the answer here would becomes 14 now you the answer here would becomes 14 now you have successfully reached the last row have successfully reached the last row and the final answer would be equal to and the final answer would be equal to the minimum of the value that is set in the minimum of the value that is set in this entire row because you can reach this entire row because you can reach any cell in the last row so the minimum any cell in the last row so the minimum value that exists in this last row value that exists in this last row happens to be 13 so the answer becomes happens to be 13 so the answer becomes 13 this isn't sync with our expectation 13 this isn't sync with our expectation this is what we are going to do in the this is what we are going to do in the coding section as well the time coding section as well the time complexity of this approach is order of complexity of this approach is order of n Square the space complexity of this n Square the space complexity of this approach if you're creating a new array approach if you're creating a new array new DP array then the space complexity new DP array then the space complexity would be order of n square if you're would be order of n square if you're updating the original array which is not updating the original array which is not a good practice then the space a good practice then the space complexity would be order of one to complexity would be order of one to conclude it further let's quickly walk conclude it further let's quickly walk through the coding section and get a through the coding section and get a good hold of the entire algo here in the solution uh I have used and updated the same Matrix which is not a good practice ideally I would have created a different dprf for this however one of the subscribers submitted the solution the same solution in Java so I thought you guys would be able to correlate to it the most so here basically he has created a helper method wherein he's identifying the minimum path possible out of the three paths and he does that depending upon the conditions of the column index if we are at the first uh column if we are at the last column then these conditions should be checked and then we return the minimum one out of the three possibilities uh and basically we are doing it for each cell therefore uh we have written two Loops over here our index starts from I equals to 1 why because we are doing it from the first row till the last one and this is pretty simple and straightforward once we have identified this up what do we do we basically identify the minimum value in in the last row so whatever the minimum value exists in the last row that becomes our answer and this algorithm correspond to that so let's try and up accepted awesome this is up accepted awesome this is approximately approximately uh 95% faster which beats a lot of good uh 95% faster which beats a lot of good developers in terms of time complexity developers in terms of time complexity and this seems like a good solution and this seems like a good solution ition with this let's wrap up today's ition with this let's wrap up today's session I hope you thoroughly enjoyed it session I hope you thoroughly enjoyed it if you did then please don't forget to if you did then please don't forget to like share and subscribe to the channel like share and subscribe to the channel thanks for viewing it have a great day thanks for viewing it have a great day ahead and sa you for more updates from ahead and sa you for more updates from coding decoded I'll see you tomorrow coding decoded I'll see you tomorrow with another fresh question but till with another fresh question but till then goodbye | 2024-03-25 11:36:02 | 931 | Leetcode 931 Minimum Falling Path Sum | Coding Decoded SDE Sheet |
|
ipovEFTOGyE | Dream II car, when I know I'm in this row, I'll wear it and solve a math in this row, I'll wear it and solve a math problem to know better. For more problem to know better. For more detailed information, please go to the available books. okay how okay how we work this number Ok hello we work this number Ok hello everyone came here 2 years of d up to everyone came here 2 years of d up to Nikko play times Today we will Nikko play times Today we will continue with you this one song already before continue with you this one song already before coming to the next of the responses coming to the next of the responses coming to the next of the responses today Can Tho has anyone going to work 747 Lucky number of English day of Death Ok to present us like me given a life of five and there is only 1 largest number find this piece Is it Is it Is it twice as big as all the molecules of re? twice as big as all the molecules of re? For example, we have a network of 36, the For example, we have a network of 36, the largest number is 6, then compared to largest number is 6, then compared to all the retry, the number 6 must be at least twice as all the retry, the number 6 must be at least twice as big big in the molecules. in the molecules. in the molecules. we have 6 times double three and 6 times 1 and not counting zero. This 6 level is at least 2 times the remaining words, this is the largest number that in the remaining molecules, I just maybe it's three, 6 divided by two is three, but 1234 is the largest number, but four is double or not just 1, how many times is that? command and we Return not one but if interesting then we go name the Index of this number Ok the idea of this article is also for the audience because we need to check whether this largest number 2 times more than the 2 times more than the 2 times more than the other molecules, then we just need to find the other molecules, then we just need to find the second largest molecule and we second largest molecule and we will compare the largest molecules into the will compare the largest molecules into the second order, but it is greater than or equal second order, but it is greater than or equal to 2 times the second largest molecule. to 2 times the second largest molecule. to 2 times the second largest molecule. it, then I'm this combined and we write down the name Index of the largest number. Okay, so this lady will be similar to finding the third largest number that In the all In the all In the all right section Ok now let's start with the exercise right section Ok now let's start with the exercise Ok first we will need 2 canes which are Ok first we will need 2 canes which are Les Tab and Jessica number to céleste shore Les Tab and Jessica number to céleste shore then we will save the largest number then we will save the largest number of the dirty sackcloth Lumpur then of the dirty sackcloth Lumpur then of the dirty sackcloth Lumpur then will save it for Monday. Ok we can see that the problem for all the elements is greater than zero so we will initialize these two variables the first number Serial number with negative alligator ok that will ensure that in time that will ensure that in time that will ensure that in time we can find If but not we can find If but not find the largest number two is the largest number find the largest number two is the largest number then the value and remains about - 1 then the value and remains about - 1 if we achieve zero then if if we achieve zero then if the piece the piece the piece n't know what kind of scene it is again, we won't be able to distinguish between the first number and the normal number here, we will have a case that is if As expected, it is equal to one. This means that this thing has only one element, then this is the asuka of this coin. If there is only one Buddhist, it is of course larger than all the remaining elements. The remaining molecules are considered okay, but we will always have the Index of the first molecule. We will go through that from beginning to end. Ok if there is anything to lose. Whose number is first dream, we will first dream, we will first dream, we will reassign it to the good one. How is it? The reassign it to the good one. How is it? The number a a. number a a. But before re-labeling the But before re-labeling the first number as number a, we will first number as number a, we will save the previous value of the save the previous value of the removed one because of the removed one because of the removed one because of the it will become the second largest number when searching with the first largest numbers, the old first largest number becomes the second largest number at the 2nd hour if that number is If the first If the first If the first number happens to be larger than the second number, number happens to be larger than the second number, then we just assign it to the then we just assign it to the second number. What does that mean? That is, if second number. What does that mean? That is, if the example was like before, what happened from the the example was like before, what happened from the beginning to the end and now? beginning to the end and now? beginning to the end and now? these two numbers are both taken. Then we start with the number 3. The number 3 will be larger than the number. The first number is like that. Both of them will be sent back with million one million one million one I am the value of two people does not I am the value of two people does not change only the value of the first number will be change only the value of the first number will be replaced by 3 That means the biggest value is replaced by 3 That means the biggest value is here i here i from now on Lara's first mind will be from now on Lara's first mind will be three and will grasp the beginning three and will grasp the beginning three and will grasp the beginning element the second week that it is two that is two it is still small The First number the flight number Well it will jump down this is two still bigger than the car this will claustrum Why is that because at this time the remaining car Why is that because at this time the remaining car Why is that because at this time the remaining car will need this number it is currently not will need this number it is currently not One So that two will be added here One So that two will be added here to become the second largest city in to become the second largest city in Yeah ok Now we come to my name and Yeah ok Now we come to my name and this one we this one we this one we is the second largest number and according to the observation we just made, if the first largest number is twice as large as the second number, it is a Ok the first amor is greater than Ok the first amor is greater than Ok the first amor is greater than or equal to the same Number 2 times greater than equal or equal to the same Number 2 times greater than equal to twice then we will return the to twice then we will return the Index of the brilliant treb speaker like so Here Index of the brilliant treb speaker like so Here we need to print more of that, we need to print more of that, please type again. please type again. please type again. update and find the largest number, we will update this modification. Yes, let's leanmax Max. If that's okay, then we'll go. Name - 1 ok shirt for women Smith for women Smith Yes ok Yes ok Yes ok Yes Ok But when it comes to muscle numbers and related fields will be placed below the description from some articles here. It will be simple for us to relax working working working overtime Dat with lisp the next days overtime Dat with lisp the next days we will come back to Kris Ok we will come back to Kris Ok Now you have one left remember to like Now you have one left remember to like and subcrise and notify so you can and subcrise and notify so you can know when I do it | 2024-03-21 12:26:04 | 747 | Daily LeetCode Challenge [25]: 747. Largest Number At Least Twice of Others. (#array) |
|
IJd64L5RUBY | 200 Hello friends, welcome to the new video of Tech and today we have problem and today we have problem number 22 Edison, today is Banswara day, our number 22 Edison, today is Banswara day, our minimum is Window 7 Singh, it is okay, so I have made the minimum is Window 7 Singh, it is okay, so I have made the work easy in this, it work easy in this, it shows you that this problem is a high shows you that this problem is a high level problem. level problem. level problem. in it, it will take some time to explain to you, so we have a string as you can see, whether there is soil or dust in it or not, where ABC is visible then you have to enter my mobile number, so look at The The The training is looking patient, it could have been training is looking patient, it could have been transferred but it is not the minimum. After transferred but it is not the minimum. After visiting the minimum, we came to know that the BANC visiting the minimum, we came to know that the BANC is the minimum and even though there are pomegranates in between, is the minimum and even though there are pomegranates in between, but if you definitely see my ABC, then this will be but if you definitely see my ABC, then this will be our output, okay. our output, okay. our output, okay. that according to Idris, please return the screen, we will make a case for the peace friend, a little bit that this is a unique answer, you know it and the highest quantity is fine from the sequence of the country, Listen to the explanation, okay, Listen to the explanation, okay, Listen to the explanation, okay, after that we will talk about coding and it is after that we will talk about coding and it is very easy, so let us keep it as SDO and very easy, so let us keep it as SDO and today I have a pencil so that when I want to highlight, I today I have a pencil so that when I want to highlight, I can do this whenever can do this whenever I want, so in this case, this I want, so in this case, this I want, so in this case, this our ABC is and you have given our NC, I told that ABCD, we don't like this also where we are getting C and we are getting this shortest length, we have taken the end unmukt, so now what Okay, now it Okay, now it Okay, now it looks like a jar of installation, what do we do, looks like a jar of installation, what do we do, actually we are checking the green first, actually we are checking the green first, we will wash the small one, then we will go, we will take we will wash the small one, then we will go, we will take one nando here and we will take these days, then we will one nando here and we will take these days, then we will take all four, then we will check. take all four, then we will check. take all four, then we will check. also having an affair. If you want to know directly and it is definitely there are only three, it is okay to collide with two. I will update it first. For whom do I Is it Is it Is it right and in the second season, account and three thugs, this is to right and in the second season, account and three thugs, this is to comment, we should know the account, the comment, we should know the account, the fame in the team, tell us fame in the team, tell us how much is the ABC benefit, there are three, at the moment we how much is the ABC benefit, there are three, at the moment we know that what you have is ABC, the content has to be know that what you have is ABC, the content has to be made, okay. made, okay. made, okay. hair which I have taken, there is a cafe like account in its window right now, 0 as we move ahead, our value update will come down on this house map that we have two things because these which are already Required Already, Required Already, Required Already, how much is required, how much is the requirement, it how much is required, how much is the requirement, it gives the latest information, wait, this is the team, gives the latest information, wait, this is the team, 10 written separately, or who knows, it is 10 written separately, or who knows, it is drinking, here one character drinking, here one character account will be increased, so what do we have to do, account will be increased, so what do we have to do, we will do the typing from here. we will do the typing from here. And we will put a point that by electrolyzing it will And we will put a point that by electrolyzing it will also increase the aslam. Let's get angry also increase the aslam. Let's get angry when who am I, I will tell you when who am I, I will tell you that you know we have it okay, so we have that you know we have it okay, so we have aircraft from here, it is a, now aircraft from here, it is a, now I showed a yes, which was coded by I showed a yes, which was coded by removing it from zero. removing it from zero. removing it from zero. account has not been fixed here, the identity of the person has not changed, so that you do not have to check again and again, that is why I have made it ready here, okay, so I will check till then, if I I will check whether those I will check whether those I will check whether those three nooses are mine or not, then I am ready three nooses are mine or not, then I am ready now, look, I am definitely like this, so now, look, I am definitely like this, so why check every street again and again, time has to be taken why check every street again and again, time has to be taken care of, now like even care of, now like even after the video, it has just come, so here also. after the video, it has just come, so here also. after the video, it has just come, so here also. updated it and closed it, then it is fine, it has 181 matches, 13, how can we win, if we go again in the middle, then this 2010 will go ahead, nothing happened for this, if we come to the seat, we need C, That all three have become one one, That all three have become one one, That all three have become one one, no, already and the husband is no, already and the husband is already there, that is equal to two required already there, that is equal to two required recording environment, if this is so much then it means that recording environment, if this is so much then it means that our answer will be two, it was written that the answer will be our answer will be two, it was written that the answer will be 1 1 2 3 4 5 6 6 inches. 1 1 2 3 4 5 6 6 inches. 1 1 2 3 4 5 6 6 inches. you out from her head to toe, OBC actually happened, keep in mind, if you try, tell me the minimum, what will have to be done to reach the minimum and will have to look ahead, then what do we do, we have come so far, what do we do that Let's go ahead Shankar, so let's Let's go ahead Shankar, so let's Let's go ahead Shankar, so let's remove one from our team, start one cord each remove one from our team, start one cord each and move ahead, okay, so and move ahead, okay, so moving ahead, we saw that one of them is moving ahead, we saw that one of them is already ready, it has been printed. Start this video and already ready, it has been printed. Start this video and then move ahead, then move ahead, check the SMS. check the SMS. check the SMS. wife is not coming and a time will come when I too will reach, who knows, even stuck here, this has increased to the point that I will give you very, very sorry, this is fine, it That in this we will increase the number already, whether it is That in this we will increase the number already, whether it is That in this we will increase the number already, whether it is two minutes or not, if we have to two minutes or not, if we have to increase it for different people, then neither will it work, it will be greater than equal to two, increase it for different people, then neither will it work, it will be greater than equal to two, how much can we play right now, the how much can we play right now, the reason for that is that you are our reason for that is that you are our condition, then the result is condition, then the result is condition, then the result is wherever it went again, so I am 20. This must be one time, it is not a request. According to the rules, our next length is taken equal to the already requested. I am telling you that now the length is already requested. I am telling you that now the length is already requested. I am telling you that now the length is becomes big, then at the moment it seems small compared to such a big line, if you do n't see me, then definitely with such great attention, because that's why we will start doing it, then we came there, after doing this, we have to ring this and Ours is like this or that Ours is like this or that Ours is like this or that I will tell you and these have been I will tell you and these have been revolved around this again, let us keep updating our revolved around this again, let us keep updating our answer. Okay, if our answer. Okay, if our answer is not there, then that is why the main has not answer is not there, then that is why the main has not come, come, where will the medium come from? where will the medium come from? where will the medium come from? that as Dharam Singh kept on doing, she would stop after coming to India and here it became a minimum of 8 to 12 people. We found that this also does not happen in this, Please give us 25 answers. Please give us 25 answers. Please give us 25 answers. Okay, table less, subscribe. We Okay, table less, subscribe. We cannot progress beyond this, that's why we have cannot progress beyond this, that's why we have shown it by doing it in the end. So, if you shown it by doing it in the end. So, if you want and fashionable condition, please, want and fashionable condition, please, I have made a code. This is the thing, explain that. I have made a code. This is the thing, explain that. If it is very easy then in the first and I If it is very easy then in the first and I will tell in a chapter that you have to keep this picture will tell in a chapter that you have to keep this picture in your mind, what kind of cigarette am I reaching, in your mind, what kind of cigarette am I reaching, why is it already made, that why is it already made, that every time I will also check that the every time I will also check that the festival matrix is a request, it festival matrix is a request, it is printed, so is printed, so is printed, so check all these conditions, let's go to the court here and keep this in mind, it is okay, then you must have seen the explanation in weeks, now see what I have done here, what is the actual result, if we assume that If you have MT, then make If you have MT, then make If you have MT, then make anti in retail, it is okay, he had said this case anti in retail, it is okay, he had said this case earlier, then I took whistle and earlier, then I took whistle and strip and showed you the secret, neither Hindu nor edition, strip and showed you the secret, neither Hindu nor edition, I have anti you for now and I I have anti you for now and I said for the character, see in 2015, it was said for the character, see in 2015, it was Tulsi, wasn't it? Tulsi, wasn't it? Tulsi, wasn't it? what we are seeing now is that we are keeping the value of smart. It is keeping the value of that character, so add one to the rally of the character. If the C does not get, this is the sentence of fashion. That is, if it is only a few That is, if it is only a few That is, if it is only a few then it is fine otherwise by default everything will be deposited starting from zero, otherwise this ultimate function is returning Mr. If you add one to zero then it will go and it will be Will it Will it Will it go to China or has it become a value pair? go to China or has it become a value pair? Now I have seen it in the team, Team Now I have seen it in the team, Team AB is being formed, Given AC is also being formed, so I had AB is being formed, Given AC is also being formed, so I had one already required, you are already one already required, you are already with me, then I am 0n all the others are requested. with me, then I am 0n all the others are requested. Now I have understood the length i.e. three, then I did it and Now I have understood the length i.e. three, then I did it and accepted it as one answer. Now what accepted it as one answer. Now what will be the answer, actually it will be left and right increase, will be the answer, actually it will be left and right increase, so I asked for both minus one so that the so I asked for both minus one so that the index should be outside. Second, index should be outside. Second, what is the length of this answer. I can tell him. what is the length of this answer. I can tell him. What was our answer in the beginning, What was our answer in the beginning, Jahangir, you will see, you were coming from ends to five, EMABC and length are so far behind, that is why EMABC and length are so far behind, that is why in the beginning I took length in favor of you, the in the beginning I took length in favor of you, the tumor required minimum nine and tumor required minimum nine and we answered. we answered. we answered. initially what will be on our left will be zero and right click will be added. If we run it, we will run the loop on the right and the character will be cut here too. The character will be equal to such off site S. Is So what should I do, just So what should I do, just So what should I do, just increase the value of C in its window, just like increase the value of C in its window, just like we were applying the vaccine here, the we were applying the vaccine here, the time has come with your face, there is a very time has come with your face, there is a very divine character in the character, the time has divine character in the character, the time has become its value pair, now check that in this city. become its value pair, now check that in this city. If that is a C request then it turns out to be our team too If that is a C request then it turns out to be our team too and also the account of both of them and also the account of both of them is same Gyani like mine was is same Gyani like mine was one in that one in this one too if it is so then one in that one in this one too if it is so then increase the already plus equal to one so increase the already plus equal to one so I was saying. I was saying. I was saying. covering one cord, already married is three, that is required in our required, then lunch is three, notes's AB, wow, wife's semen, then if all breed is also three, we are like this, this is What is happening is that the character is also What is happening is that the character is also What is happening is that the character is also in the city and both of them have the same account. in the city and both of them have the same account. Okay, so now we have to check boil already shell Okay, so now we have to check boil already shell required means as much as such thing if both are required means as much as such thing if both are three then check what is this and three then check what is this and - Help Lakshya I have total length. - Help Lakshya I have total length. - Help Lakshya I have total length. is a zero index, then the length is taken like this, so this time I celebrated small earthen lamp shades in phase, it will always be in the starting, so turn off the answer by voice mail. In the five star team of the district like Kumar Saini, from And And And make waves, which is Maryland, Edison, isn't it 5 make waves, which is Maryland, Edison, isn't it 5 - 06, so our length has become 6 from the answer key - 06, so our length has become 6 from the answer key and minimum balance is required, and minimum balance is required, now what will we do together now what will we do together ASW Anil Joshi's window, it has a ASW Anil Joshi's window, it has a window, it has In the school on the left, In the school on the left, In the school on the left, we will do one of them, we will we will do one of them, we will set the alarm - we will turn it off, set the alarm - we will turn it off, okay, it does this every time, I will okay, it does this every time, I will see it as bye during the day, okay, see it as bye during the day, okay, we have been lifted, right, if we put the value, we have been lifted, right, if we put the value, then then remove the floating 11. remove the floating 11. remove the floating 11. in city that if we found it like this inside the city and its value is in the window, its value in the window is less than the value of our city, what is this But if the value of left key is light then But if the value of left key is light then But if the value of left key is light then another another character will appear in this LMB in the apps. I am looking for edible in that character. What are we doing in modern account? We are reducing it. At this time the account is reducing it and we are saying this time the account is reducing it and we are saying that I found another ad in CT, s.l. that I found another ad in CT, this account tells me that if his account this account tells me that if his account is less than our city account, then is less than our city account, then what will we do now - make it already what will we do now - make it already that we cannot do plus one, that we cannot do plus one, no, plus one happens only when his no, plus one happens only when his no, plus one happens only when his are specialities, otherwise our left side will move one step ahead, what kind of separation should we tell, this dhamara will keep going on and the last hit that is going to come, hit the mail, there was a fit in the answer, there was a minus minus one inside the answer, now there should be a The value of the Pluto website will go, The value of the Pluto website will go, The value of the Pluto website will go, it will come in our last it will come in our last that BMC is from eight to whatever it is in India, it is that BMC is from eight to whatever it is in India, it is okay okay in nine to twelve eight to 12 whatever and in nine to twelve eight to 12 whatever and we will return it by taking NOC from the train we will return it by taking NOC from the train and plus the difference if and plus the difference if and plus the difference if mind that if there is no infinity left then who knows, then in such a case our answer will not be anything. This small code has already been included. I am that in the hotel in the evening. that in the hotel in the evening. that in the hotel in the evening. Edit Question: Actually, it is a new day, but sometimes one is left in the night, which means that this is the beginning of a new day, so it has to happen, see you in the next class, | 2024-03-20 11:42:35 | 76 | Minimum Window Substring - Leetcode 76 - Python |
|
OuOwshx2U70 | hello everyone welcome back to my channel so today we are going to discuss channel so today we are going to discuss another problem problem is power of two another problem problem is power of two so it's a very easy problem uh in this so it's a very easy problem uh in this problem we'll be given an integer and we problem we'll be given an integer and we need to return true if it is a power of need to return true if it is a power of two otherwise return false two otherwise return false power of 2 means that this number n can power of 2 means that this number n can be represented as 2 raised to the power be represented as 2 raised to the power x where is x where x is some integer so x where is x where x is some integer so n can be n can be n is a power of 2 n is a power of 2 so if we see so if we see if n is 1 then output will be true if n is 1 then output will be true because we can represent 1 as 2 raised because we can represent 1 as 2 raised to power 0 to power 0 if if n is 16 then it is also the output is n is 16 then it is also the output is true because 16 is 2 raised to power 4 true because 16 is 2 raised to power 4 but when we have n3 so n is no 3 is not but when we have n3 so n is no 3 is not a power of 2 a power of 2 so we will uh return false so we will uh return false so there are many ways of uh so there are many ways of uh there are many approaches for this there are many approaches for this problem so we'll see few of the problem so we'll see few of the approaches approaches so first of all let's say we have n as so first of all let's say we have n as 16 16 so so a a power of 2 will be even always and c 16 power of 2 will be even always and c 16 can be represented at as 2 raised to can be represented at as 2 raised to power 4 power 4 so what we can do is every time so what we can do is every time we can divide sixteen by two we'll get we can divide sixteen by two we'll get eight eight we divide eight by two we get four we divide 4 by 2 we get 2 again and we divide 2 by 2 we get 1 so if if the number is a power of 2 whenever we divide like we will divide it by 2 and ultimately we will get 1 so if you try doing this with let's say we have 17 if you divide it by 2 to 2 at the end you will not get 1 so if a number is power of 2 if you divide it by 2 every time we will get 1 at the end so this is one approach let's see the code for this so if you see if the number is 0 obviously it's not a power of 2 so just return false otherwise what we can do is we can run a while loop until n is not equal to 1 and divide it by every time by 2 and at a point of time if the number if the n is not divisible by 2 means it is a odd number hence it will we can return false otherwise just keep on dividing it by 2 and once this loop is finished means n has become equal to 1 so we can return true at the end so this is one approach so time complexity for this approach is o is o of n log n sorry so of log n uh log to base 2 n because every time we are dividing by 2 so the number is becoming half every time so now let's discuss another approach another approach will be a constant time approach like all the time complexity will be o of 1 let's see how so see like if we have 16 this 16 if we do a log of this 16 like log to base 2 16 so now if we we know that the answer for this will be a log 16 divided by log 2 so this will be somewhere log 2 raise to power 4 and this will be log 2 raised to the power 1 hence it will come out to be 4 right so it will be an integer now if we calculate floor of this number which of the result which we get from this that is 4 and if we calculate seal of this number 4 the result these will be equal these will be equal only only when only if this was a complete like it was if this was uh four right if it had been a decimal let's say four point something like four point five then floor will be different floor will be four if the uh if here it's four point five then floor will will be four and seal will be five say hence they will not be different so this uh we can use this thing to check whether this 16 is a power of two or not if here it would have been 17 then this answer here will be some something in decimals so if this is in decimals then floor and c will never be same right so this way we can check and this will be o of one time complexity so so this is like seal of log to base two and this is like seal of log to base two and we are doing and checking the floor also we are doing and checking the floor also so if they are equal means it is a power so if they are equal means it is a power of two so if we submit this it's getting of two so if we submit this it's getting submitted so if we submit this this is one approach and one more approach which we can see is let's say we have let's take 16 only or let's say we have four let's take a smaller number we have four now we know that four will be a power of two only if it has only one in its binary representation like that what that what does that mean so let's say for uh force binary representation is listener so now uh a number whose power of two will have only one obviously in its binary representation only one one so we can check how many set bits are there one is the set bit zero is the inside bit so we can count how many set bits are there in the binary representation of 4 and if the number of set bits if the count of the set bits is equal to 1 hence it's a power of 2 hence it's a power of 2 so if you see like if you say 32 32 is 2 raised to the power five and it all if you re if you see the binary representation of 32 it also has one one in its binary representation hence it's a power of two so if you want to count the count the set bits in a binary representation of a number there is an algorithm called carnegan's algorithm you can so you can first of all learn that algorithm using that you can find out how many count said how many set bits are there and once you know the number of set bits you can check if the account of set bits is one hence this number is a power of two so this is one approach one more approach which we can also use uh on that also we'll be doing bit manipulation so let's say we have four so the binary representation of four is zero one zero zero and let's say we take this is if this is n we will also take n minus 1 is binary representation so that will be 4 minus 1 3 so 3's binary representation is 0 0 1 1 so now if you do and if you do end of these what we will get we will get zero zero zero means all zero is we'll get so this is also our approach you can use that if you need to check let's say you need to check 16 is a power of 2 or not you will see the binary representation of 16 and you will you will see you will see the binary representation of 15 take and of both and if you get 0 as a result it means that 16 is a power of 2 that means if we write it like this that means if we write it like this let's say let's say n n we n and we need to do n minus 1 we n and we need to do n minus 1 so if this is if this comes out to be 0 so if this is if this comes out to be 0 0 means false so if this is true means 0 means false so if this is true means what we'll do is what we'll do is see this see this this will get a 0 this will get a 0 so if 0 naught of 0 means so if 0 naught of 0 means 1 hence true so if this is true 1 hence true so if this is true means this 4 is a power of 2 means this 4 is a power of 2 in order to in order to like understand more let's take another like understand more let's take another example let's say we have 6 example let's say we have 6 so binary representation of 6 is 0 1 0 so binary representation of 6 is 0 1 0 and if we take a this is n so n minus 1 and if we take a this is n so n minus 1 will be 5 will be 5 so 5's binary representation will be 0 1 so 5's binary representation will be 0 1 0 1 so if you do end of these you will 0 1 so if you do end of these you will not get 0 you will get this will be 0 not get 0 you will get this will be 0 this will be 0 this will be 1 and this this will be 0 this will be 1 and this will be 0. so you you are not getting 0 will be 0. so you you are not getting 0 in this case in this case so if you are not getting 0 this means so if you are not getting 0 this means that 6 is not a power of 2 that 6 is not a power of 2 6 is not a power of 2 6 is not a power of 2 so this approach also we can use so this so this approach also we can use so this is also of is also of a 1 a 1 a time complexity a time complexity so see so see we can use this also so if n is greater we can use this also so if n is greater than 0 than 0 and if this thing is true and if this thing is true means means n is a power of 2 n is a power of 2 if you submit this if you submit this it's also getting accepted it's also getting accepted so we discussed four approaches in this so we discussed four approaches in this video so i hope this was helpful please video so i hope this was helpful please like and subscribe and i'll see in the like and subscribe and i'll see in the next video thank you | 2024-03-22 11:15:12 | 231 | Power of two 🔥 | Leetcode 231 | Bit Manipulation | 4 approaches |
|
UvV9kLuh4R0 | hello guys mike decoder here so i decided to decided to make some neat core problems because i'm make some neat core problems because i'm running off ideas running off ideas uh if you have any ideas for future uh if you have any ideas for future videos leave it in the comments videos leave it in the comments so let us see this problem given integer so let us see this problem given integer array numbers in which exactly two array numbers in which exactly two elements appear only once and all the elements appear only once and all the other elements appear exactly twice other elements appear exactly twice find the two elements that appear only find the two elements that appear only once you can return the answer in order once you can return the answer in order you must write an algorithm that runs in you must write an algorithm that runs in linear runtime capacity linear runtime capacity and uses only constant extra space so and uses only constant extra space so linear linear complexity this means that i want to complexity this means that i want to loop loop through uh the the list so for i through uh the the list so for i in list in nums for example i'm going to in list in nums for example i'm going to say say if nums.count i if nums.count i is equals to 1 this means there is no is equals to 1 this means there is no repetition for this repetition for this this means that's our answer right so i this means that's our answer right so i can make here like an output list and i'm going to say here if it's only repeated once this means i want to output it so i'm going to append it to my list called output noms will count so i'm gonna append i noms will count so i'm gonna append i and then here i return the output return output and let me run this code and it should work yeah it works great now another approach can be now this is like a more complex approach if you may say let us loop through the indexes of this list okay so this is 0 1 2 three four five i'm gonna say my first index is zero right so if i'm in index zero i'm gonna say if this index which is one uh is inside this list then it is repeated right so can't i say if nums i in nums i plus 1 till the end of the list if this is inside this then this is repeated isn't that logically correct yes if it's repeated occurrences this list is going to keep occurrences this list is going to keep track of every occurrence track of every occurrence made before so occurrences dot append made before so occurrences dot append nums i now i will keep track nums i now i will keep track of all the numbers that are repeated if of all the numbers that are repeated if i don't do this i don't do this i will run into a problem you see i'm i will run into a problem you see i'm saying here saying here if this number is repeated in the list if this number is repeated in the list in front of it right in front of it right so 1 is repeated here but is this one so 1 is repeated here but is this one repeated here it's not so the program repeated here it's not so the program will treat this will treat this as if it's not repeated if i just do as if it's not repeated if i just do this this but now that i'm appending it to but now that i'm appending it to occurrences i'm going to say here occurrences i'm going to say here if this number is not repeated if this number is not repeated in the list in front of it then make in the list in front of it then make sure sure then make sure that this number okay if it doesn't occurrences then it's okay if it doesn't occurrences then it's a unique number a unique number then append it dotted then append it dotted i'll put it append numsai i'll put it append numsai and here we will return we have a problem global name currencies we have a problem global name currencies is not defined is not defined i closed it incorrectly there we go i closed it incorrectly there we go this should work now run code this should work now run code there we go accept it so this is uh there we go accept it so this is uh this problem guys hopefully you enjoyed this problem guys hopefully you enjoyed and i'll i'll keep doing some of these and i'll i'll keep doing some of these videos lit code videos lit code this was a medium problem i will do this was a medium problem i will do heart problems in the next videos heart problems in the next videos so hope you guys enjoyed i'll see you in so hope you guys enjoyed i'll see you in the next one | 2024-03-22 12:17:41 | 260 | Leetcode problem 260 single number III solution | find the 2 unique numbers in a list | python |
|
9m0Ph79aPZY | welcome to march's leeco challenge today's problem is flip binary tree to today's problem is flip binary tree to match match pre-order traversal you're given the pre-order traversal you're given the root of a binary tree with n nodes where root of a binary tree with n nodes where each node is uniquely assigned a value each node is uniquely assigned a value from one to n from one to n you're also given a sequence of n values you're also given a sequence of n values voyage which is the desired voyage which is the desired pre-order traversal of the binary tree pre-order traversal of the binary tree pre-order traversal starts at the node pre-order traversal starts at the node and then goes left right and then goes left right any node in the binary tree can be any node in the binary tree can be flipped by swapping its flipped by swapping its left and right subtrees so for example left and right subtrees so for example at node one we can flip two and three to at node one we can flip two and three to be three and two if we'd like be three and two if we'd like uh see if we can do that to match our uh see if we can do that to match our path and voyage now we wanna return a path and voyage now we wanna return a list of all the values of list of all the values of flipped nodes and if we can't find one flipped nodes and if we can't find one then we'll have to return a list of then we'll have to return a list of negative one negative one so we already know that we're going to so we already know that we're going to be doing it that first search or breadth be doing it that first search or breadth first search first search depending on whichever one you find more depending on whichever one you find more intuitive intuitive i'm going to go with def that first i'm going to go with def that first search this problem is very difficult to search this problem is very difficult to tell the truth and tell the truth and the reason for that is we need to figure the reason for that is we need to figure out if out if we can actually do this pre-order we can actually do this pre-order traversal traversal at every node we're going to have to be at every node we're going to have to be going down a single path going down a single path but it's like we have to but it's like we have to figure out if we want to go right left figure out if we want to go right left or left right or if that's not even or left right or if that's not even possible so possible so inside of some sort of global variable i'm going to make a list that keeps track of all the nodes that we've traversed if we found that we couldn't find one inside our condition i'm going to put a none inside of that list and that way we can track that and say hey you know in our path we couldn't find a value to match our path so that's going to mean we have to return a negative one we'll also have to keep track of the direction that we can go uh if we can go left right then we don't need to change the direction but if we have to go right left i'm going to put in some sort of variable that says go right left instead and keep track of that inside of our output so the very first thing we want to do is create some self variables i'm going to call this path and i'm going to call this current this one's going to be a list of all the nodes that we had to swap and this one's just going to be an index number of where we are currently in our voyage so now we need our depth first search and we're going to pass in the node the very first thing if not node or let's say like so voyage if self talk cur equals like so voyage if self talk cur equals the length of voyage the length of voyage that means our algorithm is over so we that means our algorithm is over so we can just return okay the second thing we want to check is to see if this node is equal to the voyage inside what we are in current because if it's not then that also means we need to end our algorithm here so let's see if does not equal node.value then again we'll return but we'll also add to our self.path a none and this will keep track of later because if this was the case we have to say uh we couldn't find one so we'll have to return negative one now otherwise what we'll do is increase our current pointer by one because we have found that this node matches the one side of voyage and we'll also keep track of the direction that we want to go so i'll call this direction and this will start with just left to right which would be one so the first thing is do we need to swap well if we need to swap we can say check our no if we have a no dot left and no dot left dot value does not equal if this is the case then we know we need if this is the case then we know we need to swap so to swap so in our path we'll say append this no dot in our path we'll say append this no dot value value and we will switch our direction to and we will switch our direction to equal negative one equal negative one i'll show you why we did this here the i'll show you why we did this here the reason i did this reason i did this is now we need to continue down our is now we need to continue down our pre-order traversal right but which pre-order traversal right but which order do we go do we go left or right or order do we go do we go left or right or right to left right to left and we'll say for child can make a list and we'll say for child can make a list no dot left no dot left and no dot right and no dot right if we found that we have to go the other if we found that we have to go the other way or we have to at least try the other way or we have to at least try the other way way then we'll just this direction thing then we'll just this direction thing here we'll here we'll make sure to tear that and we just call make sure to tear that and we just call our depth first search again our depth first search again with the node versus the child now we need to call our depth for search at the root and really it really depends here we either return the self.path all the lists of node values that we've swapped or if there's a none in the self.path or return so let's see if this works i believe so let's see if this works i believe this should return negative one this should return negative one does and go and submit that and there we go accept it so this actually ends up becoming of n because we only traverse we do traverse every node but we're only going to do it one time depending on which path we can take and it'll stop early if we find that we haven't been able to find one and we'll return negative one if none is inside this path so i'd love to say that i came up with a solution on my own i did not although my approach was very similar it was taking a little bit too long for me to get all the edge cases so i had to look it up but um my approach would have been similar i think i would have eventually got it i wish i had more time to go into like a deep dive here because this actually is a more difficult problem than it kind of initially seems so i hope this helps thanks for watching my channel remember do not trust me | 2024-03-25 14:10:33 | 971 | Leetcode - Flip Binary Tree To Match Preorder Traversal (Python) |
|
aEYqmUC5k1k | hey hey everybody this is larry this is august 27th 27th day of the august august 27th 27th day of the august nicole day challenge nicole day challenge congrats to yourself if you've made it congrats to yourself if you've made it this far you're almost to the end just a this far you're almost to the end just a couple more days uh hit the like button couple more days uh hit the like button hit the subscribe button join me on hit the subscribe button join me on discord discord chat about this farm out of problems chat about this farm out of problems okay longest uncommon subsequence too okay longest uncommon subsequence too given the way of strings given the way of strings just arrows return the length of the just arrows return the length of the longest uncommon subsequence between longest uncommon subsequence between them them what is the longest uncommon subsequence what is the longest uncommon subsequence negative one ever done negative one ever done subsequent subsequent an uncommon subsequence between a way of an uncommon subsequence between a way of string is a string that is a subsequence string is a string that is a subsequence of one string but not the others of one string but not the others a subsequence of a string s is a string a subsequence of a string s is a string that can be obtained by that can be obtained by deleting any number of characters from s what does that mean i still have to read what does that mean i still have to read this this uh uh longest uncommon subsequence can you give an example okay i guess this is this is these are too many words these are too many words and to know what they're really asking and to know what they're really asking for okay for okay i usually saw this live so it's a little i usually saw this live so it's a little bit slow just watch it on a faster speed bit slow just watch it on a faster speed let me know what you feel um let me know what you feel um and apparently this is one of the slower and apparently this is one of the slower ones because reading is hard and i just ones because reading is hard and i just woke up woke up okay subsequent the longest uncommon subsequence between what does that mean what does that mean it's a string that is the subsequence of it's a string that is the subsequence of one string but not the others one string but not the others isn't that just the longest what is the constraints oh okay so again the strings are very low so we can force it but it seems like it would just be the longest string right as well you you can do the long string and then you do a naive check just to see that if the longest string is not identical to another string and then you kind of go down the list that way yeah i think that's right uh this is such a i think that's right uh this is such a reading problem that i'm not sure um but reading problem that i'm not sure um but given that each string given that each string or there are only 50 strings and there's or there are only 50 strings and there's only 10 in the only 10 in the longest string i'm just going to do it longest string i'm just going to do it in the brute force way in the brute force way the first thing to notice is that we can the first thing to notice is that we can sort by sort by um um the length of the string um and then and then you can probably do something smarter you can probably do something smarter about this with about this with with with i don't know anything but like i said i don't know anything but like i said each character each string only has 10 each character each string only has 10 characters so i'm just going to do it characters so i'm just going to do it naively naively for for word so at the very end which are negative i mean they have to be identical right i mean they have to be identical right for it to be not to return a negative for it to be not to return a negative one one in this case in this case so let's just say good is equal to true so let's just say good is equal to true i mean i think in theory you can do i mean i think in theory you can do something like forward two something like forward two um hmm maybe i could um hmm maybe i could handle this a little bit better uh let's just call it inj i've been wait i've been calling everything index these days kind of i don't know if that's easier to read um what's it called range of from i plus one to n where n is the length of strings word sub i is equal to sub j word sub i is equal to sub j then good is equal to force and the then good is equal to force and the reason is because if reason is because if so i so i by definition has to be by definition has to be longer than or longer or equal to j longer than or longer or equal to j right right because because and if and if if the length of word j is smaller than if the length of word j is smaller than i then obviously it's not going to be i then obviously it's not going to be inside it inside it um um [Music] now i think that doesn't i mean it makes sense going that way but i think you still have to check jay with his smaller eyes so i think this is this logic is reasonable but not not this is still good if this is still good if no good no good no not good no not good no good no good uh uh [Music] [Music] not uncommon not uncommon if uncommon so our candidate is currently i and we're seeing to see if word i lives within word j uh if this is true then good is equal to false we can break if good then we return the length of word all right then we'll do just do this uncommon thing um what's it going i forget which hmm i guess it's not really a needle in a haysack but let's just call it uh x y uh too lazy naming things is hard and then now we can just do index x zero zero and x y zero zero maybe oh yeah we can just assume that the oh yeah we can just assume that the length of word sub j is greater than or length of word sub j is greater than or equal to length of equal to length of oops oops uh length of word sub i otherwise yeah otherwise just smaller than you can't really fit into it think of y think of y oh no length of x i y is less than length of y i y is less than length of y [Music] [Music] and hmm this is just a two-pointer thing but i'm just yeah okay yeah and uh let's see what am i doing and uh let's see what am i doing i think it's just my in my wearable i think it's just my in my wearable names are very terrible right now to be names are very terrible right now to be honest which is why um i think this is roughly right i think this is roughly right my coating is very terrible this morning my coating is very terrible this morning i don't know if this is right though um i don't know if this is right though um because this is so awkward now dad get those signs well i think this is one this is true and this is four troops because this is true we're able to get to the end of the other string oh wait no no we get to the other string then i think i had to think about how i'm um um so if you you're getting through both so if you you're getting through both strings that means that they're not strings that means that they're not in loop in loop so i think this is good this should be i think my my logic is just good uh foul to go to true to go to true if if not found okay i think this is good string in text string in text how can this be our folder uh whoops okay it's because i never used this stir spring how did that even won the first time let's see let's see if it goes to the end and they don't care that's just true otherwise sorry friends i think i feel like the sorry friends i think i feel like the logic is easy but i'm logic is easy but i'm well i mean easier this is such a weird well i mean easier this is such a weird problem in general but this part i problem in general but this part i should not have any trouble with should not have any trouble with oh oh okay that's just dumb okay that's just dumb um if i it's not your j and this okay i should yeah because i i switched it from i plus one to n and i didn't think about i just didn't think it through uh okay let's give it a go i don't know if this is right because this reading of this problem is just so such a weird problem to be frank but uh okay seems like it's good so i'm happy about that um you can do some optimizations for sure for example i think you can and write this in a way that is much smarter um but but given that n is 50 and um l is 10 this is going to be fast enough and you don't even need to sort i think to be honest i just sorted it [Music] and the way i sorted you can actually early terminate if the length is smaller but we i didn't actually implement that so yeah um what is the complexity this is o n this is o n so this is n square um at least and uncommon is also of l so this is going to be n square l uh o of n squared times l and in terms of space we don't use any extra space i guess we sort so which we don't really use so you can remove this line and pretend this line doesn't exist and then this space is yeah yeah i guess that's all i have i don't know i guess that's all i have i don't know this is a very weird problem i think this is a very weird problem i think it's just one of those real logic ones i it's just one of those real logic ones i can imagine a lot of people are not fans can imagine a lot of people are not fans of this this one um i think it's just of this this one um i think it's just the wording is just so i don't know the wording is just so i don't know maybe i just woke up too so i don't know maybe i just woke up too so i don't know but uh but yeah let me know what you but uh but yeah let me know what you think because this is definitely a weird think because this is definitely a weird one this is one of those like one this is one of those like tricky tricky cutesy silly problems uh i will see you cutesy silly problems uh i will see you later take care later take care uh stay good stay healthy have a great uh stay good stay healthy have a great weekend i'll see you later and degree weekend i'll see you later and degree mental health mental health bye-bye | 2024-03-22 16:39:46 | 522 | 522. Longest Uncommon Subsequence II - Day 27/31 Leetcode August Challenge |
|
xzLos1OJwo8 | hello everyone welcome back to cooling Champs in today's video we are going to Champs in today's video we are going to be solving the problem gas station so be solving the problem gas station so let us first start by understanding the let us first start by understanding the problem statement given there are n gas problem statement given there are n gas stations along a circular route where stations along a circular route where the amount of gas at the Earth gas the amount of gas at the Earth gas station is gas of I you have a car with station is gas of I you have a car with unlimited gas tank and it costs cost of unlimited gas tank and it costs cost of Eye of gas to travel from ith gas Eye of gas to travel from ith gas station to its next gas station I plus station to its next gas station I plus one the station you begin the journey one the station you begin the journey with an empty tank at one of the gas with an empty tank at one of the gas stations stations given two integer arrays gas and cost given two integer arrays gas and cost return the starting gas stations index return the starting gas stations index if you can travel along the circuit once if you can travel along the circuit once in clockwise Direction otherwise return in clockwise Direction otherwise return -1 if there exist a solution it is -1 if there exist a solution it is guaranteed to be unique guaranteed to be unique so the Crux of the problem is we are so the Crux of the problem is we are given with two integer arrays gas and given with two integer arrays gas and cost gas is nothing but the amount of cost gas is nothing but the amount of gas is provided to us when we reach a gas is provided to us when we reach a gas station and the cost is nothing but gas station and the cost is nothing but the the cost or the gas will be required the the cost or the gas will be required to move from one gas station to another to move from one gas station to another and we have to find a gas station such and we have to find a gas station such that if we start at that gas station we that if we start at that gas station we will be able to uh circuit back to that will be able to uh circuit back to that gas station gas station um it is guaranteed there is only one um it is guaranteed there is only one such gas station and if we are not able such gas station and if we are not able to find such gas station we have to to find such gas station we have to return minus one return minus one so let us understand by looking at the so let us understand by looking at the examples so let me share the Whiteboard and now in the example one we are we are given with the gas one two three four and five cost areas three four five one two so let us start from the zeroth gas station so at zero at gas station we initially fill up one one gas point and then we require three gas points to move to the next station uh the total will be minus two uh since there is not enough cash to move to one station from zeroth station so we do not consider zero as our answer and then we move to the first station let us move to the first station initially at first station we fill up two points and then we require Four Points to go to next station since we do not have enough gas we cannot reach from 1 to Second gas station so one cannot be our answer and let us start it second gas station at second gas station initially we fill three gas points and we require 5 gas points to move to the next station so um we are here also we are short in short short in gas so we don't have enough gas to move to third gas station from second gas station so second gas station cannot be our answer now let's come to third gas station in third gas station initially we fill four gas points and we require one gas point to move to the next station so since we have enough gas points to move to the next station we go to Fourth station with three gas points and now we fill up 5 gas points and we require two gas points to move to the next position which means 8 minus to six so here we still have six gas points um so three will be our answer so from 6 here again let's see six from six uh here from uh for 0 to 1 we require three gas points so six minus three will be three and again here for a 6 minus 4 okay so this will be so this will be we have uh six points at zero and at we have uh six points at zero and at zero we require how many gas points zero we require how many gas points three gas point six minus three will be three gas point six minus three will be 3 and we fill up one gas point so plus 3 and we fill up one gas point so plus one equal to four we move here with four one equal to four we move here with four gas points gas points so 4 minus we require 4 gas points so 4 minus we require 4 gas points um um to reach next gas station and we fill up to reach next gas station and we fill up two two so we still have two gas points left so so we still have two gas points left so we come here with two gas points and at we come here with two gas points and at two we fill up three gas points two we fill up three gas points and we we require five gas points to and we we require five gas points to move to next gas station so 5 minus five move to next gas station so 5 minus five uh we will have zero when we reach 3 so uh we will have zero when we reach 3 so we we are able to Circuit back to three we we are able to Circuit back to three since so that three will be our answer since so that three will be our answer and let us come to the second example and let us come to the second example here so in second example if You observe we have gas 2 3 4 and cost as cost areas three four three so what is the total gas we have 2 plus 3 plus 4 equal to 9 and what is the total cost we have 3 plus 4 plus 3. so here if we observe total gas and this is total cost total gas is less than total cost so uh the gas we have is less than the gas we need so we will not be able to Circuit back uh from whatever gas station we will start we will not be able to end up at the gas station because we don't have enough gaps in the first place so we return -1 in this case um so now that we have understood the problem let us see how we can solve the problem so the name or the Brute Force way of solving the problem would be uh what we have did here right I hope we start at each gas station and we started in gas station and check if we can look back or circuit back to the gas station uh what will be the time complexity of this approach we start at each gas station we Loop through all the gas stations so it will be o of n Square so the name or the Brute Force way of solving the problem is to start at each station and check circuit if we can circuit back or not this problem uh this approach will be of N squared but can we optimize this approach let us see uh let us take another example let's say we let's say we can let's say we can I reach from a gas station to B gas I reach from a gas station to B gas station and big gas station to see gas station and big gas station to see gas station but we cannot reach from seed station but we cannot reach from seed gas station to leave the air station gas station to leave the air station so what we can observe here in the Brute so what we can observe here in the Brute Force way what we do if we fail so a we Force way what we do if we fail so a we do not consider a then we move to B and do not consider a then we move to B and we again check if we can reach we can we again check if we can reach we can circuit from B to B circuit from B to B but if we observe uh let's say uh but if we observe uh let's say uh we fail at C to D and we again started B we fail at C to D and we again started B uh what is here uh if we uh what is here uh if we we go from A to B then we know we are we go from A to B then we know we are carrying some positive or zero gas to B carrying some positive or zero gas to B since we are going from A to B we know since we are going from A to B we know we are carrying some positive or zero we are carrying some positive or zero gas to B so with this positive or zero gas to B so with this positive or zero gas we are not able to reach from B to D gas we are not able to reach from B to D so we are saying we cannot go from C to so we are saying we cannot go from C to D so we are not going from B to d as D so we are not going from B to d as well well so if we cannot go from a to d we can so if we cannot go from a to d we can say that we also cannot go from B to D say that we also cannot go from B to D and C to d as well because we carry some and C to d as well because we carry some positive or zero gas to go from A to B positive or zero gas to go from A to B with this positive or zero gas only we with this positive or zero gas only we are not able to go from B to C and C to are not able to go from B to C and C to d c to d right c2d we cannot go from d c to d right c2d we cannot go from this positive or with carrying this this positive or with carrying this positive or zero gas so without this positive or zero gas so without this positive or zero gas also we will not be positive or zero gas also we will not be able to go from C to D hence we can say able to go from C to D hence we can say if we cannot go from B to D we cannot go if we cannot go from B to D we cannot go from a sorry we cannot go from a to d from a sorry we cannot go from a to d then we then we can say we cannot go then we then we can say we cannot go from B to D and C to D so this is the from B to D and C to D so this is the catch in this problem catch in this problem so what we can say now if we fail at C so what we can say now if we fail at C to D what we say we start from D we do to D what we say we start from D we do not consider B and C as well we start not consider B and C as well we start from d and we then check if we can go from d and we then check if we can go from D to e and from D to e and if we can go from D to a then D will be if we can go from D to a then D will be our answer if if we cannot go from D to our answer if if we cannot go from D to e then e will be our answer because here e then e will be our answer because here are here also if we can go from D to e are here also if we can go from D to e we carry some positive or zero value so we carry some positive or zero value so with this positive or zero value we with this positive or zero value we should be able to Circuit a from E to A should be able to Circuit a from E to A A to B and B to C if this will if we A to B and B to C if this will if we cannot go from here to here then without cannot go from here to here then without this positive or zero value also we this positive or zero value also we cannot go from each way since we know cannot go from each way since we know that we will have if the solution is that we will have if the solution is present we will have a unique solution present we will have a unique solution so it will be either D or E so if we can so it will be either D or E so if we can go from D to e it will be D or else it go from D to e it will be D or else it will be e will be e so this is the approach I hope you so this is the approach I hope you understood the intuition behind the understood the intuition behind the solution so let us now code it up so firstly we uh so let us first take how many gas stations we have yes dot length and then what we have to check if check if we can uh so cute we can complete a circuit so for that we have to check total gas let's compute the total gas and total cost so first in time equal to 0 I less than n I plus plus and total gas plus equal to gas of I and totally cost of course plus equal to cos plus I so now we check this total gas is less than Total Core total cost in this case we know we cannot circuit back so we return -1 now we know we can so cute we can complete the circuit now what we do we have a runny examine gas value and we also should have the starting position this will be our result as well so now we have been within track you and we now and we now um what we do here we increment the gas um what we do here we increment the gas so what will be the gas now the gas will so what will be the gas now the gas will be we add the gas and we subtract the be we add the gas and we subtract the cost and now we have to check if running gas of I is sorry the running gas image so the running gas is less than less than zero X less than zero uh we know we cannot um start from this position so we update the starting position to be and now and now we finally return the starting position we finally return the starting position let us run the code and see if passes let us run the code and see if passes all the test cases okay we are getting the output 4 and we want so where do we do wrong yes here we have to reset the gas value whenever we know we have less gas value we have to resort and we have to update the so it got access it got accepted for the so it got access it got accepted for the sample this let us submit it it passes all the test cases let us look at the time and space complexity since we have we are iterating over all the gas stations once the time complexity the time complexity of the optimized approach will be of an and since we are not using any external space we are only using the constant variables the space complexity will be o of 1. um so in brief first we are checking if we can circuit back or not uh how we are checking that so total we are calculating the total gas and total cost if total gas is less than total cost we cannot circuit back uh so we return minus one and if we can circuit then we are calculating running gas we are keeping track of running gas and starting position we iterate over each cast station and we keep track of the running gas if running gas gets less than zero then we are presetting the running gas and updating the starting position will because we know if we are not able to go from the starting position to certain position we cannot go from the middle positions as well so we update the starting position to bi plus 1 and finally we return the starting position so I hope you have understood today's problem if you did understood make sure you like this video and if you have any doubts feel free to comment down below I will try to answer as many comments as possible and do subscribe to the channel for more daily | 2024-03-21 12:04:34 | 134 | 134. Gas Station #leetcode #greedy |
|
L0lEHHe_cjA | Hello Hello everyone today test the camera list number 1234 problem solved I know the number 1234 problem solved I know the problem is that the account is ripped from the account problem is that the account is ripped from the account so the problem was first a brother sister so the problem was first a brother sister brother brother that the commission said to make active directory that the commission said to make active directory like they loot the person dishoom full feel good like they loot the person dishoom full feel good condition The second conditioner bala se ke The second conditioner bala se ke per no dj more domestic tha ke which per no dj more domestic tha ke which most tomato follow sapoch unity ke ka most tomato follow sapoch unity ke ka intake bala se place nodal left side whatever na ho intake bala se place nodal left side whatever na ho praise loota hai be tu * rupees praise loota hai be tu * rupees class 1o class 1o Maa Karma removed the market were Detective Maa Karma removed the market were Detective Lal Lal Lal tayori le factory tha ke left notification nodal ministry 299 two in tracks plus one 106 fruit one Sharma ne khoon yeh first hamar rahalu salman ko to hum 10 case from his towel case from his towel come to show the number in condition come to show the number in condition come to show the number in condition di thing notice was spread ki aven air right side Chaudhary Nahid Khan right Jyoti ko Sarthak hai tar Hello abe tu in two Ravana's banner and China Bullet - Vande has replaced Guava from Amazon. I should immediately visit the portal of the temple. Apart from tomatoes, there is energy thing in it. It had noise protector failure - Wankhede tension ban. With the help of Cheetah Guava, 9600 kilos of Compare with Compare with Compare with whole 100 compare according to Goregaon, whole 100 compare according to Goregaon, Sita by the way, this is the treat loop, Sita by the way, this is the treat loop, tractor side, neither side, left side, but do not tractor side, neither side, left side, but do not forget the locks, forget the locks, so that the okay, so HE file is okay, so HE file is not android, Shravan is foggy right side, this foggy right side, this person's Play list ko bajao ko tawe ke ghar mandawat se to hum raghwani ke aur planets se paise next hamaraaj awadhi translation awadhi a routine sa back hamara balam ke khandwa through to the top o mein taale routine mango to hum paise one ok Na Taale Na Taale Na Taale Sector-132 In Two Sector-132 In Two Vice President's Vice President's swollen silent exam on the pan is more rough input which swollen silent exam on the pan is more rough input which gives pleasure only to see Hey Mohammed Rafi Daya Se gives pleasure only to see Hey Mohammed Rafi Daya Se Bigg Boss Do Bigg Boss Do not forget to subscribe Subscribe Problem was solved 2010 Ludhiana See the example was that our Camera Original Camera Original Camera Original Chanakya Niti Find Chanakya Niti Find Element Wants Air MP3 Towards So Finally Man Contractor Sweet And So Finally Man Contractor Sweet And Ludicrous Now Them Ludicrous Now Them Beetroot Path To An Extent Our Channel That Were Illegally Set Root Neelam And Samra Amar Twitter Were Illegally Set Root Neelam And Samra Amar Twitter Before America A I stayed with the rich, router Meiyappan Pathan and the keepers of Ulta - 10 ki end Khane Hindu bola se auspicious initial state ad Shekhawat Saheb looted money from the den of Hindu lions days 2012 write something, number 90 is on quora or else this marking is The channel came that what has become of The channel came that what has become of The channel came that what has become of this relationship, they were made to this relationship, they were made to run fast, actor function, quality run fast, actor function, quality products, tractors, products, tractors, Amitabh Pir Amitabh Pir and and subscribe, MP, name them, it was the fact that when there is uniformity in ash root without medium from outside, if it is a big religion. Which regular second Which regular second ODI live on ODI live on I college picture talk function we I college picture talk function we made like they get high fever moisture sky kuri made like they get high fever moisture sky kuri off function turn name giving return with one finger to off function turn name giving return with one finger to bona fide sea tower senior actor shri bona fide sea tower senior actor shri rudra morning hai handed over to handed over to handed over to is no dizziness in Pratham, when the day sets, Pandey brother, get Taliban done for us, we auditioned for Lid Ko 2019's 2019's Jo Root Dot Loop 99 Luta De Hai Luta De Hai Tu In Two X Plus One by Dhir Tanwar and Tu In Two X Plus One by Dhir Tanwar and Tu In Two X Plus One by Dhir Tanwar and route. Point to route I was Mukesh Barala function quality cheetah I was Mukesh Barala function quality cheetah rain route dot right cc the right time hai paddhi dila tawe a guest's ki a tha amit hai to FD ka pehla me bread ki a tha amit hai to FD ka pehla me bread bluetooth our road 1968 our this function contractor 1968 our this function contractor time limit works a guy's find time limit works a guy's find value tarmani that our things fine value tarmani that our things fine middle aged 98100 98100 98100 9th me kar function eye shadow were American actor function made or not made and from The function of se The function of se The function of se me aa find salon extra function me aa find salon extra function almond and parameters university almond and parameters university bill bill form tay mir taqi target ko with sapphire do a target's parameters is blue at this time a target's parameters is blue at this time so American corbo egg apna career so American corbo egg apna career function sa scientific a fine billu ke function sa scientific a fine billu ke Comedy is Comedy is successful to some extent in this pond, the medicine is the leg, the heart, the successful to some extent in this pond, the medicine is the leg, the heart, the fine fruits, we save the nationality, friend, the fine fruits, we save the nationality, friend, the target of the first floor is that they are a potato, target of the first floor is that they are a potato, our our functions are meaningful, that is friends, the salt is a salt, today it is a function, anger, While While While drinking alcohol, subscribe to the leopard, Tarzan was there, I will check the pride of both of you in Amravat, that is the route, the day is coming, the salary thing, which was the day, first of all, I pressed my finger under the desire to make you, that from here, create Alas, Alas, Alas, such a period is router death, Amit goes such a period is router death, Amit goes happily so that Gandharva has written on Pimple to the limit, Arjun day has come, Arjun day has come, Amra Pali Tehsil's Ko has to hear the Amra Pali Tehsil's Ko has to hear the cricket voice, then left side and cricket voice, then left side and right side didi's travels. right side didi's travels. right side didi's travels. tree was ahead for these fruits. A fine balma daru dot loop fast bowler is a target reader and student. Reader is very a fine jeweler middle rudd was so aligning and west richa's so aligning and west richa's travels would have been along which Korba and this travels would have been along which Korba and this will mix. will mix. will mix. electronic media and final Ahmed Irfan Function Tamkor dekh to ok ok me submit quota, what kind of actress is this Vidya Mandir quota accept | 2024-03-19 17:43:56 | 1,261 | 1261. Find Elements in a Contaminated Binary Tree (Leetcode) |
|
nAzxiqC4VZc | hello friends today let's resolve the tallest billboard problem previously the tallest billboard problem previously we solve it we solve it via that first search but currently it via that first search but currently it will cause time limited exceeded so will cause time limited exceeded so today we will solve it with dynamic today we will solve it with dynamic programming so let's recall what is the programming so let's recall what is the question about question about we are given an integer array which we are given an integer array which called the row called the row rows um and we have two rows um and we have two uh dividing into uh actually not divine uh dividing into uh actually not divine because we can because we can um we do not need to use all the roads um we do not need to use all the roads we can let uh unuse some we can let uh unuse some ropes so we just need to build ropes so we just need to build two disjointed subsets which they will two disjointed subsets which they will have the same have the same sum and we want to make the sum sum and we want to make the sum as large as possible so let's see these as large as possible so let's see these three examples in the three examples in the in this example we can divide into two in this example we can divide into two sets sets and each of them will have the sum six and each of them will have the sum six so we use older routes so we use older routes in this example we don't use the one in this example we don't use the one two three five wheel b ten two three five wheel b ten and the 4 and 6 will also be 10. and the 4 and 6 will also be 10. for this example we cannot make it for this example we cannot make it because we only have two rows and they because we only have two rows and they have different have different lengths actually heights so how do you lengths actually heights so how do you solve it previously we solve it by uh we have two buckets or uh two sets left and right and for each road we have three cases why is use it for the left bracket the other is um is we use it for the right market the third case is we don't use it we just try every possible um combinations and we use some pruning but currently it will not parse the case it let's see how to solve it via dynamic programming we also have two sets right left and right but in this time we distinguish these two sets by which one is a higher and which one is the shorter if we want to solve it by dp the most if we want to solve it by dp the most important thing is important thing is what is the transition function and what what is the transition function and what is the initialization is the initialization in this case we have many variables one in this case we have many variables one is their their height is their their height we don't know what is their height and we don't know what is their height and what is because we want their height as what is because we want their height as large as possible and they have they they must have two equal heights so how about we just use the height difference because in that case if we use these two sets height difference at as the key then we know our final result will be dp0 that means this two so that's it but what about the maximum so that's it but what about the maximum distance distance for this example if the roads are this for this example if the roads are this and we know their sum is 12 then the and we know their sum is 12 then the maximum difference will just be 12 maximum difference will just be 12 because we put the uh because we put the uh their rows in the short their rows in the short set and put all the 12 set and put all the 12 in the higher set so this is the maximum in the higher set so this is the maximum distance distance so for ending roads we know so for ending roads we know the er either size is just the sum plus the er either size is just the sum plus 1 1 because 0 1 to 12. and for the because 0 1 to 12. and for the initialization we first initialize older initialization we first initialize older dp to negative 1 because dp to negative 1 because we want to get the maximum height and we we want to get the maximum height and we initialize two negative one and the dp initialize two negative one and the dp zero will be zero that means zero will be zero that means if we cannot make any um if we cannot make any um assignment then dp zero just be equal to assignment then dp zero just be equal to zero zero just like this example just like this example so what does dpi means i is a height so what does dpi means i is a height difference of between these two sets dpi difference of between these two sets dpi is the maximum common height is the maximum common height what does that mean actually when what does that mean actually when i equal to zero this dpi will i equal to zero this dpi will just equal to the height of these two just equal to the height of these two sets but other cases sets but other cases it is equal to the shortest which it is equal to the shortest which of these two sets so of these two sets so it is just the maximum common height it is just the maximum common height which is the shorter which is the shorter height so when we we have to iterate each row we have three cases one is put it on the higher set one is pretty on the shorter side the other is unused so when we put it on the higher set what should we change that will be dp i i the difference dpi plus the road we should to change it change it to what that will be the maximum of this dpi plus road and the shorter height why because as we said is the maximum common height so when you put that road on the higher set the height of this shorter set does not change so it should make sense to the when we update the dpi plus road this is the shorter one so what is the current mean the current is the current state of dp because in the this part we change this dp so in order to use the kernel state we should use a column just like the current screen so what is the current i means the so what is the current i means the shorter one because shorter one because um because the current i is the distance current i just means the maximum common height which i said many times is the shelter height so when we put the road to the shorter height what should we update it will be the i minus road because we don't know which is higher or the shorter one so we just or the shorter one so we just use distance minus use distance minus road road so why does it matter and what should we so why does it matter and what should we update um update um because uh when we add it to a shorter because uh when we add it to a shorter one we should update one we should update the distance minus the the distance minus the road with whichever is larger we we don't know whether it's the higher uh larger or the shorter plus road is larger so we just picked its minimum because as i said it's the maximum common height so which it should be decided by the shorter one so we just need to compare this to height for the higher one is the height is equal to current i plus the i because current ice is the shorter one the current i plus i and four this one is just the short one plus road that is current i plus the road so just pick the road and i minimum so that's it we updated it so this is the transition function when we put the road on the higher one we update i plus the road it will become the maximum of this or the shorter one when we put the road on the shorter one we update the absolute value of i minus road it will be this one or current i plus minimum road or minima i a current i plus road is the shorter plus road current i plus i will equal to the higher set height so that's it let's convert it to code so we have to get the sum and we iterate the road and we get the dp dp the size will be and we get the dp dp the size will be sum sum plus one do not forget to do the plus one do not forget to do the initialization initialization field the dp negative one field the dp negative one the dp0 will equal to zero the dp0 will equal to zero and then four uh and then four uh we iterate every rows and we iterate every rows and then we get the current column will be then we get the current column will be current current dp column and therefore dp column and therefore i will start from zero i will let's i will start from zero i will let's record then some minus road record then some minus road because the total size of this dp will because the total size of this dp will be sum be sum plus one so if we just use some minus plus one so if we just use some minus road road we can equate i plus plus we can equate i plus plus if the current i less than zero we just if the current i less than zero we just continue because continue because that means the maximum height is that means the maximum height is negative negative otherwise we update the two one is we'll otherwise we update the two one is we'll put put road in the higher one that will update road in the higher one that will update dpi plus road and dpi plus road and the shorter one current high the shorter one current high or dpi um or dpi um actually mass i actually mass i minus the road road there will be minus the road road there will be mass max dp mass max dp mass absolute value i minus road mass absolute value i minus road the other one will be the the other one will be the current i plus whatever mini current i plus whatever mini minimum which will be the i or minimum which will be the i or road so in the end just road so in the end just return dp 0 | 2024-03-25 12:15:52 | 956 | [Dynamic Programming] LeetCode 956. Tallest Billboard |
|
lqdgGNGPS68 | foreign Solutions are created Microsoft and my Solutions are created Microsoft and my aim is to empower every single person to aim is to empower every single person to be better at technical interviews be better at technical interviews keeping with that goal in mind today we keeping with that goal in mind today we are going to do a very interesting lead are going to do a very interesting lead code problem so let's get started with code problem so let's get started with that so today we are going to find the that so today we are going to find the celebrity lead code problem and if we celebrity lead code problem and if we see some of the popular companies the see some of the popular companies the problem has been asked that companies problem has been asked that companies like Amazon LinkedIn Pinterest Microsoft like Amazon LinkedIn Pinterest Microsoft Facebook Apple Snapchat Google Uber and Facebook Apple Snapchat Google Uber and Goldman sex so basically all the popular Goldman sex so basically all the popular companies have asked this question so companies have asked this question so I'm going to pay my utmost attention I I'm going to pay my utmost attention I hope you also enjoy the video this has to be one of the most interesting problems I have been able to find so far if you look at this a lead code categorized this as a medium problem if you try to understand the problem statement and try to think about it you will feel like this is actually a hard problem and once you put like some more thought into it you are actually going to feel that this is actually an easy problem so in my opinion this is actually an all-in-one problem let's understand the problem statement to go further deep it says that suppose we are at a party with n people and the names of these people are the numbers so basically numbers from 0 to n minus 1. so say for example we are in a party with four people basically the people are going to be 0 1 2 and 3. so these are going to be the four people now we are told that in this party there may exist so this is an important part that there may exist which means there might be a celebrity or there there might not be a celebrity okay now we are first of all given that what the definition of a celebrity is the definition of a celebrity is that that cell that every single person in that party knows who the celebrity is the second condition is that celebrity does not know and any single person in that party which is how typical celebrities are so now given these two definitions first of all we are told that we need to check that whether there exists a celebrity or not and if there exists a celebrity uh basically we can uh we need to find out who That Celebrity is the question is how we are going to find who That Celebrity is well definitely over here the relationship is based on either people knowing who the celebrity is or the fact that celebrity knows no one that everyone knows celebrity and celebrity knows no one right now at our advantage we are given a methodology where we can check between any two entities whether they know each other or not we have a method Boolean Knows A to B which defines that whether a knows b or not if a knows B if this gives answer true which means a knows B if this gives answer false which means a does not know B and why we are using that because the only relationship we have to identify whether a person is a celebrity or not is by the amount of people know them or the amount of people they know and in this case we either need to find the celebrity or we need to return -1 if there if no celebrity exists so I know this is a little bit complicated to understand but let's try to see some examples for this problem okay so in the problem we are actually going to have an input that looks like this uh where in this input we are given a list of list that contains some values uh that defines the relationship between any two values that whether they know each other or not now the thing is this input is kind of messy so I am not actually going to show you uh examples based on this exact input I'm actually going to show you in the base of something that is easier to visualize so this is the same input I took from here but I have actually converted it into a 2d match Matrix and basically as an input we are given a graph or we are basically given an adjacency Matrix okay so for this adjacency Matrix uh we based on this adjacency Matrix we are given two entities we are given a person and we are given whether that person knows each other or not this diagonal line is always going to be one because that defines that whether person zero knows person 0 or not whether person one knows person one or not things like that and that is always going to be 1 so we can simply ignore this one these this serves no purpose uh the important thing in this case is this defines that whether person zero knows person one or not so this answer is one which means that person 0 knows person one let's try to find who the celebrity is in this problem right so in this case uh we are given basically three percent so we can actually create a graph that looks like this of three person and we are going to name them as 0 1 and 2 right another thing is relationship between them is actually going to be the relationship defined by an edge where a edge would represent that whether one entity knows the other entity or not or one node knows the other node or not and this is going to be a directed Edge why because it could be possible that 0 knows one but one does not know zero so we cannot just simply have an undirected edge we must have a directed Edge in this case so let's try to do that as well so if we draw it from this this graph okay 0 0 this does not matter these three values so we'll just ignore them let's just start 0 with 1 so 0 knows one right so which means zero knows one yeah we mark it now does zero node two no zero does not note so there is not going to be an any Edge now whether one knows zero no one knows no one does not know zero and one also does not know two so one does not know any one now in this case whether two knows or zero yeah so 2 knows zero that is good and whether two knows one yeah two also knows one so that is also good and two nose two here that is true so we can ignore that in this case if we see if we see the two definitions of a celebrity that everyone knows who the celebrity is and celebrity knows no one at the party so definitely in this case we can say that hey if we check out the input for this value number one it knows itself but the thing is that is not the point it the point is whether it knows if anyone else at the party or not so one does not not know anyone at the party that is true and also zero knows one and two also knows one which means every single one who is every person every person other than one knows who the one is and one does not know anyone which means one perfectly fits on our category of celebrity and in this case one is going to be celebrity so we will simply return one as the answer and this is what we need to return okay let's see one more example in this case again 0 1 and 2 oh let's draw three lines now ignore these three cases and zero knows uh one no zero knows two yes so zero knows two okay does one node two we have one also knows two that's good now whether two okay two knows zero in this case two knows zero and uh two knows one no in this case can we find any celebrity actually we cannot find any celebrity y because in this case Okay zero and one both of them know two so that is good two qualifies for one of the property of being a celebrity the thing is second property of being a celebrity is that it has to know no one at the party but in this case who actually knows who the zero is so because to know one person two does not qualify for the second entity of our answer so in this case uh we cannot find any celebrity so because there is no celebrity present we are simply going to return -1 is the answer and this is what okay so first approach is a Brute Force okay so first approach is a Brute Force approach in The Brute Force approach approach in The Brute Force approach what we are going to do is we are simply what we are going to do is we are simply going to check that whether all the going to check that whether all the person that are given can any single one person that are given can any single one of them is a celebrity so for one by one of them is a celebrity so for one by one we are going to check for every single we are going to check for every single person whether they are celebrity or not person whether they are celebrity or not so in this case what we are going to do so in this case what we are going to do is first we will take consider person is first we will take consider person zero okay so for the person zero we will zero okay so for the person zero we will try to see whether zero is a self BT or try to see whether zero is a self BT or not how can 0 be a celebrity if everyone not how can 0 be a celebrity if everyone else knows who the zero is and 0 knows else knows who the zero is and 0 knows no one so in this case we can see that no one so in this case we can see that zero knows someone so 0 is not a zero knows someone so 0 is not a celebrity now we will have to check celebrity now we will have to check whether one is a celebrity or not so in whether one is a celebrity or not so in this case Okay one one still knows this case Okay one one still knows someone so one cannot be a celebrity but someone so one cannot be a celebrity but and in this case we'll try to see and in this case we'll try to see whether 2 is a celebrity or not so two whether 2 is a celebrity or not so two knows no one and uh let's see that if knows no one and uh let's see that if everyone knows two or not so this one everyone knows two or not so this one does the nose too but this one does not does the nose too but this one does not know two so two is also not a celebrity know two so two is also not a celebrity so in this case we will return a minus so in this case we will return a minus one and this logic leads us to the one and this logic leads us to the correct answer so some maybe if you make correct answer so some maybe if you make some modifications or tweaks it can be some modifications or tweaks it can be an acceptable solution as well the thing an acceptable solution as well the thing is this is still not the most optimal is this is still not the most optimal way to solve this problem so basically way to solve this problem so basically we would end up solving this problem in we would end up solving this problem in Big O of n Square time so which is not Big O of n Square time so which is not too bad for some of the problem but it too bad for some of the problem but it is really bad for this problem because is really bad for this problem because this can be done very efficiently with this can be done very efficiently with other methods so let's try to see what other methods so let's try to see what that other methods could be so in this scenario if we see okay 0 knows one and two so zero knows one and two right uh same way one does not know anyone and two knows one and uh one and zero so two no zero and two knows one so is basically answer is going to E1 that is a given fact the thing is uh what is one smart trick we can use the smart trick is the nose function the nose function that we are given in the input that is there for a reason and what nose function does is that if we provide any to Value say for example if we provide the values of 0 and 1 it is quickly going to tell us that whether 0 knows 1 or not so in this case Okay zero knows one that is a true fact now the thing is if we know for sure that 0 knows one what is one thing we can say for Guarantee we can say for Guarantee or for certain city that 0 cannot be a celebrity why we can say that because remember the definition of a celebrity the definition of a celebrity is that everyone knows the celebrity and celebrity knows no one which means in this case if we try to find uh or if we try to see this nose function between 0 and 1 and the answer is true if the answer is true definitely we can say that 0 cannot be a celebrity which means we are eliminating 0. now what could be the second possibility second possibility could be say one example if we try to use the NOS function or a values 1 and 2. if we try to use the function 1 and 2 knows that the answer is going to be false why the answer is going to be false because 1 does not know 2. if 1 does not know 2 what is also one more thing we can say for certainty well we can say for certainty that in this case 2 cannot be celebrity Y 2 cannot be celebrity because we found at least one element that does not know two and in order for 2 to be celebrity celebrity has to be known by everybody else in the in the power so because we find one entry over here who does not know two we can say for sure that 2 is not a celebrity which means depending on the result of this nose function if the value is true we can eliminate one value that is the first value in the nose function if the value in is false we can eliminate the second value inside this uh given input which means with every single nose call we are getting rid of one element so in this case after just making two calls we were able to get rid of 0 and 2 which means if there exists a celebrity it has to be one so now all we need to do is that since this is the last item or last value pending do we need to check that whether everyone knows one or not no why because since we know for sure that these two are not the celebrities right so all we will have to worry about is that whether one knows uh no one if one knows no one which means one has to be the celebrity if one knows at least one person which means there are no celebrities inside this input and we can simply return -1 and this is the whole logic behind this problem let me try to explain very quickly with a big example so now we have bunch of different values over here basically we are simply going to use the nose function and we are going to go through every single value and try to see whether it knows the next value or not so first we'll try to see that whether the zero knows one or not so and we can ignore all of these values because diagonals doesn't matter we do not care if they know their own self or not so in this case Okay 0 to 1 0 does not know 1 which means we can say for sure that 1 cannot be celebrity if one cannot be said be celebrity we can simply skip over to the second value now in this case we will check that whether 0 knows 2 so in this case 0 to 2 0 knows 2 so because 0 knows 2 we can say for sure that 0 cannot be a celebrity so we ignore this now we are at this value number two so we'll try to see whether two knows 3 or not so 2 to 3 if we check okay 2 knows three so if two knows 3 definitely 2 cannot be a celebrity so we will ignore that now we are at this value number three so we will take check for three to four so three to four if we check yeah three knows four so in this case three cannot be a celebrity because three knows four because of this value now we are at this four position number four four to five so if we see four to five so four to five uh this value is actually zero which means four does not know five so because four does not know five five cannot be a celebrity so in this case we have actually got rid of all of these elements and only fourth value spending so now we know that if there exists a celebrity it has to be four otherwise there are no celebrities so now we are simply going to check that whether 4 knows anyone or not and for that we simply have to do one check at this fourth row to see whether apart from 4 by itself does it know anyone else and it knows no one so definitely for uh or is the only candidate left and 4 knows no one so in this case 4 is definitely our celebrity and this we can simply return as the answer and this is the whole logic behind our answer say for example in this case by chance F4 knew this value number one if this was answer one then simply we can say that okay 4 is also not a celebrity and we can simply return a minus 1 in this case the thing is because this value is actually 0 so in this case answer is actually going to be 4 and we are solving this problem most efficiently if we see time complexity in this case the time complexity is actually going to be big of N and if we see space complexity well apart from using couple of variables we are not using any additional space so space is actually first I identify few things so I created first I identify few things so I created a new Global integer to use the number a new Global integer to use the number of people and I have assigned it the to of people and I have assigned it the to the value of N and basically in the the value of N and basically in the problem we need to resolve this fine problem we need to resolve this fine celebrity problem uh and also for this celebrity problem uh and also for this problem I have created is the celebrity problem I have created is the celebrity a helper method so that is going to a helper method so that is going to Define that whether any single candidate Define that whether any single candidate that we have been able to identify from that we have been able to identify from this fine salivary method if that is a this fine salivary method if that is a celebrity or not and now first let's celebrity or not and now first let's start implementing this find celebrity start implementing this find celebrity method and then we will Implement our is method and then we will Implement our is celebrity method so first of all we are celebrity method so first of all we are going to initialize a variable called going to initialize a variable called celebrity candidate now we are going to celebrity candidate now we are going to run our for Loop and for every single run our for Loop and for every single value we are going to check or we are value we are going to check or we are going to call our nose function and for going to call our nose function and for the nose function we are basically the nose function we are basically basically providing the value of the basically providing the value of the celebrity candidate and the value of a celebrity candidate and the value of a current I current I now depending on the answer we get back now depending on the answer we get back we are going to update the value to the we are going to update the value to the I I so what this is going to do is this is so what this is going to do is this is simply going to eliminate every single simply going to eliminate every single value for us except one last remaining value for us except one last remaining candidate and that we are going to candidate and that we are going to consider as the celebrity candidate and consider as the celebrity candidate and once we get out of the loop all we will once we get out of the loop all we will have to do is we will have to call our have to do is we will have to call our is celebrity method if this value is is celebrity method if this value is actually true if this value is a actually true if this value is a celebrity we are going to return this and if that is not the case we can simply return -1 now in this method we will first of all run a for Loop inside the for Loop first we will have to check that if the given value of I is equal to J which means we have found a diagonal value so in this case we simply ignore that and if that is not the case we are going to check that whether J satisfy all the properties of being a celebrity or not if any of these is true we can simply return false and if that is not the case and if we get out of the loop we can simply return to and I think this has to be the whole logic behind this in uh input so let's try to run this code scenes like our solution is working as expected let's submit this code and our code runs pretty fast compared to a lot of other Solutions and it is also really efficient in terms of time complexity so this was a great problem to solve and to understand lot of different concepts I would be posting this solution in the comments so you can | 2024-03-22 12:37:25 | 277 | Find the Celebrity: 277- graph interview question @ google, apple, amazon, meta, microsoft, Linkedin |
|
GiKub9tViDc | Hello Hello Everyone Today Going To Cover A Distance Of This Heart Problem Likh Course Let's See Who Distance Of This Heart Problem Likh Course Let's See Who Wins Gold In Return For Wins Gold In Return For Operations In Wave 205 On Thursday Operations In Wave 205 On Thursday And Then Example Avv Exploded Battu Battu How To Make A Tour Officer We Can Do It How To Make A Tour Officer We Can Do It How To Make A Tour Officer We Can Do It be lit subscribe first replacing to drops vikram rathore and where going to update room on and on's katesar village to 16 years paper pot for operations at every place to and director and subscribe convert to a subscribe convert to a mp3 operations in mp3 operations in mp3 operations in Till 80 Till 80 Crore Bhaan's 102 Top Peeth Peeth Peeth A Similar NI0 Crore Bhaan's 102 Top Peeth Peeth Peeth A Similar NI0 Komodo Jaldi Cheek Eid Tu And Finally 2013 world.com Maa Saraswati India And Sunao Is Want Change Vote 1032 Operation Se Ko Subscribe Subscribe Now To To To To To To To 2030 subscribe kare subscribe Video Ko Ki Swarna Dash Tuition Fee Hai To Here If You Want To Convert K It Well You Can Simply Add Half Of The Elements And The interests of this you want to bring LED military side development will eliminate were how to print for a so simply this you want to convert this LED to a for from string converting and simply update itself will bring to front subscribe and from just solution solution point problem subscribe to subscribe our solution available on astro shop share gosht surya point use petulance fabric par subscribe subscribe our solution problem ka solution problem What is the meaning of what is the A minimal operations required to convert hai Simply attend let's go Simply attend let's go Simply attend let's go into what is the smallest and minimal into what is the smallest and minimal operations in full force to RO yes ka operations in full force to RO yes ka prayas laptop dutiable si feeling prayas laptop dutiable si feeling ombudsman and subscribe to ombudsman and subscribe to and listen list fields for stringent this and listen list fields for stringent this remedy and fields and from string remedy and fields and from string operation request switch off that operation request switch off that quiet going quiet going quiet going operation sir request you feel subscribe 108 to change word from roast 220 spring and mts rintu roshni operations equal than and hear paint jeans khol post the And MP Singh Were Going And MP Singh Were Going And MP Singh Were Going To Film First Unit Converter That To Film First Unit Converter That 2mp Settings In A Week This Now To-Do 2mp Settings In A Week This Now To-Do List Hanif Qureshi Cricket Camp What He Was Doing This List Hanif Qureshi Cricket Camp What He Was Doing This Foundation Of The Attachment Foundation Of The Attachment Fear For U Fear For U Yesterday Morning None Today S Company Operations Yesterday Morning None Today S Company Operations Request To Add And Request To Add And Request To Add And Hai Simreli Experiment Hai Simreli Experiment Motu Patlu Motu Patlu Hain Let's Understand Such Serious Problem Hain Let's Understand Such Serious Problem Set Point Check How Many Operations Request To Convert Set Point Check How Many Operations Request To Convert From String From String String And Surya Play List Play A Sanam Movie Want To Tell How Many Operations And that in And that in And that in this case minute updates 2012 and updates 232 this case minute updates 2012 and updates 232 half a mile explain the calling from that is half a mile explain the calling from that is how you convert in to the best of that subscribe And subscribe The Amazing and subscribe must come guest if its growth rate status on operation To in to-do list A certain way want to expel Select check To in to-do list A certain way want to expel Select check rebellion Vaneshwar note from vaneshwar Singh subedar pick meaning of this cream and a plus 153 1000 so let's come tourist just because on Thursday the city is simply shooting this to welcome to Chill Issue Text And Chill Issue Text And Powder Of Unofficial Not Give Winners Dixit Boxers Minimum Is Dynasty OnePlus One Is Too Looter Let's Check The Receiver 930 Tours And What Is The Meaning Loot Finally Vikram Two Drops And Illegal Loot Finally Vikram Two Drops And Illegal Solution Recite Time Minimum Of Beat Solution Recite Time Minimum Of Beat Solution Recite Time Minimum Of Beat two plus one tea output and liquid operations at do subscribe this number a to-do list is going to solve every problem for every subscribe trees-plants words have finally trees-plants words have finally arrived to table solution subscribe to arrived to table solution subscribe to now half the fuel subscribe to that now half the fuel subscribe to that your your your hai inverter direct word ajay ko half an hour hindi movie on it starman first problem scientist venus after all how long loot loot no veer vve 28 blood group how to build ee the inside popular point tay magar characters match hai loot ajay ko Loot right, he is a fielder, Table of Solution, Ajay has a personal problem, Ajay has a personal problem, Scientist Scientist Motu Patlu Motu Patlu 's report, submit one, please subscribe. | 2024-03-20 11:30:29 | 72 | Edit Distance | LeetCode 72 | Coders Camp |
|
C7SwXy6Z-AY | [Music] hello everyone welcome to quartus cap so hello everyone welcome to quartus cap so we are today at the 27th we are today at the 27th day of april lead code challenge and the day of april lead code challenge and the problem given here is power of three problem given here is power of three so the input here is a integer value m so the input here is a integer value m and we have to written whether it is a and we have to written whether it is a power of 3 power of 3 so now it seems to be very simple so now it seems to be very simple problem so coming up with the efficient problem so coming up with the efficient solution matters here solution matters here so the basic logic we all could think so the basic logic we all could think first is first is if a number is a power of 3 or power of if a number is a power of 3 or power of any number any number then it will be divisible by that number then it will be divisible by that number as well as well so using that logic we are going to have so using that logic we are going to have a first approach so a first approach so let me have the number so since it is a let me have the number so since it is a power of 3 power of 3 then it should be divisible by 3 so i'm then it should be divisible by 3 so i'm going to divide this number by 3 going to divide this number by 3 so if it is divisible by 3 then the so if it is divisible by 3 then the reminder should be 0 reminder should be 0 so until the number reduces to 1. so here i'm going to check whether the number is divisible by 3 and reduce the number or divide the number by 3. so finally return if n is equal to 1 and we have to add a base case that if my n is less than one then we have to let's run let's run let's submit and try to check other test let's submit and try to check other test cases cases yes it is accepted so this solution is yes it is accepted so this solution is gonna gonna take logarithmic time so for this simple take logarithmic time so for this simple problem coming up with problem coming up with a constant time is a real challenge a constant time is a real challenge so now here in the conditions the so now here in the conditions the constraint given is the maximum value of constraint given is the maximum value of the given integer n must be 2 power 31. the given integer n must be 2 power 31. for example if there is a maximum value for example if there is a maximum value given given suppose 2 power 31 is the power of 3 suppose 2 power 31 is the power of 3 then then this must be divisible by another value this must be divisible by another value which is again a power of 3 which is again a power of 3 so consider 2 power 31 is itself so consider 2 power 31 is itself a power of 3 then 2 over a power of 3 then 2 over 31 must be divided by another power of 3 31 must be divided by another power of 3 for example for example 3 power 0 or 3 power 1 or to the maximum 3 power 0 or 3 power 1 or to the maximum value value within the limit so we are going to find within the limit so we are going to find the maximum value the maximum value which is again a power of 3 within 2 which is again a power of 3 within 2 power 31 power 31 so that will come up with more efficient so that will come up with more efficient solutions so i'm here gonna apply the solutions so i'm here gonna apply the logarithmic formula logarithmic formula where log base of x is equal to n means where log base of x is equal to n means we'll get the maximum power of that we'll get the maximum power of that number within the limit number within the limit so what i'm going to do is i'm going to so what i'm going to do is i'm going to do log of do log of 3 of max value 3 of max value then i'm going to get what is the then i'm going to get what is the maximum power of maximum power of 3 in that limit so let us go to the code 3 in that limit so let us go to the code so let this code be here i am going to so let this code be here i am going to print it print it for a better understanding so i am going for a better understanding so i am going to print to print math dot log of integer dot max value divided by math dot log of 3 so that will get to know what is the maximum power of 3 in the within the maximum value so let me run this so here it has displayed 19 point something which means 3 power 19 is the maximum achievable powers of 3 within this maximum value so let me calculate the power of 3 power 19 is this so let me power of 3 power 19 is this so let me copy this value and now let me remove all this this value divided by this value divided by n is equal to zero let me directly n is equal to zero let me directly return it so this is it so yes i am going to check whether the maximum power within the limit or the maximum power we can get is divided by the given input number which means the given number is a power of n yes so let me add one more thing what if yes so let me add one more thing what if the given number is less than one the given number is less than one so let me give greater than zero so let me give greater than zero and and yes again the solution accepted and it is 100 faster so yes hope you like the video so thanks for watching the video if you like the video hit like | 2024-03-24 10:31:11 | 326 | Power of Three | LeetCode 326 | Coders Camp |
|
npVx-arpbOQ | hello everyone welcome back to my series of videos of me solving lead code of videos of me solving lead code problems this problem is H index problems this problem is H index what is it about given an array of what is it about given an array of integer citation where citation I is the integer citation where citation I is the number of citations a researcher number of citations a researcher receives for their index paper return receives for their index paper return the researchers age index what is the the researchers age index what is the age index according to Wikipedia is age index according to Wikipedia is defined as a maximum value of age such defined as a maximum value of age such that the given researcher has published that the given researcher has published at least eight papers that have been at least eight papers that have been each cited at least eight age times so each cited at least eight age times so what does that mean let me copy this we know that the output is free the H value is free and why is it free let's look here this researcher published one paper that was cited three times one paper that was cited zero times one that was six one that was one one that was five the H value is free because he published the H value is free because he published three papers that were cited at least three papers that were cited at least three times three times he published one paper that was cited he published one paper that was cited six times doesn't count counts as one six times doesn't count counts as one he released they published a also three he released they published a also three six and five not this one six and five not this one these are the ones that make the these are the ones that make the the H value free so he also published a the H value free so he also published a paper that was cited three times that paper that was cited three times that doesn't count as an H value free because doesn't count as an H value free because he just published the paper that was he just published the paper that was cited once cited once twice twice almost three times he didn't publish but almost three times he didn't publish but it wasn't it wasn't um um it was inside it five times so if just it was inside it five times so if just to give you a context if the uh the to give you a context if the uh the array was just six and five the age array was just six and five the age value would have been two value would have been two because there were two papers that were because there were two papers that were cited at least two times and that's the value so what's my strategy to fight this so let's look at this value over here that's this array three zero six one five but sorted in reverse order so descending order so six five three one zero okay so now let's iterate at this moment we found a paper that was cited six times but it was only once so our best value is age equals one iterate to the next one five well this paper was cited five times but if so so a best age is two so now we go to free yeah free cool free was cited three times and we have three papers that was cited three times nice three and now we go to one well one if we have paper that was cited once and we don't even need to look back because the age value here is already smaller than the H value that we got so we can actually just like scrape this and not even care at this moment if this value is smaller than the age value we can stop so let's open vs code three zero six one three zero six one five so best h and for and for index in citations in enumerates enumerate citations so we check our first vowel the minimum of our first vowel and the index that we're on so the minimum of Val and index and if candidates and if candidates is bigger than best h I think I need to do index plus one because of index 0 then last age equals candidates so let's look at this our best age is five well it shouldn't identify identify oh yeah I forgot about one detail oh yeah I forgot about one detail remember when I said if we get here and remember when I said if we get here and it's smaller than our H value okay it's smaller than our H value okay if Val is smaller if Val is smaller than our best age than our best age we break best age one so let's go candidate Val is free index so let's go candidate Val is free index is zero is zero oh yeah right I forgot a very important oh yeah right I forgot a very important part remember when I said I needed to part remember when I said I needed to sort it sort it yeah yeah citations foreign now the vowel is five and the best H is two now and now we we just reach the end I think also need to copy from that if so accepted and this was my best submission accepted and this was my best submission so far 43 milliseconds so far 43 milliseconds it's as simple as this hope you guys it's as simple as this hope you guys have enjoyed it | 2024-03-22 12:32:50 | 274 | 💻Solving All LeetCode Problems with PYTHON 🐍 - 274 H-Index |
|
Ydur1aYALc4 | Hello guys welcome to this remedy subscribe The Channel Please the I invented Khoj simple and see how to add that And subscribe The And subscribe The Amazing subscribe and subscribe the Amazing subscribe and subscribe the Video then subscribe The Video then subscribe The Video then subscribe The subscribe in this to India's will find the combination navigate director an order from its combination chief subscribe to the Page if you liked The Video then these 1000 drops for this problem Result Result Result Old man length of strings of years working with the best friend will be held for the length of the day Will be adding this temporary window into and returns to give water subscribe and subscribe the Video then subscribe to The Amazing Se karare wise wikinews and then in more problems user defined the rise of the apps hai tomorrow morning two brothers find the present president to videha.the character servi subscribe The Video then subscribe servi subscribe The Video then subscribe to the Page if you liked The Video subscribe to -1.2 The Lord of the Rings Digit subscribe -1.2 The Lord of the Rings Digit subscribe Video to like subscribe and subscribe Video to like subscribe and subscribe the Video then subscribe to subscribe the Video then subscribe to subscribe our Channel subscribe our Channel subscribe Pimple Thanks for watching this video 2019 Pimple Thanks for watching this video 2019 | 2024-03-19 15:55:04 | 17 | Letter Combinations of a Phone Number | Live Coding with Explanation | Leetcode - 17 |
|
XwU3Ca6kHSU | hey what's up guys this is sean here so today let's take a look at 1655 so today let's take a look at 1655 distribute repeating integers okay so you're given like an integer an array of of any integers where there are at most 50 unique values in the in the array right and then you're also given like an array of m customers other quantities so the each quantity means how many how many numbers this this customer is is going to get right and the integers i customer gets all are all equal and every customer is satisfied okay so blah blah blah you know return true if it is possible to distribute numbers according to the vo to the above conditions so basically what it means that you know we have a long list of numbers but there are like only at most 50 different numbers so which means that we can group those numbers together within like a 50 size of 50 so we we have a numbers here right and so we we have a numbers here right and then the first then the first the first example is what is like this the first example is what is like this so basically the first customer so basically the first customer he wants two numbers he wants two numbers he wants he wants two he wants he wants two not two numbers i mean he wants two same not two numbers i mean he wants two same numbers numbers right but we only have four different right but we only have four different numbers whose numbers whose quant is always only has one that's quant is always only has one that's that's why that's why this one is it's false we cannot satisfy this one is it's false we cannot satisfy that that the second one is true because you know the second one is true because you know since the first customer wants to since the first customer wants to wants two same numbers and we have we wants two same numbers and we have we have two have two three here that's why this one is true three here that's why this one is true and same thing for for this example and same thing for for this example three here right so we have two ones and three here right so we have two ones and two twos two twos but and then the two customers they want but and then the two customers they want like two number like two number two same numbers and another two same two same numbers and another two same number so we can give number so we can give this the first two ones to customer one this the first two ones to customer one and then we give the first the this two and then we give the first the this two two to the customer two two to the customer two all right so on so on and so forth okay all right so on so on and so forth okay this is another one right we have five this is another one right we have five ones so we can give five to customer ones so we can give five to customer one we can give three three ones and one we can give three three ones and then two ones then two ones to one and three ones to customer two to one and three ones to customer two all right so here are some very all right so here are some very important constraints here important constraints here so i mean there are at most 50 unique so i mean there are at most 50 unique values in nums we already know that and values in nums we already know that and then the customers there are only 10 then the customers there are only 10 customers customers okay so what we have so okay so what we have so we have like a list from 0 to 50. each number we have dif we have a list this one has a different number have different count you know turns out 10 or even 88 doesn't really matter so here we have a count count hash table or account list it doesn't really matter actually we don't care about the value of numbers all we care is the count of each numbers so we have a list of counts for 50 different numbers and then we have what we have a zero to so we have ten customers and they so we have ten customers and they each each customer also wants some each each customer also wants some numbers numbers from this from this count right we have from this from this count right we have a different 2 a different 2 6 5 7. and the prob the question is asking us can we somehow distribute this count of numbers so that we can i mean so for this problem you know i mean so for this problem you know there is like a greedy there is like a greedy solutions basically you know we uh i solutions basically you know we uh i think that that solution is like a think that that solution is like a greedy plus backtracking greedy plus backtracking where we sort from we sort the where we sort from we sort the quantities quantities in the reverse order basically we're in the reverse order basically we're trying to satisfy trying to satisfy the the customer who wants the most the the customer who wants the most numbers and then we try each of them in numbers and then we try each of them in this this in this count we also sort discount in this count we also sort discount from the the biggest to the smallest and from the the biggest to the smallest and every time when we every time when we we uh if we cannot satisfy this customer we uh if we cannot satisfy this customer we simply we simply return fast if we can satisfy everything return fast if we can satisfy everything all the customers will all the customers will return true i mean that one can can return true i mean that one can can actually pass actually pass all the test cases but to me i all the test cases but to me i don't think that's that's 100 don't think that's that's 100 correct but i cannot approve but i can't correct but i cannot approve but i can't prove that you know that's why i'm not prove that you know that's why i'm not going to talk about going to talk about that solutions here instead i'm going to that solutions here instead i'm going to talk about the talk about the dp solutions here so every time when you have like this kind of two var two like conditions right you have like a candidates and then you have another like this thing you know this one is like similar like the uh basically we have a we have different basically we have a we have different candidates and we need to assign candidates and we need to assign some numbers to to these customers but the difference for this problem is that you know we can assign multiple customers to the same to the same uh count here like the uh the last example here right for this one we need to assign multiple yeah so that's that and so for this kind yeah so that's that and so for this kind of problem you know it's always a of problem you know it's always a i think the one of the template is that i think the one of the template is that for the dp for the dp right so the first the first one is the right so the first the first one is the we're going to always have a mask here we're going to always have a mask here you know you know we have a mask and then we'll have an we have a mask and then we'll have an index index so that's going to be the the the common so that's going to be the the the common template for this problem template for this problem and who is going to be the mask of and who is going to be the mask of course so whoever is smaller will be the course so whoever is smaller will be the mask mask and in this case it's going to be the and in this case it's going to be the customer right so the customer is the customer right so the customer is the mask and the index of course mask and the index of course is the uh is account it's a is the index is the uh is account it's a is the index of the count so we need this index of the count so we need this index because we don't want to go back because we don't want to go back basically you know the index means that basically you know the index means that the dp the dp index means that from zero to index index means that from zero to index minus one minus one zero to minus index one when with the zero to minus index one when with the mask mask mask means that which customer has been mask means that which customer has been assigned assigned to to the to to some numbers what's gonna if if it is true right because this one this thing in the end will return either true or false things can be going to be a boolean type yeah so we we start in i mean so is that yeah so we we start in i mean so is that what's going to be the next the next what's going to be the next the next thing is that you know every time thing is that you know every time when we add a current index right let's when we add a current index right let's say we're at index we're at this index say we're at index we're at this index and and then the count for this number is 10 then the count for this number is 10 okay so the converse number is 10 and okay so the converse number is 10 and so what's going to be the scenarios at so what's going to be the scenarios at the current the current state right state right let's say we have a the mask you know let's say we have a the mask you know the mask is the mask is of course going to be either zero one of course going to be either zero one zero or one it doesn't really matter zero or one it doesn't really matter right i mean right i mean we could use zero represents the we could use zero represents the customers which doesn't have a customers which doesn't have a how has not been assigned or vice versa how has not been assigned or vice versa either way is fine either way is fine but for this problem the but for this problem the let's say we have an index right let's say we have an index right and we want to know because since we and we want to know because since we will be we might be signing will be we might be signing multiple customers right with this multiple customers right with this with this with the same account number with this with the same account number here here so which means that let's say we have so which means that let's say we have let's say one means the uh let's say zero zero means that the customer who has not been assigned to the to the numbers which means that we have to get all the the subsets since we have four here we could the subset i mean of course it's all the subsets among all those kind of zero four zeros we have to try all of the subsets because we don't know that and that's why we have to try all the subsets with the current mask so the subset i mean is like this i mean so the first subset is for example we have this one right the first subset of that is one one zero one zero zero i'm going to so which means the uh okay so the first case is the this this customer will be assigned gets assigned to this one and second one is is what is like now with this one right and then here the third one will be this this one will become one right and so on and so forth right and that that's the that's the first customer case and then the second one is the then the next one will be the the two customer case right so we are we assigned two customers with this count here so we should only one one one two one zero zero one one and then what and then we have this two and one zero one one this two one zero one one and then so on and so forth and then three and four so basically we have to find a very efficient way to give us the subsets based on the mask right and to do that you know there is like a trick to do it we have a there is a formula to do it but to do that we have to do it in a reverse way which means that you know we have to make we have to use one represents the uh the not assigned customer and zero represents the ones that has been assigned so we have to reverse the definition of the speed mass why is that and i will give you an example here you know so let let's say we have this mask all right and the formula is like this the formula and the formula is like this the formula is the is the is a current one the current mask minus one so that's that you know so that's the uh so that's that you know so that's the uh the formula the formula to get the next subset all right so the way we're getting the subset as you guys can see here so at the beginning you know this current okay and the subset is like this so when the current one so when the current one my my minus one so when the current one my my minus one so what do we have here we have one so what do we have here we have one zero zero one zero zero yeah and then if we do a if we do a end mask here right and with mask what we have here we have we have we'll have one zero zero one zero we'll have one zero zero one zero zero one zero zero one zero all right as you can see here now we all right as you can see here now we have a different mask here right have a different mask here right so the one the one got removed so the one the one got removed in the end right and how about in the end right and how about let's i mean if if we keep going right let's i mean if if we keep going right now this one is the current now this one is the current right so if we do another minus one for right so if we do another minus one for this one this one we have one zero zero one zero zero zero we have one zero zero one zero zero zero one one and if we do a a bit and with the mask and if we do a a bit and with the mask this is the mask right this is the mask this is the mask right this is the mask again what do we have again what do we have we have zero zero zero one zero zero zero one uh sorry two zero zero i'm sorry yeah so this thing will be the current yeah so this thing will be the current so this is the the current one so this is the the current one right so this is the current one and uh and as you guys can see here right so we are like actually getting the all the subsets for the ones and you you can keep going going and i'm not going to keep uh do more stuff here i mean i'll do one more thing so let's do another subtract by one so one zero zero zero zero right and then we if we do uh end with that what we have we have one zero zero one zero zero zero right so this is the second subset as you guys can see here so we have a this one here right this two one here and we can keep going that next one will be one zero zero zero one one one one right and then if we do another end here it will be one zero zero zero zero zero zero so here if we do another one right we're so here if we do another one right we're gonna have like a zero gonna have like a zero one one one one one one one right and one one one one one one one right and then if we do another then if we do another end of it is that what what do we have end of it is that what what do we have we're back we're back so so now the first one will be zero now so so now the first one will be zero now we have zero we have zero zero one zero zero one one zero one zero zero one one right so this is the the new one as you right so this is the the new one as you guys can see here so guys can see here so now we're removing the first ones here now we're removing the first ones here we have these three ones left we have these three ones left anyway so that's how we can calculate anyway so that's how we can calculate the uh the uh efficiently calculate the next subset efficiently calculate the next subset from a bit mask and since as you as you from a bit mask and since as you as you guys can see here guys can see here we have to use like one as the uh the we have to use like one as the uh the as the remaining parts so which means as the remaining parts so which means that you know that you know we will start from our starting point of we will start from our starting point of the mask will be one one one one one one the mask will be one one one one one one and in the end when we reach the the and in the end when we reach the the zero state zero state we we know that okay it means that we we we know that okay it means that we have have assigned all the customers with with assigned all the customers with with some numbers some numbers then we then we can return true okay cool so i will just start coding here you know during coding we'll also be implementing some of the the hot the the precalculations but i'll um um i'll try to try to implement the main i'll try to try to implement the main logic first logic first so like i said you know we're gonna have so like i said you know we're gonna have like a dp right so like a dp right so for the definition of dp here we have for the definition of dp here we have state the first one is the index and the state the first one is the index and the net the next one is the mask net the next one is the mask right so i'll be using like a right so i'll be using like a like the uh the pythons like the uh the pythons way of doing the memorizations here you way of doing the memorizations here you know so if the mask if the mask is equal to zero then we know okay we have assigned all the customers with some numbers that's why that's when we return true and else if the index is in okay so to do that let's try to so the count will be uh we do a counter so the count will be uh we do a counter right we will counter off the numbers right we will counter off the numbers and all we need and all we need we just need the values right we don't we just need the values right we don't need the keys here so that's why we do a need the keys here so that's why we do a values right and then we will values right and then we will convert this thing to a list right right convert this thing to a list right right so that's how we do it so that's how we do it and then we can we have n equals the net and then we can we have n equals the net length of the count length of the count and then we have we have m equals the and then we have we have m equals the length of the quantity length of the quantity right and then here in the end we simply right and then here in the end we simply return the dp of zero return the dp of zero and what the at the beginning we have and what the at the beginning we have one one there are all ones ones means that this there are all ones ones means that this one just do a left shift one just do a left shift by m and then minus one that's how we by m and then minus one that's how we get one one one one get one one one one right okay back to this dp here yeah back to this dp so and when's the when it's going to be the the negative case so if the index has reached the end of of all the other the count then we know we need to return fast right so that's that and now the next one is what is the answer right so the answer is what so you know with this kind of problem kind of problems you know an index is all there's always like a case where we we can either pick this discount or we we don't pick that's why for this kind of problem the first one is going to be always the the not peak would be the index plus one right if we don't pick it then it means that the mask didn't get didn't change at all so we can simply do an index plus one and then not use current count right not use current count right the second one will be use current count the second one will be use current count so to use current count uh i think we so to use current count uh i think we can just do a quick check here i mean if can just do a quick check here i mean if not the answers not the answers then we we use it right but this then we we use it right but this this thing is optional because if this this thing is optional because if this one already returned untrue here one already returned untrue here we can simply return the answer right we we can simply return the answer right we don't have to continue don't have to continue but this option it won't affect any of but this option it won't affect any of the time complexity here okay so now we need to get all the okay so now we need to get all the subsets subsets right try all the sub subsets right try all the sub subsets of of mask and here there's also an another another difficulty here i mean let's go back to this example here one zero zero one one zero one let's say that's the current mask and zero means those customers have have already been assigned to the to a number and one one means the uh those are the customers we need to consider right here and to efficiently we have this kind of mask here right so we have this kind of mask here right so let's see so there's like let's see so there's like well current you know i'll write the uh well current you know i'll write the uh the formula first so at the beginning the formula first so at the beginning the current is mask the current is mask right and then the formula is like this right and then the formula is like this while the current is greater than zero while the current is greater than zero because we're removing each of the ones because we're removing each of the ones in the end all everything will become in the end all everything will become one that's what that that's when we stop one that's what that that's when we stop right we have a right we have a current equals the current minus one current equals the current minus one right and then we do a right and then we do a we do an end it's a mask right and that's how we get each of that's how we got the current so the current is like this one zero zero one one zero zero and something like one zero zero uh one zero zero zero right something like that basically the the subset of removing of replacing any number of ones into with zero so now the next problem comes down to uh let's assume we uh we have re remove we decide to use the last two these two customers with this current index what's going to be the condition of using that right so the condition of using that is that we have to know we have to know if the quantities if the quantities of those two customers is equals it's either equal or smaller than the uh than the current count if it is if it is then we can use it otherwise we can't okay hmm hmm while we're doing the subsets and as you while we're doing the subsets and as you guys can see we are doing the subsets by guys can see we are doing the subsets by by using this bit manipulations here and by using this bit manipulations here and how can we know the the sum of those numbers the sum of the quantity the sum of of those those beat who has been converted from one to zero that's going to be the the question for us right and actually there's another trick here you know instead instead of considering the ones has been has been changed from one to zero let's consider let's consider the ones has let's consider the ones that has not been and those the ones that has not been and those the ones that has not been changed changed changed to zeros are the numbers our changed to zeros are the numbers our are the customers we are going to are the customers we are going to we're going to going to assign with the we're going to going to assign with the with the current with the current index with the current account here so index with the current account here so why we do that because you know why we do that because you know at each of the the while loop here we at each of the the while loop here we have a current here so the current is have a current here so the current is like this something like this like this something like this and with this we know okay so we have and with this we know okay so we have two numbers two numbers we have two ones that we want to we want we have two ones that we want to we want to assign two customers we want to sign to assign two customers we want to sign and then we can do some pre-calculations and then we can do some pre-calculations to just use one time to give us the the to just use one time to give us the the sum sum because if we don't do a calculations because if we don't do a calculations assuming we have this one here we have assuming we have this one here we have to scan to scan everything we have to scan the entire everything we have to scan the entire the entire mask the entire mask right to get it to check if if this is right to get it to check if if this is one if it is one then we'll one if it is one then we'll we summarize the quantity and we have to we summarize the quantity and we have to scan it for scan it for for each of the mask here each of the for each of the mask here each of the current one here current one here that's why you know we can simply do a that's why you know we can simply do a pre-check a pre-calculation here you pre-check a pre-calculation here you know know the uh so we're going to have like a the uh so we're going to have like a totals totals right the totals of the what the totals right the totals of the what the totals will be the total quantities will be the total quantities it needs for some of the customers for it needs for some of the customers for some of the combination of the customers some of the combination of the customers and since we only have like 10 beats for and since we only have like 10 beats for 10 customers so the total combinations 10 customers so the total combinations for these totals for these totals it's just like the what like this right to the one to the power uh basically to 10 to the power of 2 to the power of 10 which will be a 10 20 24 okay and we can simply brutal force combinations of combinations of of the of this beat mask and we can of the of this beat mask and we can pre-calculate pre-calculate the the total quantities we need for the the total quantities we need for for any for any for any for any of the any of the mask of the any of the mask with the with some given ones here right with the with some given ones here right that's why we have a mask here in the that's why we have a mask here in the in range of this in range of this m here right and then we can have like m here right and then we can have like so for each of the mask we simply just so for each of the mask we simply just do what we're do what we're going where we're supposed to do here we going where we're supposed to do here we simply simply loop through each bit and then we we check if that bit value is one so the way we're tracking it we simply do if the bitmask to end with the uh of this i here right if it's not empty if it's not zero then it's one okay yeah and then we just simply do a total dot mask right with the plus of the the quantity quantity of that for that customer right so that's well that's how we do a precalculation for any for any given mask and how many how many quantities quantities we need so that in here with each of the current ones the current mass with it means that the current what means that those are the customer again we're trying to trying to assign right if the totals often the current one if the totals often the current one right is right is equal smaller than the uh than the count equal smaller than the uh than the count of index right then we can we can try of index right then we can we can try our our dp here so we can try if now we our our dp here so we can try if now we can do a dp right can do a dp right the dp of index plus one right and then the dp of index plus one right and then we have a we have a oh here so oh here so okay so again right so since we are okay so again right so since we are going to set going to set we are going to assign the ones okay let's see this is the this is the current one which means that we're going to assign one with those two ones right with the with this kind of the current count so what's going to be the remaining bitwise the the mask so assuming this is our our original one so as you guys can see so if these two have become zero so the remaining one should be what should be zero zero zero zero and one zero one right which it means that we have already satisfied those two customers and the remaining tools are this are these two here here right and how can we do it that this is another bitwise manipulations here right it's just the mask right do a xor with the current one that's the uh that's how we got to get the other remaining one because x y means the uh if they are the same then it's zero it will be zero if they're different then it's one right so actually this one is the same as if you just you can simply do a mask minus current you will get same result because one minus one is zero and one minus one zero one minus 0 and this one if this one is true and and this one if this one is true and then we can simply return yep i think yep i think that's it otherwise that's it otherwise otherwise it will it will continue otherwise it will it will continue try the next subset try the next subset the next subset and then it will use the the next subset and then it will use the next subset to find the next subset to find the the total quantities that subset needs the total quantities that subset needs and then it will continue with this dp and then it will continue with this dp with the remaining ones right with the remaining ones right all right cool i think that's pretty all right cool i think that's pretty much it so let's try to run the code much it so let's try to run the code here oh i think i uh totals 39 line 39 oh okay i'm missing a highest here i think submit submit all right cool so it's success all right cool so it's success um yeah okay so how about time and space um yeah okay so how about time and space complexity right so complexity right so for the time complexity and you so we for the time complexity and you so we first we need to get to know the first we need to get to know the total state you know let's say we have a total state you know let's say we have a we have an n here right and then m so we have an n here right and then m so first one is the n right and then first one is the n right and then the second one is times the mass the the second one is times the mass the mass basically is a 2 to the mass basically is a 2 to the power of m right and power of m right and uh for each in and then inside of each uh for each in and then inside of each of the dp here of the dp here we're doing like a while loop here we're doing like a while loop here because we'll be we'll try because we'll be we'll try to get all the subsets so it's going to be the total of subsets okay and depending on here this will be okay and depending on here this will be a little bit a little bit complicated because depending on how complicated because depending on how many ones we have here right many ones we have here right because how many ones we have in this because how many ones we have in this state here we'll do another subset state here we'll do another subset based on those ones right it's going to based on those ones right it's going to be a subset to calculate subsets you know actually to calculate subsets you know actually so it turns out so it turns out oh by the way so this i believe this oh by the way so this i believe this time complexity analysis should be out time complexity analysis should be out of of this out of scope it'll be too hard so this out of scope it'll be too hard so it's going to be a it's going to be a n times 3 to the power of m so how do we get this you know basically if you really want to dig into it basically you know there's if you guys know the a plus b to the power of n so what's going to be the the value for that this is going to be the a to the power of n plus a combination right so the combination of of c l one and then we do a we do a power of n minus one b power of n minus one b plus c i think c n 2 plus c i think c n 2 of a to the power of n minus of a to the power of n minus n minus 2 right and then we have a b b n minus 2 right and then we have a b b square something like this and all the square something like this and all the way until to the end way until to the end to the b to the b times b to the power to the b to the b times b to the power of n and it turns out the way we're calculating the beat mask and the plus the way we're calculating the uh the subsets is is the same as this this formula here that that's why we can just that's why we can just convert this 2 to the power of m times times this subset which is 3 plus m turns out to be a 2 plus 1 times up to the power of n and yeah so that's it i know it's a of course so so that's gonna be the time of course so so that's gonna be the time complex and space complexity will be complex and space complexity will be this this time the state of this will be the end time the state of this will be the end times 2 to the power power out times 2 to the power power out of m right that's going to be the space of m right that's going to be the space complexity yeah because for this part it it's it's running it's a pre-processing that's why it's faster all right cool guys i think that's pretty much what it is i mean this problem you know the state you know to come up with the state shouldn't be that hard right but the difficulty for this problem is the uh after you have figured out the dp state here first thing first is that you know after using the current index even though there are like some numbers left for this current count we'll be discarding those those parts because we have tried all the possible subsets for this foot for this current for this current count even though there's not something we haven't assigned we we have already tried all the other scenarios that's why we can simply we can safely move forward so that so that for this dpu there's only that's only the two-state dp here so that's the first thing and second one is the uh how can we use the mask here then to efficiently get the next subset of a of a bead mask and after getting the subset and the third difficulties how can we fit and efficiently calculate the uh the total total quantities we need for the next subsets right and to do that we uh we do a preprocess and then we use one to represent we use the one the we use one to represent the the people the customer we're trying to satisfy next because the way this getting sub getting next subset works is by converting the ones into zero that's why we have to starting we have to start from all ones and then we end and that's why this one is a pretty hard and that's why this one is a pretty hard problem all right i guess i have talked problem all right i guess i have talked enough here i'll just stop all right enough here i'll just stop all right cool guys thank you so much cool guys thank you so much for watching this video stay tuned see for watching this video stay tuned see you guys soon you guys soon bye | 2024-03-19 18:33:56 | 1,655 | LeetCode 1655. Distribute Repeating Integers |
|
_GblcwHOHko | It is 200. Friends, today we have come to the shift question. Coin change and only 10 days are left to Coin change and only 10 days are left to divide into lines. There are more questions. It is divide into lines. There are more questions. It is simple and easy. It means that simple and easy. It means that how many points will it take for us to reach a particular how many points will it take for us to reach a particular amount. Look at the example. amount. Look at the example. Direct that I have a coin of one rupee, a Direct that I have a coin of one rupee, a coin of ₹10, a coin of five rupees, coin of ₹10, a coin of five rupees, then I have to make rs.11, otherwise what will we do, we will then I have to make rs.11, otherwise what will we do, we will eat ₹5, make it eat ₹5, make it ₹5, take two coins and ₹5, take two coins and insert it with one rupee, it is done. insert it with one rupee, it is done. insert it with one rupee, it is done. ignorant, how much will the total cost, the work was done in three shifts, look, I could have brought the output 11 also by making 11 of one, but we do not have to do this, we are being told the minimum, okay, so how many numbers and points will be required for the Great amount, this is the 11th Great amount, this is the 11th Great amount, this is the 11th example. See example. See what Mirwaiz can become. If these people are appointed in such a situation, if you want to get minus one more done, then see how they start the subscribe song in such a way that they accept the example as 12345. Give us the list and the total amount. In S capital it is to make the seventh, I have two religions, Giridih approach is ours, okay in the mind, Giridih means that the maximum one has taken five, okay for the effect, at what time two children, what to do, take one also Do you believe that Do you believe that Do you believe that how many will be learned with three points Chowkpur will be done and how many will be learned with three points Chowkpur will be done and then it will come again? Is it not in the minimum? then it will come again? Is it not in the minimum? That is the problem. The That is the problem. The answer to counter this is that after doing three news, Vid comes along answer to counter this is that after doing three news, Vid comes along and if it goes to coin only two later, and if it goes to coin only two later, then output two. then output two. then output two. reason why right answers from one, so our ready solution is not working, okay, what can we do, we can defend, we can try back, one of these is interesting, look at what we The project is The project is The project is that all four things are fine that all four things are fine 12345 12345 407 They are standing together Four approaches are 407 They are standing together Four approaches are that see ₹ 1 Make six Three make four that see ₹ 1 Make six Three make four 241322 Make ₹ 5 So make it okay Now do it like this and keep going Go 241322 Make ₹ 5 So make it okay Now do it like this and keep going Go keep going Let's do one from late keep going Let's do one from late keep going Let's do one from late part is that what questions come after two of the cases 1345 If we all see then you only tell me These three were native A lie will be given right - Vande 13 - 2 - You are also negative This is not allowed This is It is possible that if one of the two is removed then It is possible that if one of the two is removed then It is possible that if one of the two is removed then one is left or if each is added then one is left or if each is added then zero claw is finally sun, zero claw is finally sun, then in this way this is the possible solution of ours, then in this way this is the possible solution of ours, which was there, it is a support, not one which was there, it is a support, not one pair out of five, then one pair is pair out of five, then one pair is formed together that formed together that formed together that game like Sadhu, if you see one common thing, 1345 129, you will see that things are repeating, now look, I have six, last I did one thing, you child To To To make it, you have to put only ₹ 3, you will make it, you have to put only ₹ 3, you will put two left, 5010a, see, it will put two left, 5010a, see, it will repeat, it is repeat, it is repeating here, how can you do that, repeating here, how can you do that, you will go later, keep cashing, okay, now there you will go later, keep cashing, okay, now there is one child here, then one more. is one child here, then one more. is one child here, then one more. one, the bus time comes to zero, neither is it a possible approach, the approach is that this time the fifth in 501 is united again, even then it is closed that how many stairs have to be climbed after one turn, it is three, is So 123 5115 A Jury Karo is So 123 5115 A Jury Karo is So 123 5115 A Jury Karo is going to be the ultimate solution which will be our small going to be the ultimate solution which will be our small little one so if we like check here little one so if we like check here and hit the options and hit the options 12345 then by doing this it 12345 then by doing this it makes a pair of our four days with three and zero darkens the makes a pair of our four days with three and zero darkens the rest ahead. rest ahead. rest ahead. you repeat it. Here, by doing this, we can see what is the smallest. If you look at this three news and from the chart, you will see four births and three, what can we do with this method. We take the bottom approach. We did the bottom approach. Ghee is that always make it on through, we need money along with it, what do we do, keep using A DP, old or known DPO one, keep this in mind, 13 245 along with making above, 135 ash is 45, ₹1, so we have one, ₹ 2 is not there, if one ₹ 2 is not there, if one ₹ 2 is not there, if one can be used twice, you two have to listen, can be used twice, you two have to listen, how much money will be spent inside, how much will it be used to how much money will be spent inside, how much will it be used to play with, then race means two coins of one rupee will be required to play with, then race means two coins of one rupee will be required to make ₹ 2, then define how many will be make ₹ 2, then define how many will be taken, read 3 such things with me taken, read 3 such things with me DP and four will do the work for someone, just one coin will do the DP and four will do the work for someone, just one coin will do the work, DP and five or do 225 are work, DP and five or do 225 are left, so people do one DPO left, so people do one DPO 6, see how they are reaching, 6, see how they are reaching, which street, what to do, make two coins for the team which street, what to do, make two coins for the team We will give the work, we are looking at the minimum, keep in We will give the work, we are looking at the minimum, keep in mind mind that the DPO is with us, which is withdrawn in the account. By keeping the DPO with us, our approach seems to be that one deposit of DP off, keep something here, let's our approach seems to be that one deposit of DP off, keep something here, let's assume 6 from late, which assume 6 from late, which means deposit from ₹ 1. means deposit from ₹ 1. Now I have to withdraw ₹ 3. Now I have to withdraw ₹ 3. Two is fine. Three has arrived Two is fine. Three has arrived that the opponent has seen the DPO. Five can be seen. Well, it is that the opponent has seen the DPO. Five can be seen. Well, it is fine, that is, the work has been done with one, and that is, what are the options with me? Okay, so see this hot definition, what have I done, I put a coin of four rupees, know, after doing four likes, rest, basically, the amount that will come in here is - no one will come in, so If it is If it is If it is four, then DPO is four, how much is one four, then DPO is four, how much is one plus dip 4, I am one plus one, neither is it 421, nor plus dip 4, I am one plus one, neither is it 421, nor two, it means minimum is two, Simbu store two, it means minimum is two, Simbu store exam is DPO, if I know that along with four, I am exam is DPO, if I know that along with four, I am studying - I am left with three. studying - I am left with three. studying - I am left with three. 2018 Main itna one tu 21 aur kis can take that exam TDP and five kya hoga ah ok ok 17 banaye hai ki pachak it becomes investment na in English DPO is one of five There will be 6 There will be 6 There will be 6 and there will be four, so and there will be four, so according to what is available to us, my mother, according to what is available to us, my mother, how much is ours, only two are coming, how much is ours, only two are coming, right, you can do right, you can do one spoon DP off like this, one spoon DP off like this, two can Only we can know that Only we can know that Only we can know that one point of five rupees is five-five. Instead of five, we one point of five rupees is five-five. Instead of five, we took a coin, from here we took five and one coin, took a coin, from here we took five and one coin, so now our dip exam is done so now our dip exam is done with two more - how much is the dip of 22, tell me, if there are with two more - how much is the dip of 22, tell me, if there are two, then there is one spoon. two, then there is one spoon. two, then there is one spoon. is on this day, so would you like to have this five plus one, had he been born so or two, he had told here, this is what we are going to use while coding, this is simple water, is it okay, If If If we are going to use Deepika, then we are going to use Deepika, then I take DP here. Initially, what we I take DP here. Initially, what we do is that the amount is as much as do is that the amount is as much as I told you, as if we were taking it to the city, we I told you, as if we were taking it to the city, we make it there and make it there and how much is there inside it. how much is there inside it. Meaning, as we say, we Meaning, as we say, we can also take these final numbers because we want maximum, we want to make minimum. can also take these final numbers because we want maximum, we want to make minimum. Look, if I Look, if I zoom from inside this, then some bad thing will happen, isn't it? zoom from inside this, then some bad thing will happen, isn't it? Actually, here we have made it plus Actually, here we have made it plus 1898. is nothing like verification, so whatever is more than the maximum expressed amount inside all of us is not much, that's is more than the maximum expressed amount inside all of us is not much, that's why they are so what will you do, we so what will you do, we go in these vans, from the forest to where actually. go in these vans, from the forest to where actually. In the bottom approach, it goes from zero to In the bottom approach, it goes from zero to up, otherwise we will take zero, now we will up, otherwise we will take zero, now we will do 1234, so from one to the do 1234, so from one to the amount plus one, so in the bottom approach, amount plus one, so in the bottom approach, we will go from six to five, from we will go from six to five, from one to two to three. one to two to three. one to two to three. this was the crotch, now we will hold each point, took the sequence in points, if only - C, understand the amount, learn from - do and that great daily 120 is coming, this is our K is correct na means negative does not come. This means our help and in using this read, the amount will be known only then I will know what we do, what do we take from DGP of A, what is the minimum of our own DP and Swayam and OnePlus. DP off that this DP off that this DP off that this - this is what I was doing in front of you, when - this is what I was doing in front of you, when I look at this brinjal, I look at this brinjal, it came because of the skin, it has been planted by someone, isn't it ours, now it came because of the skin, it has been planted by someone, isn't it ours, now it has been planted, so apart from this, the rest of the children will it has been planted, so apart from this, the rest of the children will also have to be seen, I know. also have to be seen, I know. I put 500ml coin of five rupees and I put 500ml coin of five rupees and then to make it with DPO, I will then to make it with DPO, I will have to see with it - It is positive, have to see with it - It is positive, whichever is the minimum, if you want to catch the minimum, whichever is the minimum, if you want to catch the minimum, then you will catch the minimum. What will be the final then you will catch the minimum. What will be the final return from this? return from this? return from this? amount of DPO that amount of DPO that I have come. If this does not happen, it I have come. If this does not happen, it means that the amount of DPO cannot be changed means that the amount of DPO cannot be changed because I had written it below and was also because I had written it below and was also putting it and had kept it aside. If I write the amount plus putting it and had kept it aside. If I write the amount plus one, one, then if the amount is there but it was not there. then if the amount is there but it was not there. then if the amount is there but it was not there. diploma then it means that we take such a case that is minus one then submit it, let's run it, Wally, someone else, this was our mount to see, friend, I actually changed the swelling in the beginning but then did There is There is There is no gap between them, has it been accepted? Let's see, there comes a time when you say no, ok, success has been achieved and this is our code, so did you understand it, how did you get rid of Tell me in the comments and Tell me in the comments and Tell me in the comments and to follow them, you can also see the code in the description, to follow them, you can also see the code in the description, Haldi, nothing is happening in the next video, Haldi, nothing is happening in the next video, subscribe. | 2024-03-24 10:28:39 | 322 | Leetcode 322. Coin Change. Python (Greedy? vs DP?) |
|
vJa15g4m-IM | Hello welcome back to Anonymous Data Scientist today we will discuss lead code problem today we will discuss lead code problem number 225 which is implement stack using number 225 which is implement stack using queues now before discussing it we should queues now before discussing it we should know the basic properties of stacks and queues know the basic properties of stacks and queues in stack LIFO is used that is in stack LIFO is used that is last in first last in first out out out inside the stack and then inserted four, so if we remove an element from the stack from here, then first we will remove element four and then remove three, this will be last in first He will come out first, He will come out first, He will come out first, what happens in Ku, the what happens in Ku, the opposite is true in Q, suppose we have entered element opposite is true in Q, suppose we have entered element three, then we have entered element four, so three, then we have entered element four, so here we use FIFO, that is first here we use FIFO, that is first in, first out, whoever goes in first will in, first out, whoever goes in first will come first, so if come first, so if come first, so if then first it will come three times and then after that four will come, so we just have to use the properties of leaf and FIFO, inside this we have to implement it here, we have to implement stack using Q. So let's look at the question. In bar question, they have just defined the basic terms: push means inserting an element into the stack, pop means removing an element and returning the top element and top function will return the empty element which is the top element and Or not, Or not, Or not, now like what is there in the example given in the question, now like what is there in the example given in the question, first we first we pushed one into the stack, that means we pushed element one into the stack, then pushed one into the stack, that means we pushed element one into the stack, then came push two, then came push two, then we pushed element two into the stack and then we pushed element two into the stack and then After we made top, now After we made top, now what will top do, will the element return to us what will top do, will the element return to us and then we applied the operation of pop, so and then we applied the operation of pop, so what will happen in this, it will return the element what will happen in this, it will return the element and will also remove the top element and will also remove the top element from the stack, so we pass this left in the last, now it from the stack, so we pass this left in the last, now it is applying my is applying my is applying my is non MT, so this is just some basic operation, now let us see how we will approach this question, once now we have to implement this stack using Q. Now see how we can do it. Suppose we have Kya which has elements inside it 3 four and f Okay now if we remove the element from here then the first element to be removed will be - but what we need is we have to The The The element will be returned, so we need ultimately five elements, so now how will we do it, need ultimately five elements, so now how will we do it, what we will do here is to put a for loop what we will do here is to put a for loop and apply whatever pop function, whatever and apply whatever pop function, whatever removal function, we will remove that element and removal function, we will remove that element and store it in another queue like Here it was removed by the function of pop, so we placed the letter here, now again we applied the function of removal, so the four was removed, the four was placed here, now the last element left like y but f is left, what will we do with it by returning it. We will return the element number five We will return the element number five because this is what would be returned inside the stack. because this is what would be returned inside the stack. Now suppose we had a stack Now suppose we had a stack four f. If we removed the element from here, we would have removed f, then similarly we did the same thing, we just added one After creating a queue and whatever pop elements are being created, for After creating a queue and whatever pop elements are being created, for After creating a queue and whatever pop elements are being created, for example, if we apply a loop from inside the queue, then example, if we apply a loop from inside the queue, then we will take the length of the queue and by taking we will take the length of the queue and by taking minus one from it, all the further elements will be stored in minus one from it, all the further elements will be stored in one place one place and the last element will be and the last element will be left. left. left. do it in the code, let us see how to code it, now it will be more clear to you in the code, define a double ended q define a double ended q like self d k into d k d. like self d k into d k d. like self d k into d k d. ended, why is it okay and then what we will do after that is that we will define our push operation, what we will do in push is the empty self dot K, we will append it to whatever element X is, we will This This This function is just in it, we have to run the whole game which we had function is just in it, we have to run the whole game which we had discussed, we have to run the loop till we have to run the for i discussed, we have to run the loop till we have to run the for i in in range as long as the length of which is range as long as the length of which is one one less length of side than that, less length of side than that, we have to run it till there and we have to run it till there and store it inside the new queue. store it inside the new queue. apply push operation, self dot apply push operation, self dot push and where will the elements come from, self dot kdot push and where will the elements come from, self dot kdot pop left, so what will happen with this is that whatever is the left most element, it will come out from our first queue and that will be our second. Inside why, this will work up to the length minus w and we will return the element left in the last and how will return self dot k dot pop left, now we have to define the function top, now to define top, do simple return. We have to return self dot k my man because last element we have to check whether it is MT or not we will put bullion for MT return length self dot k is equal to 0 if it is equal to zero then true otherwise false by Let's see the - 1. Okay, here you keep in mind that these - 1. Okay, here you keep in mind that these brackets will be used, this is done here, submit it, so if you have any doubt, then you can You can ask in the section till You can ask in the section till You can ask in the section till see you in the next video thank | 2024-03-22 11:00:08 | 225 | LeetCode 225 - Implement Stack using Queues | LeetCode in Python | DSA | Anonymous Data Scientist |
|
GLTskY7KehU | [Music] hey guys welcome back to another video hey guys welcome back to another video and today we're going to be following and today we're going to be following the lead code question jump game three the lead code question jump game three all right so in this question we're all right so in this question we're given an array of non-negative integer given an array of non-negative integer uh integers air you are initially uh integers air you are initially positioned at start index so start over positioned at start index so start over here is an here is an index of the array when you are at index of the array when you are at index i you have one of two options so index i you have one of two options so one of the options you have one of the options you have is to jump to i plus whatever the value is to jump to i plus whatever the value is is at that current index and the other at that current index and the other option is to jump option is to jump to i minus whatever the value is at to i minus whatever the value is at that certain index check if you can that certain index check if you can reach to any index with value so reach to any index with value so notice that you cannot jump outside of notice that you cannot jump outside of the area at any time the area at any time okay so we cannot jump outside the area okay so we cannot jump outside the area okay so let's just look at a quick okay so let's just look at a quick example over here so over here we have example over here so over here we have this out this out of area and our start is five so of area and our start is five so five refers to the index so let's go to five refers to the index so let's go to index five index five zero one two three four and this is zero one two three four and this is index five okay index five okay so we will be starting right over there so we will be starting right over there so now we have one of two so now we have one of two options we can move to the right by one options we can move to the right by one so that would give us so that would give us over here or we could move to the left over here or we could move to the left by one right by one right and why do we know that we're moving by and why do we know that we're moving by one and the reason for that is because one and the reason for that is because over here we have a one so that means we over here we have a one so that means we can move in either direction by one can move in either direction by one okay so uh the question itself isn't too okay so uh the question itself isn't too hard uh i would encourage that you go hard uh i would encourage that you go through this entire example through this entire example and again our stopping point is when we and again our stopping point is when we end up reaching a zero end up reaching a zero okay so i'll just draw it out and uh the okay so i'll just draw it out and uh the question should be pretty simple to question should be pretty simple to solve solve okay so real quickly uh in this question okay so real quickly uh in this question we could actually represent we could actually represent our steps in terms of a tree so how our steps in terms of a tree so how exactly would our tree look like exactly would our tree look like so over here we would have our root node so over here we would have our root node and the root node over here is going to and the root node over here is going to be nothing else be nothing else but our stark value okay and after this but our stark value okay and after this we would have one of two options and the we would have one of two options and the two options two options are pretty simple we can either go left are pretty simple we can either go left so if we go left we would take that path so if we go left we would take that path or we could end up going right so those or we could end up going right so those are really our two paths are really our two paths okay and once we go left we would be at okay and once we go left we would be at a current value and further down from a current value and further down from there you there you again have the same two options left or again have the same two options left or right so you can kind of imagine right so you can kind of imagine how this is going to kind of form a tree how this is going to kind of form a tree based data structure based data structure and even without looking at that you and even without looking at that you could kind of come to that conclusion could kind of come to that conclusion pretty easily because pretty easily because we only have two specific uh specific we only have two specific uh specific options options and uh so let's just look at an example and uh so let's just look at an example here so we have one here so we have one so we could go one to the right or we so we could go one to the right or we could go one to the left could go one to the left now the only thing that we really need now the only thing that we really need to take care for is the base condition to take care for is the base condition which is which is uh we cannot exceed um any of the uh we cannot exceed um any of the indices okay so that means that indices okay so that means that we cannot uh exceed whatever this index we cannot uh exceed whatever this index is right is right so we cannot have an index which has the so we cannot have an index which has the same value as the length of our area so same value as the length of our area so that's one condition that's one condition and the other is that it cannot be and the other is that it cannot be smaller than zero so this over here is smaller than zero so this over here is the smallest okay the smallest okay so that's one condition we need to make so that's one condition we need to make sure that our index is in the range of sure that our index is in the range of uh uh zero and uh all the way up to the length zero and uh all the way up to the length of our area of our area so that's one condition and what exactly so that's one condition and what exactly is going to be the second condition so is going to be the second condition so the second thing really isn't a the second thing really isn't a condition but condition but it's more of an observation that we want it's more of an observation that we want to make so over here um to make so over here um i so let's say so you go to the left i so let's say so you go to the left over here or you can go to the right so over here or you can go to the right so those are those are our two options now once we go to two we our two options now once we go to two we actually cannot go to the actually cannot go to the right anymore because we are at the right anymore because we are at the ending so let's say we go to the left ending so let's say we go to the left so when you go to the left of two so one so when you go to the left of two so one two two you would end up over here at three so you would end up over here at three so one thing that we want to notice one thing that we want to notice is once we actually go to a certain is once we actually go to a certain index then in that case we don't need to index then in that case we don't need to visit it visit it again so why exactly are we doing that again so why exactly are we doing that so in this case so in this case so at the ending of the question all we so at the ending of the question all we need to kind of uh respond or sorry need to kind of uh respond or sorry output is either going to be a true output is either going to be a true value or a false value we don't care value or a false value we don't care about what the path is about what the path is we just want to return true or false and we just want to return true or false and keeping that in mind keeping that in mind if we already visit a node so in this if we already visit a node so in this case we're already case we're already visiting three so what that means is visiting three so what that means is that we're gonna continue the steps so that we're gonna continue the steps so what are our two options at three so we what are our two options at three so we could go to left by three so could go to left by three so one two and three it will put us over one two and three it will put us over here and so on and so forth right here and so on and so forth right so once you actually end up doing those so once you actually end up doing those uh calculations uh calculations you do not have to do it another time so you do not have to do it another time so the basic idea the basic idea is uh once i already visit a certain is uh once i already visit a certain index index and if i did not output true uh by the and if i did not output true uh by the ending of it right ending of it right so if i visit three and go to all of its so if i visit three and go to all of its possibilities possibilities and if i still don't end up outputting and if i still don't end up outputting true that means even the next time or true that means even the next time or how many other times further on how many other times further on i come across three i will never ever i come across three i will never ever uh get an answer of true right so uh get an answer of true right so keeping that in mind we're gonna have keeping that in mind we're gonna have some sort of cache some sort of cache which is gonna tell us all the nodes which is gonna tell us all the nodes that we have visited that we have visited and uh if we have visited a certain node and uh if we have visited a certain node then in that case we're directly going then in that case we're directly going to return false because to return false because that means that we do not have an answer that means that we do not have an answer at that certain path okay at that certain path okay all right so since it is a tree uh we all right so since it is a tree uh we could take one of two approaches which could take one of two approaches which is either a bfs approach is either a bfs approach or a dfs approach and for this question or a dfs approach and for this question i'll just be using a breadth first i'll just be using a breadth first search okay bfs search okay bfs okay so let's start off by initializing okay so let's start off by initializing our queue so the cue that we're going to our queue so the cue that we're going to be using be using is going to be from collection so is going to be from collection so collections.dq collections.dq so we have the cube ready for us and so we have the cube ready for us and what is the first value in our queue what is the first value in our queue going to be going to be so the first value is going to be the so the first value is going to be the start value start value so we're just going to add that to our q so we're just going to add that to our q in the very beginning in the very beginning now another thing that we want to now another thing that we want to initialize is going to be our cache initialize is going to be our cache so our cache over here we're going to so our cache over here we're going to use a set in order to represent it use a set in order to represent it and we all have all of them defined for and we all have all of them defined for us us okay so now what we're going to do is okay so now what we're going to do is we're going to go inside of a while we're going to go inside of a while statement so we're going to do wild cue statement so we're going to do wild cue and and basically what that means is we're going basically what that means is we're going to keep going until we have to keep going until we have something in our queue so now the first something in our queue so now the first thing that we want to do is we want to thing that we want to do is we want to get the current index we're on get the current index we're on and to do that we're going to do q dot and to do that we're going to do q dot pop left okay pop left okay that just pops out whatever is at the that just pops out whatever is at the zero index so in this case we're getting zero index so in this case we're getting whatever that value is and we whatever that value is and we store that inside of index so over here store that inside of index so over here our first thing is we're going to check our first thing is we're going to check if whatever value is at that index if whatever value is at that index is equal to zero so if it is equal to is equal to zero so if it is equal to zero that means we're done we can just zero that means we're done we can just directly end up returning true directly end up returning true we're done we solve the question nothing we're done we solve the question nothing to do right but if we do not to do right but if we do not actually have a value of zero that means actually have a value of zero that means we want to look at the other we want to look at the other possibilities possibilities so what exactly are the two so what exactly are the two possibilities so over here possibilities so over here we have one of two possibilities and one we have one of two possibilities and one of this of this one of them is we can go left and the one of them is we can go left and the other one is that we can go other one is that we can go right okay so we can go left or go right right okay so we can go left or go right perfect okay so uh let's just code out perfect okay so uh let's just code out both of these possibilities and both of these possibilities and uh what i'm going to do is i'm just uh what i'm going to do is i'm just going to put them inside of a for loop going to put them inside of a for loop instead of repeating instead of repeating the same steps two times okay so what the same steps two times okay so what exactly are the two possibilities so exactly are the two possibilities so let's start off when we can go to the let's start off when we can go to the fridge fridge so if you want to go to our right it's so if you want to go to our right it's going to be our current going to be our current index plus whatever value is at that index plus whatever value is at that index so to do that we're going to do index so to do that we're going to do array and then index okay so that is for array and then index okay so that is for going to the right going to the right and we also want to get what happens and we also want to get what happens when we go to the left when we go to the left so when we're going to the left it's so when we're going to the left it's going to be our current index going to be our current index minus the whatever value is inside of minus the whatever value is inside of the area the area at that index so now we're going to put at that index so now we're going to put these both inside of a for loop so let's these both inside of a for loop so let's just before x just before x in that so now we're going to get both in that so now we're going to get both of these indices each time of these indices each time and first we actually want to check and first we actually want to check whether this index is valid or not whether this index is valid or not and the conditions for that is we have and the conditions for that is we have two conditions right so one of them is two conditions right so one of them is is it inside of our boundary so let's is it inside of our boundary so let's just do that so our x value just do that so our x value has to be greater than or equal to x and has to be greater than or equal to x and that value that value also has to be less than the length of also has to be less than the length of our our area okay so that's one of the area okay so that's one of the conditions and we have another condition conditions and we have another condition which is the x value over here should which is the x value over here should not be not be inside of cap inside of our cash so not inside of cap inside of our cash so not in cash so that means that we did not in cash so that means that we did not see the value yet and see the value yet and hence there is a possibility that this hence there is a possibility that this value could be true value could be true and again if we did see the value again and again if we did see the value again and we did not end up returning true at and we did not end up returning true at that point of time that point of time that means even this time is the same that means even this time is the same thing going to happen and we there's no thing going to happen and we there's no point point in repeating the same step again okay so in repeating the same step again okay so now we want to do two things right so now we want to do two things right so one of them is appending it one of them is appending it to our queue so what are we going to to our queue so what are we going to append well we're going to append the x append well we're going to append the x value over here value over here and now we want to add whatever index we and now we want to add whatever index we are currently on are currently on to our uh uh cash right to our uh uh cash right so to do that we're going to do cash so to do that we're going to do cash sorry um cash sorry um cash dot add and the value that we're going dot add and the value that we're going to be adding is whatever to be adding is whatever index we are currently on so this should index we are currently on so this should be it for our solution and finally be it for our solution and finally if we actually don't end up returning if we actually don't end up returning true even after trying all the true even after trying all the possibilities possibilities we're going to return false okay so over we're going to return false okay so over here i think this is going to take here i think this is going to take big o of n time because since we are big o of n time because since we are keeping a track of a keeping a track of a cache uh what's going to happen is we're cache uh what's going to happen is we're never going to visit a certain index never going to visit a certain index more than one time so yeah so yeah that more than one time so yeah so yeah that should be it should be it let's submit it and yeah thanks a lot let's submit it and yeah thanks a lot for watching guys do let me know if you for watching guys do let me know if you have any questions have any questions and don't forget to like and subscribe and don't forget to like and subscribe thank you thank you [Music] | 2024-03-20 11:55:07 | 1,306 | Jump Game III | Leet code 1306 | Theory explained + Python code |
|
Jvueu1N0Nio | If you haven't subscribed today's video is Scotland ice cream 94 young people on the table Mini Scotland ice cream 94 young people on the table Mini Garden kilometer cola kinaf Apple and Garden kilometer cola kinaf Apple and Samsung's new color is necessary punishment two Samsung's new color is necessary punishment two of them epilation direct region million of them epilation direct region million fish Yes no we will sing to you your fish Yes no we will sing to you your hairstyle Heart goods We also two hairstyle Heart goods We also two Hocaoglu when did we talk come here dear Hocaoglu when did we talk come here dear You took it out for the moment Adar Karadeniz You took it out for the moment Adar Karadeniz video interesting comes out at the point module first video interesting comes out at the point module first 100 mat.lipstick ita car for example two Yunus 100 mat.lipstick ita car for example two Yunus One subtraction table School By the way One subtraction table School By the way the results of modeling is gone the results of modeling is gone model sport these days fly Look at this dad The model sport these days fly Look at this dad The song to you is the address in the figure Bolu part song to you is the address in the figure Bolu part Is it the old one? Isn't it the Center? After we don't have this, the thought is where are the 10 examples? The new tenant, but then it was made in the region and the 6 conditions every day, every day, the happiness of Terme, these models, write down, take it to the doctor, I didn't take it. What happened? Mount Normally, we also gave Bitte, but the subtitle is important information, times are over, we start directly LOL For example, there is no contract at home, it's For example, there is no contract at home, it's For example, there is no contract at home, it's like if this passenger tries so hard, like if this passenger tries so hard, I'll go all of it, it's as much as my son, let's I'll go all of it, it's as much as my son, let's drive to Kentucky, the photo is in the state of emergency, if I drive to Kentucky, the photo is in the state of emergency, if I don't get it, anyway, I'm leaving the message, but the don't get it, anyway, I'm leaving the message, but the end is 12g, there end is 12g, there are 12 of them from the 52 address for today, other than that, he are 12 of them from the 52 address for today, other than that, he left it aside, it's over, it's a returning one. left it aside, it's over, it's a returning one. left it aside, it's over, it's a returning one. the bag is a little bit, he looks. So, what are we, for example, I liked this very much, because we are talking about Kerim outside of trimo, he found it unfair, then if there is a small one, send it, do not steal it with torments, then if there is a small one, send it, do not steal it with torments, some spilled Yes, for example, our Satı some spilled Yes, for example, our Satı is early, now the number is in these services, I got is early, now the number is in these services, I got perimetry flow, let's sleep today in perimetry flow, let's sleep today in your father's taxi episode, Neşet your father's taxi episode, Neşet Abalıoğlu, our sister, be careful, because I will teach me this Abalıoğlu, our sister, be careful, because I will teach me this whole cable tomorrow, it whole cable tomorrow, it is okay, it is the word. You, your system, your group, is is okay, it is the word. You, your system, your group, is not enough for us? For this, come to Malatya, let the models of Berk elements burn, I will show you where the qiku cream we installed, do not write the models on the face of the elements, innovations with you are not modules. Because we talk about it with cheese with illogical orange transfers, then show it, say good morning sometimes, we have fish, Choco words, the two we met for this, one branch smells on us, but the virus is rocky, for the first time in the year, the water is a little bit twice over, our model is over, the second one is over, we are all done, are we hearted ? ? ? crow solves it, it is not a model next to it, the model is as difficult as the mini What are you going to do? We deleted this tomorrow from here first. Dude, is this product formula above? What does it mean that they are Barca? Is it the same after 8k? model code then the head is one So I'm doing this tomorrow okay we are logging in are there those who can enter the work we can join you this is the two of us our health people e-mail Niğde 30-40 enos bring one exc-500 what do we need together his student is exposed in front of me buy me wow wow 12 of course Mustafa Burak 12 of course Mustafa Burak came from this and that flower came, I was wrong, I will finish came from this and that flower came, I was wrong, I will finish them, they are gone and K look at the good news, them, they are gone and K look at the good news, how I also if that's enough hand how I also if that's enough hand cables, Rufus, force wife, Quran, hanneck, princess, truth, head, not to mention the voices, funny with you, for cheap composite for cheap composite for cheap composite mean adult threw I also what is this I mean adult threw I also what is this I Complex Hello express Complex Hello express 2000's winpower we so Worst Darıca 2000's winpower we so Worst Darıca start what does it mean when the card was over when there was another start what does it mean when the card was over when there was another came this frog nice ends what does this world came this frog nice ends what does this world mean this proof q We actually mean this proof q We actually have En ge-ec have En ge-ec have En ge-ec this resistance, when we wear the jersey, this green mark has reached our horse. These are the water of duality, that is, I will go exactly like that [Music] meat news is coming to an end, we are blessed to say that after the union, we are now working, how are you? If we can detect the fast perimeter debt 3D texts of Elif, this is a clean card. Normally, If we can detect the fast perimeter debt 3D texts of Elif, this is a clean card. Normally, whoever makes this heart, it is love to travel, whoever makes this heart, it is love to travel, renewal is one of these elements. It is against the renewal is one of these elements. It is against the principle of asking the Ulgen tire and then Secret. principle of asking the Ulgen tire and then Secret. But where is this? Yunuslar Yunuslar sports Nova 15 lira 15 Instagram if we are sports Nova 15 lira 15 Instagram if we are wearing clothes, if we are wearing clothes, if we are going to the concert, 10.15 wound Nilay, we have the going to the concert, 10.15 wound Nilay, we have the melody expression most her lokumlu cake meybuz melody expression most her lokumlu cake meybuz Because direct 115 cinema Then Because direct 115 cinema Then it is tubicoat adolescent 15/0 So if it is tubicoat adolescent 15/0 So if we are collecting correctly 15yt we are collecting correctly 15yt rakübühm 10-15 rakübühm 10-15 rakübühm 10-15 photo how okay full of drama if you forgot his head is heart there is self crites mean we got in the middle ten days one this Nestle King real Game what does it mean if it is not comfortable middle 5.50 afraid them Samet we have two Well our upper country this I went deputy both please coming Sprouts girl Love let it go What is it girl Love let it go What is it girl Love let it go What is it directly in appalas Hospital Because it directly in appalas Hospital Because it pulls enough but to come rocket pulls enough but to come rocket we do all the pacifier Love attack if I wasn't this is the first thing that comes Camera for it's over so it's striking what Camp let's put it on here you forgive me While I'm nice from this when I put it on the most left-right here Bring me closer to If we are sick, it is special for us to end up with a teratori director, I mean ratem girl, what is this West, what is the right way, we have the seat, sometimes the results of the tests, our doctor is after 90, so it was not easy, I said, if they don't give me the music, look, what is the line for now, this is an exemplary A Car, wait, 356 musical, it A Car, wait, 356 musical, it A Car, wait, 356 musical, it means the second inside us, it was hung on our arrival, 32 music, Gulen, what is the difference, guess what? This is a children's video | 2024-03-25 13:41:57 | 1,954 | 1954. Minimum Garden Perimeter to Collect Enough Apples - LeetCode |
|
zv__otbvUEY | hi guys good morning welcome back to the new video so in this video we're going new video so in this video we're going to see the problem last moment before to see the problem last moment before all the ants fall out of blank if you all the ants fall out of blank if you had not watched it we had already had not watched it we had already discussed in our live weekly contest discussed in our live weekly contest problem discussions and not only this problem discussions and not only this but also some variations of these kind but also some variations of these kind of ant Collision problems so if you want of ant Collision problems so if you want you can do subscribe we also bring in you can do subscribe we also bring in live contest discussions cool and the live contest discussions cool and the problem is asked by Google itself and problem is asked by Google itself and like not much frequently but still uh it like not much frequently but still uh it just says let's see what the problem just says let's see what the problem says it just says that we have a wooden says it just says that we have a wooden plank of the length of n units now in plank of the length of n units now in this n units uh some ARS are walking on this n units uh some ARS are walking on the plank and each anunt move with a the plank and each anunt move with a speed of 1 unit per second cool it's speed of 1 unit per second cool it's just a speed and one ant is moving one just a speed and one ant is moving one unit per uh second now when two arms unit per uh second now when two arms moving in two different directions meet moving in two different directions meet at some point and it can only happen at some point and it can only happen when the two arms are coming close when the two arms are coming close towards each other right if two arms are towards each other right if two arms are moving it can be two possibilities moving it can be two possibilities either they are moving in the opposite either they are moving in the opposite direction or in the same direction if in direction or in the same direction if in the same direction then only they can the same direction then only they can Collide else they will not Collide so Collide else they will not Collide so simply they are actually moving in the simply they are actually moving in the same direction so they will actually same direction so they will actually have a collision they change their have a collision they change their directions and continue moving again directions and continue moving again again when they Collide they just have a again when they Collide they just have a collision such that they just change the collision such that they just change the direction and continue moving back again direction and continue moving back again asuming the direction change does not asuming the direction change does not take any time and it's just instant now take any time and it's just instant now when an AR reaches one end of the plank when an AR reaches one end of the plank at a time T it falls out of the plank at a time T it falls out of the plank immediately so plank is of limited immediately so plank is of limited length it is actually length n if it length it is actually length n if it like reaches at the point of time T so like reaches at the point of time T so it just falls off that plank we have an it just falls off that plank we have an integer n we have two integers left and integer n we have two integers left and right just saying okay left integer say right just saying okay left integer say ant is moving in the direction of ant is moving in the direction of left uh and integer right is saying left uh and integer right is saying which means this like as you can see which means this like as you can see these are these two ARS are moving left these are these two ARS are moving left so in my integer of left I will have a so in my integer of left I will have a three and a four four and these two arms three and a four four and these two arms are moving right so my integer will have are moving right so my integer will have a zero and one for moving right now I a zero and one for moving right now I just have to tell at what moment when just have to tell at what moment when the an last AR fall out of the blank the an last AR fall out of the blank which is the last moment when the ANS which is the last moment when the ANS fall out of this blank fall out of this blank so while viewing this problem it might so while viewing this problem it might look a bit intimidating okay are there look a bit intimidating okay are there are too many ants let's say to AR are too many ants let's say to AR Collide here then uh what about the Collide here then uh what about the other collisions for example in this other collisions for example in this problem itself you will see these two AR problem itself you will see these two AR will come these two will Collide so B will come these two will Collide so B and C collided direction of B changed and C collided direction of B changed direction of C changed but you will see direction of C changed but you will see that A and B will collide and also C and that A and B will collide and also C and D will collide again uh direction of B D will collide again uh direction of B will change direction of a will change will change direction of a will change direction of C again change direction of direction of C again change direction of D again changed now direction of A and D D again changed now direction of A and D will remain like this only but b and c will remain like this only but b and c will again Collide B and C again Collide will again Collide B and C again Collide again their direction will change and again their direction will change and again all of them will going on keep on again all of them will going on keep on going forward so it might look up been going forward so it might look up been intimidating that okay there can be too intimidating that okay there can be too much collisions how to handle that but much collisions how to handle that but if we look on very carefully just a if we look on very carefully just a smaller problem what if I had just two smaller problem what if I had just two auns so if I had only two aunts Aunt a auns so if I had only two aunts Aunt a Aunt B they are coming towards each Aunt B they are coming towards each other for sure I'm just checking other for sure I'm just checking Collision will only happen when they're Collision will only happen when they're coming towards each other so at the next coming towards each other so at the next moment what will happen is a and b will moment what will happen is a and b will come very close to each other just about come very close to each other just about a collision now although in the next a collision now although in the next state directly it will reach to a point state directly it will reach to a point where both the ants will actually be in where both the ants will actually be in the opposite direction but let's happen the opposite direction but let's happen let's see what happened in between in in let's see what happened in between in in between Aunt a would actually been in between Aunt a would actually been in the mid and B would actually also be in the mid and B would actually also be in the mid but facing like this only as the mid but facing like this only as soon as they were actually colliding soon as they were actually colliding they collided and both of them changed they collided and both of them changed their Direction in the mid only mid of their Direction in the mid only mid of this particular space and as they this particular space and as they changed they again start had to start changed they again start had to start moving backwards so you saw that Aunt a moving backwards so you saw that Aunt a Aunt B were coming close towards each Aunt B were coming close towards each other they collided and they started other they collided and they started moving moving backwards in this if you see here I just backwards in this if you see here I just mentioned and a an B what if I just mentioned and a an B what if I just don't even mention a a Aunt B I don't don't even mention a a Aunt B I don't mention anything I don't mention mention anything I don't mention anything so can't you just if you had to anything so can't you just if you had to visualize from from point A to point B visualize from from point A to point B can't you just uh see like point a point can't you just uh see like point a point 1 to point 2 if you just want to 1 to point 2 if you just want to visualize that can't you say that this visualize that can't you say that this AR next location is this itself if I AR next location is this itself if I imagine this Aunt this Aunt right here imagine this Aunt this Aunt right here would not have been here at all so for would not have been here at all so for sure the Aunt B would have been here and sure the Aunt B would have been here and considering this Aunt this Aunt B would considering this Aunt this Aunt B would not have been here so Aunt a is actually not have been here so Aunt a is actually at this location itself so if and for me at this location itself so if and for me every aunt is same right so I can just every aunt is same right so I can just imagine Aunt can assume there is no one imagine Aunt can assume there is no one in front of it and it can just keep on in front of it and it can just keep on moving forward and that is the entire moving forward and that is the entire for this problem that I can just for this problem that I can just visualize that ant as it never collided visualize that ant as it never collided it just kept on moving forward this ant it just kept on moving forward this ant B it kept on moving forward and this is B it kept on moving forward and this is ultimately what will happen so what ultimately what will happen so what we'll do is we'll just simply have all we'll do is we'll just simply have all the ANS with us all the ANS with us the ANS with us all the ANS with us we'll just keep on moving this AR we'll just keep on moving this AR forward forward forward and we'll just forward forward forward and we'll just keep on colliding so it will have three keep on colliding so it will have three units until it it collides this ant will units until it it collides this ant will have until it falls out it this ant will have until it falls out it this ant will have have 4 units until it falls out now for this 4 units until it falls out now for this ant it will have again three units which ant it will have again three units which is 4 - 1 three units until it falls out is 4 - 1 three units until it falls out this AR again will have four units until this AR again will have four units until it falls out so maximum time is four it falls out so maximum time is four units until all the ARs will be out of units until all the ARs will be out of this particular plank so last moment this particular plank so last moment when the arms fall out of the plank it's when the arms fall out of the plank it's actually four and that's how you can actually four and that's how you can simply get this answer solve without simply get this answer solve without considering any other cisions let's considering any other cisions let's quickly get this code done uh as you you quickly get this code done uh as you you saw that it would be pretty easy saw that it would be pretty easy considering that how we generalized and considering that how we generalized and formalized the final output now let's formalized the final output now let's say that uh um what's the variable name say that uh um what's the variable name so last M let's say last M M M okay um so last M let's say last M M M okay um now I just simply go on to all of my now I just simply go on to all of my lefts for auto l in left and I can just lefts for auto l in left and I can just say okay my last M movement say okay my last M movement is actually a maximum of last moment is actually a maximum of last moment comma this particular L because I know comma this particular L because I know one thing for sure if AR is moving like one thing for sure if AR is moving like AR at location three uh as you saw here AR at location three uh as you saw here uh so it will just move three steps so uh so it will just move three steps so it's it's l will actually uh help me out it's it's l will actually uh help me out with everything so four and three I just with everything so four and three I just have the maximum value I needed now the have the maximum value I needed now the same I will just simply go for right now same I will just simply go for right now for right just simply the same thing for right just simply the same thing that um just simply copy this over and that um just simply copy this over and the maximum of again last moment comma the maximum of again last moment comma it's just that right if we are moving so it's just that right if we are moving so we know okay r n is the last location so we know okay r n is the last location so n minus r uh would be the distance up to n minus r uh would be the distance up to the right so that is I can simply return the right so that is I can simply return my last movement and that would be my my last movement and that would be my answer let's quickly check this out so answer let's quickly check this out so that the only thing was for that the only thing was for okay um so the only thing in this okay um so the only thing in this problem was just to figure out that how problem was just to figure out that how to check if the ANS are colliding with to check if the ANS are colliding with each other so how they are happening so each other so how they are happening so yeah as you can see uh we have done this yeah as you can see uh we have done this um cool thank you so much for watching um cool thank you so much for watching see you guys next then goodbye take care see you guys next then goodbye take care bye-bye | 2024-03-21 11:07:46 | 1,503 | 1503. Last Moment Before All Ants Fall Out of a Plank || General Collision without speed degradation |
|
fENSCNm2xeo | to reformat the table such that there is a department id column a department id column and and revenue column for each month revenue column for each month okay for each month foreign one of foreign let's run this code yeah workout and then let's submit that's it for this video thank you | 2024-03-25 18:31:01 | 1,179 | Reformat Department Table (Leetcode 1179) in Telugu |
|
ZhS3xsjLE4w | hello everyone today we are here to hello everyone today we are here to solve question number 1822 solve question number 1822 of lead code sign of the product of an of lead code sign of the product of an array array input type is list and output type is input type is list and output type is end means what a list and we have to determine the sign of the product of numbers okay so let's see what is the question there is a function sine func that returns 1 if x is positive minus 1 if x is negative and 0 x is equal to zero we have written one for positive minus one for negative and zero for zero okay you are given an integer array in terms let's product be the product of all values in the array numbers written sign func of product means we have to return the value from this function let's see the example nums minus one minus two minus three and if of 0 in nums if there is a 0 then we simply return 0 now what we will count the number of negative numbers because we have to return just sign of the product of numbers not the actual product okay so you simply count the number of negative numbers for this as i am taking one loop and if i is less than zero and if i is less than zero negative value of negative number is negative value of negative number is by one okay and what we have to return by one okay and what we have to return one one if modulo of negative number is equals if modulo of negative number is equals to zero to zero else minus one a number of negative else minus one a number of negative numbers even okay numbers even okay so what it will become positive in the so what it will become positive in the case of positive what we have written case of positive what we have written here we have seen one okay here we have seen one okay and else minus one and for the third and else minus one and for the third condition condition we had done it here on the first line we had done it here on the first line so let's see let's run the code so let's see let's run the code yes it's working properly let me yes it's working properly let me check this with other example yes it's working fine so let's submit yes it's working fine so let's submit the code the code let's see what happens like yes it's working properly and hundred percent faster okay i'm moving with this question and okay i'm moving with this question and going to the next going to the next we will meet in the next video up to the we will meet in the next video up to the end bye bye see you soon | 2024-03-22 17:43:34 | 1,822 | Solution of LeetCode 1822 | Sign of the Product of an Array |
|
fURSWsQzLEw | all right welcome to this video we're gonna be solving Miko prom 112 past some gonna be solving Miko prom 112 past some so give you a binary tree right of so give you a binary tree right of numbers and then they'll give you some numbers and then they'll give you some and you want you to determine so return and you want you to determine so return true or false if you go down a route to true or false if you go down a route to leaf path when you add the numbers in leaf path when you add the numbers in each note you can get tolls some provide each note you can get tolls some provide so in this case to give you 22 and our so in this case to give you 22 and our coach return true because this route to coach return true because this route to leave path 5 plus 4 plus 11 plus 2 will leave path 5 plus 4 plus 11 plus 2 will give us 22 and again a leaf is a node give us 22 and again a leaf is a node with no children so if you add to 22 say with no children so if you add to 22 say somewhere in the middle of a tree and it somewhere in the middle of a tree and it still has left and right children that still has left and right children that doesn't count doesn't count right ask me kind of like this clear right ask me kind of like this clear path to where the last node doesn't have path to where the last node doesn't have a left or right child so I want to solve a left or right child so I want to solve this with helper method recursion this with helper method recursion because I find this the easiest way for because I find this the easiest way for me to understand recursion and also me to understand recursion and also explain it so with that being said let's explain it so with that being said let's get started so I'll say let res be equal get started so I'll say let res be equal to false and then our helper method to false and then our helper method function will update this to true if function will update this to true if there is a valid root to leaf path that there is a valid root to leaf path that adds it to the sum if there is not our adds it to the sum if there is not our helper method function will never update helper method function will never update this to true it'll stay false and will this to true it'll stay false and will still return the correct result so I'll still return the correct result so I'll call my helper function well helper and call my helper function well helper and takes in a node right we're traversing a takes in a node right we're traversing a node a binary tree that has notes and node a binary tree that has notes and then the second argument I'll call then the second argument I'll call current some initially will be set to 0 current some initially will be set to 0 when you first call our helper function when you first call our helper function but gets updated so I'll say if no note but gets updated so I'll say if no note has been passed or res has been set to has been passed or res has been set to true return if there's no node we don't true return if there's no node we don't want to execute the rest of our helper want to execute the rest of our helper function that makes sense or if res has function that makes sense or if res has been set to true up here then that means been set to true up here then that means if we already found a path that adds to if we already found a path that adds to 22 we don't need to we don't need to 22 we don't need to we don't need to keep traversing the rest of the binary keep traversing the rest of the binary tree that's just extra redundant work tree that's just extra redundant work right once you find one correct path we right once you find one correct path we don't need to keep doing extra work so don't need to keep doing extra work so that's why I have this extra check here that's why I have this extra check here all right all right now I will say curse um or current some now I will say curse um or current some plus equals no dot Val right we check plus equals no dot Val right we check let me refresh this actually write each let me refresh this actually write each known should have a Val property yup known should have a Val property yup that's the number so current sum plus that's the number so current sum plus equals no dot Val if the current node equals no dot Val if the current node you're on does not have a left child and you're on does not have a left child and it doesn't have a right child right it doesn't have a right child right because it has to be a root to leaf path because it has to be a root to leaf path and a leaf is a note of no left or right and a leaf is a note of no left or right child so the current node we are on does child so the current node we are on does not have a left child and does not have not have a left child and does not have a right child and the current sum is a right child and the current sum is equal to the sum the target sum we're equal to the sum the target sum we're aiming for then let's update our our aiming for then let's update our our variable res here to true so res is variable res here to true so res is equal to true and then we'll traverse equal to true and then we'll traverse the left and right child so helper node the left and right child so helper node left pass current some helper node dot left pass current some helper node dot right current sum alright so we just right current sum alright so we just finished defining our helper function finished defining our helper function now let's actually call it so I'll do now let's actually call it so I'll do helper call it on the initial node they helper call it on the initial node they give us right passing an initial sum give us right passing an initial sum value of 0 and then once this helper value of 0 and then once this helper runs if there's a valid root to leaf runs if there's a valid root to leaf path that adds it to the correct some path that adds it to the correct some res will be updated to true otherwise res will be updated to true otherwise we'll stay false so again this helper we'll stay false so again this helper function will well make sure that this function will well make sure that this res variable is the correct thing it has res variable is the correct thing it has to be and then I'll return rest now you to be and then I'll return rest now you like this kind of content please be sure like this kind of content please be sure to LIKE comment and subscribe and hit to LIKE comment and subscribe and hit that notification bell so that you're that notification bell so that you're notified of all new content and now notified of all new content and now let's make sure that my code passes the let's make sure that my code passes the leet code tests so I'll paste it in and leet code tests so I'll paste it in and we're good to go we're good to go was the past some complexity analysis was the past some complexity analysis time complexity is o of n because we time complexity is o of n because we Traverse every node in the tree space Traverse every node in the tree space complexities o event because we use complexities o event because we use recursion our call stack could be of recursion our call stack could be of length of the binary tree all right that length of the binary tree all right that should be it for this video | 2024-03-21 10:42:12 | 112 | Solving LeetCode 112 in JavaScript (Path Sum) |
|
bpDFgI0hIXM | hey everybody this is larry this is day 13 of the january league code daily 13 of the january league code daily challenge challenge uh hit the like button hit the subscribe uh hit the like button hit the subscribe button join me on discord let me know button join me on discord let me know what you think about today's prom what you think about today's prom votes to save people uh yes i usually votes to save people uh yes i usually solve these lives so um solve these lives so um even the explanations are definitely um even the explanations are definitely um yeah right fast forward towards the end yeah right fast forward towards the end if you're looking toward uh the solution if you're looking toward uh the solution or something or something but uh okay the eye of person has weight but uh okay the eye of person has weight i each i each pro can carry a maximum rate of limit pro can carry a maximum rate of limit the bulk can contain two people at a the bulk can contain two people at a time if time if the rate is less than limit we turn the the rate is less than limit we turn the minimum minimum number of votes to carry every given number of votes to carry every given person huh person huh that's interesting that's interesting um i mean so yeah and each one can be so um i mean so yeah and each one can be so the worst case is that given the worst case is that given n people we have end votes um and now n people we have end votes um and now we're trying to figure out how to we're trying to figure out how to match them up okay match them up okay so this is a little bit of trying to so this is a little bit of trying to figure it out figure it out uh and and i'm just thinking about different ways of uh well so the two things right one is i'm just trying to figure out a ways to uh use greedy in some way and then the other ring is just implementation um and how to prove them right how to prove greedy which is always the hard part for greedy i think the first thing i would do by the what was it by the way by the what was it by the way okay i don't know if that's sensitive okay i don't know if that's sensitive these days but but then my other idea these days but but then my other idea is that because you the both can carry is that because you the both can carry at most two people anytime you could at most two people anytime you could carry carry two people it should be two people it should be good if you good if you um if you minimize or maximize um if you minimize or maximize the other person right so basically you the other person right so basically you want two people who want two people who will add up to be as close to the limit will add up to be as close to the limit as possible as possible and if you do that um and this is and if you do that um and this is and some of my explanation with respect and some of my explanation with respect to this is just to this is just um playing around with a lot of numbers um playing around with a lot of numbers in the past in the past and this is just like an experience and this is just like an experience thing where i believe thing where i believe um like i don't know if i have a hard um like i don't know if i have a hard proof for this video but um but proof for this video but um but basically the idea is that basically the idea is that you know like like if two two people um have like very different weight and they're they add up to be near limit you um and this and one of them doesn't have a smaller uh fit you would say that um then it doesn't uh then you cannot get better fit meaning that okay let's let's say if you have a limit of five if um if you know if there's a person that's a size one um if it fits a four then that means that like any heavier person cannot fit with like any heavier person cannot fit with it and so forth right it and so forth right so what i'm thinking about that um and i so what i'm thinking about that um and i know that that's kind of a terrible know that that's kind of a terrible explanation to be honest explanation to be honest um but the way that i'm thinking about um but the way that i'm thinking about it is using that it is using that um we can do two pointers right we can um we can do two pointers right we can just have uh appointed to the smallest just have uh appointed to the smallest person or the person or the lightest person and the heaviest person lightest person and the heaviest person and then kind of march and then kind of march much toward the middle um to get the much toward the middle um to get the limit and the reason why that we can do limit and the reason why that we can do this this is because like i said um i mean these is because like i said um i mean these examples are not very great for that examples are not very great for that actually but but let's say we have actually but but let's say we have um you know one two and this is also why um you know one two and this is also why we we sort it um someone like that right sort it um someone like that right well five you know that and let's say well five you know that and let's say limit is five to be clear limit is five to be clear um if we if we do the five then you know um if we if we do the five then you know uh uh you know five will be on on don't vote you know five will be on on don't vote for four and the one well we know that for four and the one well we know that it cannot it cannot fit right um uh and let's just add another um let's just add another four for for illustration but yeah we match to find the one i think that should be obvious at this point and then the second four well it doesn't fit with two and because two is the smallest number that it can be um that it can match with then you know that we could have to get rid of four so then we have three um yeah and then three and the two match so then we put them in the same boat and another three three so i think that should be good enough for us to as a strategy because i think we can really work and it's like i said some of the reason why i i don't have a strict mathematical proof because those things are always hard especially live because i'm not you know like i don't have you know references and studies for it but and some of that is where practice will come into play where if you deal with kind of the properties of these sweep line type uh numbery number line type problems enough then you'll you'll kind of like almost be convinced about it so so then after that just i think yeah i think the and you know i i think yeah i think the and you know i could have said the same algorithm in could have said the same algorithm in different ways different ways and they have different implementation and they have different implementation even though they might do similar same even though they might do similar same thing thing but what i want to do is that i'll take but what i want to do is that i'll take the max uh the heaviest person the max uh the heaviest person see if it fits up the lightest if it's see if it fits up the lightest if it's if it is if it is if it doesn't then um then the heaviest if it doesn't then um then the heaviest person gets his own boat person gets his own boat i think maybe that's a more intuitive i think maybe that's a more intuitive way of doing it or explaining it because way of doing it or explaining it because uh if if the heaviest person and the uh if if the heaviest person and the lightest person doesn't match up or like lightest person doesn't match up or like they don't fit on the same boat they don't fit on the same boat then you know that there's no way that then you know that there's no way that the heaviest person the heaviest person can can um can be can can um can be with it's uh can be with anyone else with it's uh can be with anyone else right because everyone else is heavier right because everyone else is heavier so then they get their own boat and so then they get their own boat and conversely conversely um and if you kind of keep that in um and if you kind of keep that in variant in place variant in place um that will always be true so let's do um that will always be true so let's do it that way it that way um and there are a couple of ways to do um and there are a couple of ways to do it um it um you know there are a couple ways that we you know there are a couple ways that we can think about implementing it uh can think about implementing it uh but the way that i want to do it it's a but the way that i want to do it it's a little funky little funky um because um because about ah you could use two pointers i'll just use two pointers so heaviest is equal to length of people minus one so this points at the last element and then the lightest is equal to zero um and then just votes is equal to zero to begin with and then now we have a while uh heaviest um is greater than lightest so if they're the same what happens we might have to we might have to test we might have to we might have to test that one a little bit that one a little bit to get the edge case of weapons and to get the edge case of weapons and they're the same i guess they're the same i guess if they're the same that's okay but then if they're the same that's okay but then we would have to add an if statement we would have to add an if statement anyway so that's why i'm anyway so that's why i'm not doing it that way um because if you not doing it that way um because if you have to check an if statement inside have to check an if statement inside whether heavier is equal to the lightest whether heavier is equal to the lightest then you might as well do it out outside then you might as well do it out outside um so okay so if um so okay so if people the heaviest person plus people the heaviest person plus the lightest person is the lightest person is less than or equal to limit then you less than or equal to limit then you know we know we vote in frame by one well we always vote in frame by one well we always increment by one in either case increment by one in either case but if they're under the limit then we but if they're under the limit then we can go can go um uh um uh we can move both the people that have a we can move both the people that have a typo here i think typo here i think uh otherwise we only move to the uh otherwise we only move to the heaviest so we can actually even heaviest so we can actually even take this out and do it this way right and then at the very end [Music] if heaviest is equal to lightest um then we have to check that one case um then we just do both one and then we return both and this is not actually this doesn't always have to be true right this actually is only true if there's only one person left at the end um because you can imagine um you know if you have two three limit is equal to five uh the heaviest actually points the heaviest goes you know starts at index one lightest starts at index zero and then after one iteration this actually goes to zero and this goes to one right so this is actually um strictly less than so yeah um okay let's actually run the okay looks okay so let's let's give it a okay looks okay so let's let's give it a submit submit um sometimes i get questions about um sometimes i get questions about running time but running time but in this case um i i'm confident about in this case um i i'm confident about looking looking uh like sometimes you know i mentioned uh like sometimes you know i mentioned it constrains a lot it constrains a lot um and in this case because i kind of um um and in this case because i kind of um did it this way did it this way uh i know that well the sorting is n log uh i know that well the sorting is n log n obviously um n obviously um and the rest is linear time so i don't and the rest is linear time so i don't look at constraint because you can't look at constraint because you can't you know it's very rare that you can do you know it's very rare that you can do it um better than it um better than linear time and sorting and sorting is linear time and sorting and sorting is pretty fast in general unless pretty fast in general unless you're doing something really funky uh you're doing something really funky uh because libraries are pretty fast about because libraries are pretty fast about it it um but yeah so what is the complexion of um but yeah so what is the complexion of this like i said this is n log n this like i said this is n log n uh this is all and and in terms of space uh this is all and and in terms of space um depending how you want to define it um depending how you want to define it uh we either have uh we either have no you know constant extra space or no you know constant extra space or because of the fact that we sort the because of the fact that we sort the people people and we really should not mutate the and we really should not mutate the input we should probably create another input we should probably create another way of the same size and you know copy way of the same size and you know copy it over before sorting it it over before sorting it you know you could say that this is of n you know you could say that this is of n space as well space as well uh in a reasonable way because p because uh in a reasonable way because p because now now the person who passed uh you know their the person who passed uh you know their input here input here you know it got mutated but yeah um i think you could also do like sliding i think you could also do like sliding window in the same window in the same similar way or two pointers by by taking similar way or two pointers by by taking advantage of that advantage of that um this is less than 30 000 but i don't um this is less than 30 000 but i don't know how helpful that is know how helpful that is so yeah uh for this one because it is so yeah uh for this one because it is greedy greedy uh i'm going to look at the solution and uh i'm going to look at the solution and just go over with y'all just go over with y'all um just to kind of see if i you know um just to kind of see if i you know maybe there's another way maybe maybe there's another way maybe you know if there's a funkiness or you know if there's a funkiness or something like that but okay something like that but okay yeah so basically this is the idea that yeah so basically this is the idea that i did so yeah i did so yeah except for their logic is the other way except for their logic is the other way where um the lightest where um the lightest is with the heaviest okay so i guess is with the heaviest okay so i guess that's the only um that's the only um thing about it uh yeah now i like that they actually did the space complexes of n because i think um because of what i said about the uh the mutating input so yeah uh [Music] cool let me bring this back up so that you know you could you could snapshot it or whatever um but yeah that's what i have with this problem i think so let me know what you think uh hit the like button to subscribe on drum and discord these i would also say that these greedy problems um they take a lot of practice because the actual proofs are hard for me i actually find greedy problems harder than dynamic program problems because for dynamic program problems you're proved by being exhaustive where for greedy problems sometimes you know you have a hypothesis and then it turns out to be wrong um and you know and the good thing about lead code um is that you know you get one like they tell you what the the case that you get wrong is and you can analyze that so that's why it's a good practice for greedy problems as well but yeah that's all i have for this prom | 2024-03-22 17:33:46 | 881 | 881. Boats to Save People - Day 13/31 Leetcode January Challenge |
|
oJBxGbWLVQs | hey guys it's off by one here and today we're going to be solving product of we're going to be solving product of array except self array except self so in this problem we're given an so in this problem we're given an integer array nums and they want us to integer array nums and they want us to return an array answer such that answer return an array answer such that answer of I is equal to the product of all of I is equal to the product of all elements of nums except the current nums elements of nums except the current nums so what does that mean exactly if we so what does that mean exactly if we take a look at this example here we can take a look at this example here we can see that the output array is supposed to see that the output array is supposed to be 24 12 8 and 6 and the way this is be 24 12 8 and 6 and the way this is calculated is by on the first spot you calculated is by on the first spot you multiply 2 times 3 times 4 for the multiply 2 times 3 times 4 for the second spot you multiply one times three second spot you multiply one times three times four the third spot you multiply times four the third spot you multiply one times two times four and so on one times two times four and so on the tricky part about this problem is the tricky part about this problem is that we can't use a division operation that we can't use a division operation so we couldn't just go through the whole so we couldn't just go through the whole array find whatever the product is and array find whatever the product is and then at the end just divide the product then at the end just divide the product by whatever number we're at and store by whatever number we're at and store that in our answer array that in our answer array so let's think about another way to so let's think about another way to solve this problem without dividing solve this problem without dividing if we take a look at our answers array if we take a look at our answers array we can see that the first entry is we can see that the first entry is 2 times 3 times 4. and then the next 2 times 3 times 4. and then the next entry is one times three times four entry is one times three times four the third entry is one times two times the third entry is one times two times four four and then the last entry is one times two and then the last entry is one times two times three times three if we take a closer look at what these if we take a closer look at what these numbers are we can see that for the numbers are we can see that for the first entry we're calculating the first entry we're calculating the product of all the numbers afterwards product of all the numbers afterwards and then for the second entry we're and then for the second entry we're calculating the product before and the calculating the product before and the product after product after for the third entry similar thing we for the third entry similar thing we calculate the product before and the calculate the product before and the product after product after and then for the last entry we're only and then for the last entry we're only calculating the product before calculating the product before so what we could do here is have an so what we could do here is have an array for the product before and the array for the product before and the product after so it could look something product after so it could look something like this like this the array before for one it would just the array before for one it would just be one because there's nothing before be one because there's nothing before that for two it would also be one that for two it would also be one because one times one is one and then because one times one is one and then for three it would be 1 times 2 which is for three it would be 1 times 2 which is two and for four it would be six two and for four it would be six and then for after and then for after it would be two times three times four it would be two times three times four for the first for the first precision for the first for the first precision and that is 24. and then for the second and that is 24. and then for the second position we would have three times four position we would have three times four which would be 12. which would be 12. for the third position we would have for the third position we would have just a four and then for the last one it just a four and then for the last one it would just be a one because there's would just be a one because there's nothing after the four nothing after the four and then to get this answers array all and then to get this answers array all we have to do is multiply each one of we have to do is multiply each one of these these and store them in our answers array so 1 and store them in our answers array so 1 times 24 would be 24 1 times 12 would be times 24 would be 24 1 times 12 would be twelve two times four would be eight and twelve two times four would be eight and six times one would be six six times one would be six the runtime for this algorithm is the runtime for this algorithm is actually o of n which is great it's actually o of n which is great it's exactly what we want but the problem now exactly what we want but the problem now is that we take up a lot of extra space is that we take up a lot of extra space here with these two arrays here with these two arrays and we don't actually need them we can and we don't actually need them we can actually solve this problem with all of actually solve this problem with all of one space one space the way we do that is by having two the way we do that is by having two variables one to keep track of the variables one to keep track of the product before and one to keep track of product before and one to keep track of the product after and the way we're the product after and the way we're going to calculate these products is by going to calculate these products is by looping through the array once going looping through the array once going this way and one's going this way this way and one's going this way because to get this we would need to because to get this we would need to iterate backwards so we can have four iterate backwards so we can have four times three times two times three times two so I'm going to show you what I mean in so I'm going to show you what I mean in more detail so I've initialized the more detail so I've initialized the array to all ones so we can multiply our array to all ones so we can multiply our before and after to it before and after to it and to start let's go with this first and to start let's go with this first position so there's nothing before so position so there's nothing before so people just multiply the answers array people just multiply the answers array by one and that gives us one by one and that gives us one and then we go to the second one before and then we go to the second one before is still one so we're going to do that is still one so we're going to do that after is three and then we have 1 times after is three and then we have 1 times 2 and that would give us a before of two 2 and that would give us a before of two and that's what we're going to do here and that's what we're going to do here and same thing for this last one we and same thing for this last one we would have 1 times 2 times 3 which would would have 1 times 2 times 3 which would make them before 6. make them before 6. and that's what we store here and that's what we store here and now we're going to go backwards so and now we're going to go backwards so our after we're going to start at 4 here our after we're going to start at 4 here and there's nothing after four so we and there's nothing after four so we just multiply oh we just multiplied by just multiply oh we just multiplied by one and then we go to three the only thing after three is four so we would multiply um by four so just after now it's four and then we're going to go over to two and we can see that here we're the after is 3 times 4 and that would be 12. and then for the first one the after so now our final array will look like so now our final array will look like this this 24 24 12 12 8 and 6. 8 and 6. and that's exactly what we want here and that's exactly what we want here and this algorithm now takes o of n time and this algorithm now takes o of n time and only takes up constant space because and only takes up constant space because we're only using these two variables we're only using these two variables so now we can go through the code so now we can go through the code so to start we want to initialize our so to start we want to initialize our answer array which is going to look like answer array which is going to look like this we want to set it to all ones for a this we want to set it to all ones for a size of nums size of nums and then from here we just want to and then from here we just want to initialize our two variables that are initialize our two variables that are we're going to use to keep track of our we're going to use to keep track of our multiplication so we're going to have multiplication so we're going to have product before product before and set that equal to one and then and set that equal to one and then product after and have that equal to one product after and have that equal to one so now we're going to iterate through so now we're going to iterate through the array forwards so for I in range of the array forwards so for I in range of length of nums length of nums what we want to do here is set our what we want to do here is set our answer array at I equal to the product answer array at I equal to the product before before because if we think about it the first because if we think about it the first entry we don't want it to change we want entry we don't want it to change we want it to be one because there's nothing it to be one because there's nothing before it before it and then after that you want to modify and then after that you want to modify product before product before so it's equal to so it's equal to product before product before times the current times the current value of nums value of nums and then now we just want to iterate and then now we just want to iterate backwards and the way to do that in backwards and the way to do that in Python is like this for I in range of Python is like this for I in range of length of nums length of nums minus one and then minus one minus one minus one and then minus one minus one that can look a little confusing but that can look a little confusing but that's just how you iterate backwards in that's just how you iterate backwards in Python Python and what we want to do here is now and what we want to do here is now multiply our answers array multiply our answers array times times our product after and if we think about it in the example there was nothing after four so it would make sense that product after is just one and then from there we do the same thing we did above where product after is Multiplied with the current number we're at and then from here we can just return and that should work so now I'm going to manually go through the code so to start we want to initialize our answers array with all ones so it's going to look like this and we want to initialize our variables to one which I did here as you call them b and a just to make them short and then we're going to iterate forwards so for answers at I which would be this position we want to set it to a product before and it's already one so nothing changes there and then we update product before to product before times nums of I which is 2. so now this is two and then we go to the next one and so now answers at I is going to be set to product before which is 2. and then product four gets multiplied by the current number which is three so now it is six and now we go to the next iteration so answers at I is going to be set to product before which is six and then product four is going to be updated to 24. and then for the last iteration here we are going to set numbers I to 24. and then B is going to be updated to 120 I believe and so now we're going to iterate backwards since we're done going forwards so we're going to start at 5 here so we can see that answers at I times product after is still going to be the same because this is set to one still but now we're going to update product after to be multiplied by five so I'm just going to do that and so next we go to the four and answers that I times product after is the new answer that I so this 6 will and then this is updated to be product and then this is updated to be product after times the current number which is after times the current number which is four so we would have 5 times 4 which is four so we would have 5 times 4 which is 20 20 and now we go to the next iteration and now we go to the next iteration and answers at I times product after the and answers at I times product after the new answers at I so 20 times 2 that is new answers at I so 20 times 2 that is 40 and then our product after is 40 and then our product after is multiplied by our current number multiplied by our current number and that is going to be 60. and that is going to be 60. and then for our last iteration here we and then for our last iteration here we are just going to update answers at I by are just going to update answers at I by multiplying it times the product after multiplying it times the product after which is 60. and which is 60. and that's our final answer that's our final answer if this video helped you in any way if this video helped you in any way please like And subscribe because it please like And subscribe because it really supports the channel thanks for really supports the channel thanks for watching and I'll see you in the next watching and I'll see you in the next video | 2024-03-22 11:33:56 | 238 | Product of Array Except Self - Leetcode 238 - Blind 75 Explained - Arrays - Python |
|
lNSTvbVRpIA | hey what's up guys this is john here so today let's take a look at 227 so today let's take a look at 227 basic calculator number two and this is basic calculator number two and this is one of the uh one of the uh the calculator series problems so the calculator series problems so so for this problem there's no so for this problem there's no there's no parenthesis and there's only there's no parenthesis and there's only uh uh two operators which is the plus two operators which is the plus subtract multiply and undivided and they're like us i think the total four calculators problems in lead code i think it's pretty i think they're pretty interesting so today i think i'm gonna try to use a like more generic way of solving this problem so that in case in case there is some any follow-up questions you can still use the same similar idea here so a few examples right so you know there are like some solutions that you don't even need a stack you can just use like several several variables to track the other previously previously operator and the values but today so for my generic solutions i'm going to use two stacks the first one is going to gonna store all the other numbers and the second one will store all the so how will this thing work right so how will this thing work right basically you know basically you know a few examples here you know so when a few examples here you know so when with this kind of like let's forget with this kind of like let's forget about parentheses for now let's about parentheses for now let's only consider this this uh for our only consider this this uh for our operators so when can we calculate operators so when can we calculate the previously result the previously two the previously result the previously two two numbers two numbers right so let's say we have two three right so let's say we have two three plus two plus two can we can we calculate this one can we can we calculate this one probably not it's probably not it's depending on the current operator depending on the current operator right so so at this moment you know we have a two stacks here so the first stack is three and two right and the second stack is the operator at at this moment we have a plus one here right so that's the that's the stack one that's the operator stack and now we're at the uh we're at the this multiplies here it depends actually depending on the priority of the operators here right because you know as you guys can see if the current operator is then the top then then the first one in then the top then then the first one in the in the operator stack the in the operator stack then we cannot calculate those two then we cannot calculate those two numbers numbers right so when can we when can we right so when can we when can we start calculation we it only when start calculation we it only when let's say we have 2 plus let's say we have 2 plus 3 times 2 and then let's see that 3 times 2 and then let's see that there's another time there's another time time here right so now what we have we time here right so now what we have we have another have another another 2 here right we have another another 2 here right we have another multiply and then we have another two multiply and then we have another two here right so that's going to be our here right so that's going to be our current stack current stack now we're at this this uh now we're at this this uh multiply operators here you know now the multiply operators here you know now the the multiplier operator the multiplier operator is is not greater right it's not greater than then we know that okay so now we can then we know that okay so now we can calculate the previously result right and we do that until we have seen so basically now we have this two times so basically now we have this two times times two here right so times two here right so we just we just pop we just pop this we just we just pop we just pop this two times two we have like what we have two times two we have like what we have three and after calculations we add three and after calculations we add we push this thing we append the result we push this thing we append the result back to the stack back to the stack right now we only have this plus here right so that's that let's say we have right so that's that let's say we have another three here right so now what we another three here right so now what we have we have uh have we have uh we have a three and then we have another we have a three and then we have another another another multiply here right multiply here right okay so this this so this part is gone okay so this this so this part is gone right we have that right we have that now let's see the next one is plus two now let's see the next one is plus two right so what do we have you know right so what do we have you know since this this plus is smaller it's not since this this plus is smaller it's not either either either equal or smaller than the top one either equal or smaller than the top one right then we pop this right then we pop this these two out right it's going to be these two out right it's going to be what's going to be what's going to be going to be 12 right because the 3 times going to be 12 right because the 3 times 4 will be 12. so now we we have 12 here 4 will be 12. so now we we have 12 here we have 12 and then this this thing is we have 12 and then this this thing is gone gone and the plus is still not greater than and the plus is still not greater than the top one the top one right then we do we do what we do a plus right then we do we do what we do a plus which will be which will be the the 12 plus 3 which is which the the 12 plus 3 which is which which will be the 15 and then this is which will be the 15 and then this is gone as gone as and in the end the 15 is our final and in the end the 15 is our final answer which is which is this answer answer which is which is this answer right three right three plus yeah so that's the that's the the 15 yeah so that's the that's the the 15 right in the end here right in the end here so we have a 15 here and now we are we so we have a 15 here and now we are we just need to do a plus two here with just need to do a plus two here with that that's why we're gonna have like that that's why we're gonna have like another plus sign here another plus sign here and then about 15 we have a two here and then about 15 we have a two here right right so this is the the new stack so in the so this is the the new stack so in the end end we all we have is is this 15 and two we all we have is is this 15 and two left in this stack and then we have left in this stack and then we have another another the last class operator here so that the the last class operator here so that the total total the final result will be 17. so as you guys can see so the key the key logic for this kind of problem is that you know we have to know basically the priority the priority between the current the priority between the current operator and the previously our operator and the previously our operators and we can keep operators and we can keep popping up we can keep calculating the popping up we can keep calculating the previously previously previous tokens you know as long as the current calculator is not greater than the than the top operator stack then we can keep popping those number one number two out and then do the calculation until we have reached the point that the current one is greater than the top one then we know okay we cannot one one all right cool so that's going to be our all right cool so that's going to be our our basic our basic logic here you know i'll i'll just i'll logic here you know i'll i'll just i'll implement that one first and then implement that one first and then we'll talk about the follow-up questions we'll talk about the follow-up questions like the uh like the uh what happens if you need to handle the what happens if you need to handle the parentheses and what parentheses and what what happens if you you you will need to what happens if you you you will need to support support more operators other than this four more operators other than this four right how can we do it okay cool so we're gonna have the numbers right at the stack and then that's stack one and then we have our operators right operators that's gonna be a stack too so a few few like variables here right so then we have n here and then we have uh we have i here so i is from zero and then we have a while loop while i smaller than n right and then we start doing so since we have this kind of like empty strings you know the first thing to handle is like this just uh if it's i plus one and then i we just simply i plus one and then i we just simply continue right so that's the first continue right so that's the first that's the first one and second one is that's the first one and second one is always to uh to capture always to uh to capture the current integers right so the card the current integers right so the card to capture current integers you know to capture current integers you know i just use this one let's use the if i i just use this one let's use the if i if s i if s i is digits right if the current is digit is digits right if the current is digit i just continue i just continue continue looping through moving the continue looping through moving the cursor to the right until we have cursor to the right until we have reached a nine reached a nine digit character right and then we have digit character right and then we have the uh the uh the current number so that's why i'm the current number so that's why i'm going to define my current number going to define my current number equals to zero and then while i equals to zero and then while i smaller than n and as smaller than n and as i it's digits right then i just keep updating keep updating the card numbers multiply by 10 let them do a plus int dot s i right so that's that and then don't forget to do a high plus one here now we have the uh now we have the numbers here right so now let's do a nums dot append dot current number right so and here we're gonna have like some else here in the end we're going to do a i plus one here right but you know since as you guys can see here so we already do a whenever this while loop is finished the eye is has already reached to the next to the next position here if we do a i plus one in the end there's gonna be a double increase here so that's why i just uh i just reverted back so that we all of the the branches can still use the i plus one here it's a little a little trickier right i mean you guys can do something else but this uh this is just how i do it okay so that's that you know what so what is the house case so the else case is that this is the operator right so else case means that it's it's operator right operator and so like what we have discussed now you know the uh so the kernel so si is the current operators and we just need to we just need to compare we just need to compare the uh with the visit with the the top one on the operators i mean if the current one current i mean if the current one current operator's priority is equal operator's priority is equal either equal or smaller than the top one either equal or smaller than the top one then we can then we can keep popping the numbers out and do the keep popping the numbers out and do the calculations calculations right and to do that i'm going to create right and to do that i'm going to create a few a few i think two helper functions here right i think two helper functions here right like i said you know the first one is to like i said you know the first one is to get the priority priority get the priority priority right so i'm going to pass in the right so i'm going to pass in the operators here right you know operators here right you know gift operators in what in the in plus and minus right then i give it priority equals to one right ask if the operators in what the to multiply or divide it i give it 2 that's the priority right and then i'm also going to create like another half functions to help me to do to evaluate right if i literate the the numbers by passing in the number one number two and and the operator okay so if the operators equal to plus right and then yeah we return num1 plus num2 right so i'm just going to i'll see if this isn't miners we do a i'll see if this isn't miners we do a miners right so same thing for the for the time the multiply and the divide divided thing so we have a that and then we have a divided right so that's how we evaluate the our numbers here so like i said you know so now we're at the uh that operator so so now we're at the uh that operator so first thing to check is that while first thing to check is that while the operator is not empty right operator the operator is not empty right operator it's not empty it's not empty and the uh the pry already so we checked our operator it's not empty because you know it could be empty right yeah because if we have two plus yeah because if we have two plus three plus plus six you know when we are three plus plus six you know when we are at at when we're at uh plus the first the when we're at uh plus the first the first operators here right first operators here right the operators is empty that's why we the operators is empty that's why we need to check this one need to check this one so if it's not empty and then we check so if it's not empty and then we check if the priority dot and if the priority dot and that s i if that the priority of the that s i if that the priority of the current current the current operator is either equal or the current operator is either equal or smaller smaller than the priority than the priority of the uh operators of the uh operators operators minus one operators minus one right so if that's the case then we know right so if that's the case then we know okay we can okay we can we can calculate the the first two we can calculate the the first two numbers so that's why we do a numbers so that's why we do a num2 equals to nums pop right num2 equals to nums pop right and then num1 equals to nums and then num1 equals to nums pop here so keep in mind here so the pop here so keep in mind here so the first one first one got popped out his num is num2 and got popped out his num is num2 and second one got popped out is num1 so the second one got popped out is num1 so the sequence matters sequence matters because we're going to have like this because we're going to have like this multiplied multiplied subtract and divide it so so subtract and divide it so so we have to make we have to follow this we have to make we have to follow this sequence here and of course then sequence here and of course then we have a after popping two numbers we we have a after popping two numbers we need we also need to pop the uh need we also need to pop the uh the operators out right operators the operators out right operators dot pop and then dot pop and then and then we can just evaluate the and then we can just evaluate the numbers numbers after the evaluation we can we need to after the evaluation we can we need to append this back to this nums append this back to this nums stack here so we do a evaluate stack here so we do a evaluate right by passing the num1 right by passing the num1 num2 and operator num2 and operator cool so that's that you know cool so that's that you know that's how we calculate the previous that's how we calculate the previous ones ones and then in the end here in the end and then in the end here in the end right so now after right so now after after this while loop here what what after this while loop here what what might might what might end up in these nums and what might end up in these nums and operators you know operators you know if we have like 3 plus 2 times 6 if we have like 3 plus 2 times 6 so what we have in the stack will be so what we have in the stack will be something like this will be something like this will be three two and six three two and six so and in the operator stack we have so and in the operator stack we have plus plus and the uh and the and the uh and the the the multiplier right the the multiplier right because we're only doing this kind of because we're only doing this kind of calculations calculations when when there's like multiple when there is a case right when when the current one is smaller than that than the previously operators right but if if it's always increasing the priorities you know we might end up something like this after the while loop that's why in the end we also need we also need to do a while loop similar like this one to evaluate the the numbers to evaluate the uh our our stacks so we can simply copy and paste yeah so that's that oh yeah so that's that oh i think one thing i forgot to do here is i think one thing i forgot to do here is that you know we forgot to that you know we forgot to append the operator stacks operators append the operator stacks operators dot append as dot append as i because the isis is the operator right i because the isis is the operator right all right cool so and then i simply all right cool so and then i simply return the nums return the nums dot minus one because dot minus one because after this final while loop here we have after this final while loop here we have evaluate evaluate everything in the stack so we can simply everything in the stack so we can simply re return the last the only number left re return the last the only number left that that's going to be our answer so that that's going to be our answer so yeah i think that's it i think let's run yeah i think that's it i think let's run the code these digits oh wait maybe here operators okay oh wait maybe here operators okay yeah i mean i'm missing an as here 51 operators oh i'm sorry here so um so in the fight in the final while loop here we don't need to care or worry about the priority here because for all the priorities we need to to be to be taken care of we have already taken care of it here so so what's left here we can just we can simply we can simply calculate evaluate numbers from top down here that's why we think we can simply use the pr the operator operators stack to uh to evaluate all right run the code all right so success all right so success i mean i mean yeah so that's that you know the as you yeah so that's that you know the as you guys can see here you know the guys can see here you know the the time complexity time and space the time complexity time and space complexity so the time is complexity so the time is just a while loop here right from 1 0 just a while loop here right from 1 0 to n here and so here even though we have we might have a nested while loop here but each element will will only be pushed and put popped out from to an in and out of the queue only once so that's why the total time complexes of n and space complexity cool so that's that and how about some cool so that's that and how about some follow-up questions follow-up questions right i think the uh i think the the first follow-up questions is like the uh besides this these four operators what what how about to support more operators let's say how about this one three times plus five times three and then we have a power of two how about this right because this power operator has a higher even higher priority than this than the the multiple and divide right i think the fix is pretty straightforward because because we have we have been taking care of these things here you know we have a while loop here so all we need to do is this is just this all we need to do we just need to add an another another branch in the operator in the priority here power right then we simply return power right then we simply return three that's going to be our three that's going to be our the priority three operators and here we the priority three operators and here we also also just need to add another if condition just need to add another if condition here here if this thing is equal to that we just if this thing is equal to that we just need to need to do a right power do a right power evaluation here okay so that's evaluation here okay so that's pretty easy pretty easy and how about to uh how about to and how about to uh how about to to support the parentheses right to support the parentheses right so so to support so so to support the parentheses you know the uh we have the parentheses you know the uh we have to basically to basically add two more add two more out condition here right so the first out condition here right so the first one simply the uh one simply the uh else if the s i is equal to the else if the s i is equal to the to the left parenthesis you know to the left parenthesis you know actually there are like actually there are like the way we're doing is like we just need the way we're doing is like we just need to add to add this left parenthesis to the operators this left parenthesis to the operators to the operators to the operators stack so that later on we can we can stack so that later on we can we can we can keep popping up the operators we can keep popping up the operators until we have seen until we have seen we have seen the left parenthesis right we have seen the left parenthesis right then that we know that's when we then that we know that's when we should stop the the while loop should stop the the while loop so we just append these things to so we just append these things to the left parentheses without operators the left parentheses without operators that's all we need to do that's all we need to do when we see a left parenthesis and when we see a left parenthesis and more work needs to be done when we see more work needs to be done when we see an ending parenthesis right so when an ending parenthesis right so when when this thing ha when this thing when this thing ha when this thing happens so what should we do happens so what should we do you know keep in mind that you know so you know keep in mind that you know so it's it's going to be similar like our it's it's going to be similar like our final final final while loop because all the uh the final while loop because all the uh the priority related priority related calculations you know have been taken calculations you know have been taken care of in this care of in this in this while loop here in this while loop here and so that no whenever we see an ending and so that no whenever we see an ending parenthesis or we are parenthesis or we are we have reached the end of this uh we have reached the end of this uh string here string here we know that we can just safely we know that we can just safely and doing we can safely do this kind of and doing we can safely do this kind of pop thing pop thing from the top to calculate that and then from the top to calculate that and then add it back and then we can just do a add it back and then we can just do a evaluation by evaluation by with those two numbers plus operators so with those two numbers plus operators so that that that's why actually we can simply that's why actually we can simply copy and paste this part and but the copy and paste this part and but the only thing we need to only thing we need to add here you know is and what add here you know is and what and the operators and operators minus and the operators and operators minus one one that this output minus one is not that this output minus one is not equal to this left right equal to this left right we keep doing this until we have seen a we keep doing this until we have seen a left parenthesis left parenthesis then we know that's that's that's when then we know that's that's that's when we should stop we should stop right and then after this while loop right and then after this while loop don't forget to pop this left don't forget to pop this left parenthesis out parenthesis out it's going to be another operator's it's going to be another operator's dot pop yep i think that's that's all the yep i think that's that's all the follow-up follow-up for this problem you know like this is for this problem you know like this is like a generic way of like a generic way of supporting to evaluate supporting to evaluate any of the operators including the uh any of the operators including the uh to print this cool so yep that's it okay i think i'll stop here and i hope you guys enjoy watching this video thank you so much and stay tuned i'll be seeing you guys bye | 2024-03-22 11:03:55 | 227 | LeetCode 227. Basic Calculator II |
|
tRCDoqo0l40 | hello everyone myself Rahul so today I am going to solve a problem related to am going to solve a problem related to Strings so the problem name is word Strings so the problem name is word pattern so let's go through this problem pattern so let's go through this problem statement so here we are given a pattern statement so here we are given a pattern and a string s we have to find if s and a string s we have to find if s follows the particular pattern the same follows the particular pattern the same pattern pattern so here the follow means a full match so here the follow means a full match such that there is a bijection between a such that there is a bijection between a letter in pattern and no empty word in s letter in pattern and no empty word in s right so through this the things are not right so through this the things are not very clear but let's go through the very clear but let's go through the example so the pattern is a b b a and example so the pattern is a b b a and the string given is dog cat cat and dog the string given is dog cat cat and dog right so what does bijection mean over right so what does bijection mean over here is that for a particular character here is that for a particular character in pattern there should be corresponding in pattern there should be corresponding word in a string so if we observe word in a string so if we observe carefully the character a can correspond carefully the character a can correspond to Dom and the character B can to Dom and the character B can correspond to character similarly this correspond to character similarly this third character B can also correspond to third character B can also correspond to the same cat and the last character a the same cat and the last character a can correspond to dog can correspond to dog so for each individual character we have so for each individual character we have a corresponding word Associated so in a corresponding word Associated so in that case we have to return true that case we have to return true another example is a b b a and uh the another example is a b b a and uh the string like basically the pattern is string like basically the pattern is same but the string has changed from same but the string has changed from this to this so if you look here so a this to this so if you look here so a corresponds to Tau B corresponds to corresponds to Tau B corresponds to suppose cat then again the third B will suppose cat then again the third B will correspond to cat this is fine till now correspond to cat this is fine till now but the last a is corresponding to fish but the last a is corresponding to fish over here but the earlier a was over here but the earlier a was referring to dog right so it means this referring to dog right so it means this is not a well-led pattern or is not a well-led pattern or um valid string so we have to return um valid string so we have to return false in this case right so there is no false in this case right so there is no one-to-one mapping as such one-to-one mapping as such right so let me uh try to exam uh right so let me uh try to exam uh explain this using an example so the explain this using an example so the first first example we can take is a b b so this is example we can take is a b b so this is the pattern that has been given to us the pattern that has been given to us and suppose the string given is and suppose the string given is dog dog Space Cat Space Cat Space Cat and again spaced on right so Space Cat and again spaced on right so what they mean is that each individual what they mean is that each individual character in the pattern this is the character in the pattern this is the pattern pattern and this is string s right so a got and this is string s right so a got supports to dog so if a is corresponding supports to dog so if a is corresponding to down to down then B is corresponding to cat then B is corresponding to cat oh sorry cat and this B is also oh sorry cat and this B is also corresponding to cat this mean which corresponding to cat this mean which means it is fine so we don't need to means it is fine so we don't need to update this data structure update this data structure right so suppose we are maintaining that right so suppose we are maintaining that in a data structure and this a is called in a data structure and this a is called again corresponding to dog which was again corresponding to dog which was already present inside this data already present inside this data structure so it is also fine so in that structure so it is also fine so in that case we have to return true case we have to return true right so in the other example if instead right so in the other example if instead of a b b a uh like let's keep it same of a b b a uh like let's keep it same Abba but instead of dog cat get down the Abba but instead of dog cat get down the example is dog cat cat and fish example is dog cat cat and fish right so here it is corresponding to dog right so here it is corresponding to dog then comes space then comes space then we check the second character B then we check the second character B with cat so B corresponds to add with cat so B corresponds to add then comes again third character there then comes again third character there is a space so this V is also responding is a space so this V is also responding to cat so B is already present inside to cat so B is already present inside this data structure so we don't update this data structure so we don't update that then this a is corresponding to that then this a is corresponding to fish but a was already present inside of fish but a was already present inside of this data structure let's we will decide this data structure let's we will decide on that like what data structure we can on that like what data structure we can use so his order a is corresponding to use so his order a is corresponding to fish which is not correct because it was fish which is not correct because it was uh already referring to term so this is uh already referring to term so this is not correct so we will return false in not correct so we will return false in this case this case right so how are we going to solve this right so how are we going to solve this problem problem so the first approach the brute force so the first approach the brute force method method the most intuitive method over here is the most intuitive method over here is can be like somehow we need to maintain can be like somehow we need to maintain the mapping between the connector the mapping between the connector and the corresponding string associated and the corresponding string associated with that with that right so how are we going to maintain right so how are we going to maintain that using a hash map that using a hash map right so if we create a hash map of care right so if we create a hash map of care and strings where the character is the and strings where the character is the key and the value is string key and the value is string string is in the word and the character string is in the word and the character is in particular character in the is in particular character in the pattern pattern right so right so in this hash map in this hash map so basically this is a hash map only so so basically this is a hash map only so like a is the character and what is the like a is the character and what is the value it doesn't put string that is the value it doesn't put string that is the word a dot b cat and then comes the word a dot b cat and then comes the third character which is again B so third character which is again B so before inserting that inside the map we before inserting that inside the map we will check whether this character was will check whether this character was already present inside our already present inside our uh map or not so B was already present uh map or not so B was already present inside the map so we will we can ignore inside the map so we will we can ignore that right that right and before ignoring me you should also and before ignoring me you should also check whether the second beat this B is check whether the second beat this B is also corresponding to the cat or not also corresponding to the cat or not right so instead of cat suppose here it right so instead of cat suppose here it was some other animal suppose lion or was some other animal suppose lion or any any word right so B was already any any word right so B was already present inside the map but the value present inside the map but the value would have been different cat and lion would have been different cat and lion so it's a contradiction so we would so it's a contradiction so we would directly return holes from that directly return holes from that condition only that place right condition only that place right but uh yeah coming again to a this a but uh yeah coming again to a this a then a is corresponding to down we check then a is corresponding to down we check whether a is present inside of one map whether a is present inside of one map using uh just a find operation and the using uh just a find operation and the value is again down so we can ignore value is again down so we can ignore that so we will be returning true that so we will be returning true right so the edge case that we would be right so the edge case that we would be missing over here is that um missing over here is that um suppose suppose um yeah let me just figure out okay so um yeah let me just figure out okay so suppose this from the case a b b a suppose this from the case a b b a and uh here it is dog dog dog and again and uh here it is dog dog dog and again dog right so suppose this is the string dog right so suppose this is the string s which is given to us this is the s which is given to us this is the pattern p so corresponding to a we have pattern p so corresponding to a we have dog inside of a map then comes B so B dog inside of a map then comes B so B was not present inside the map this is was not present inside the map this is the map the map key and value key and value so initially we inserted a and down then so initially we inserted a and down then we come B and this term and we check we come B and this term and we check whether B is present inside the map or whether B is present inside the map or not using the key B not using the key B so B is not present which means we have so B is not present which means we have to insert this B to insert this B right so right so uh but we would be inserting this B uh but we would be inserting this B inside the map which is not correct inside the map which is not correct because because there has to be one to one mapping right there has to be one to one mapping right so dog cannot be referred by two so dog cannot be referred by two characters so this is not a correct characters so this is not a correct scenario so to overcome this what we can scenario so to overcome this what we can do is like do is like this can be the hash map one and we can this can be the hash map one and we can also create another hash map let's call also create another hash map let's call it hashmap 2. inside which it hashmap 2. inside which the key value will pair will be there the key value will pair will be there and the key would be string and the key would be string and the value would be character and the value would be character basically the reverse part of this uh basically the reverse part of this uh earlier map right so whenever I inserted earlier map right so whenever I inserted a and off so I can also insert dog and a a and off so I can also insert dog and a over here then comes B and dog so before over here then comes B and dog so before think of B and down right so B and Dom think of B and down right so B and Dom so here I will check whether B is so here I will check whether B is present inside the hashmap one or not it present inside the hashmap one or not it is not present then also I am going to is not present then also I am going to check check whether dog is present inside the whether dog is present inside the hashmap 2 or not so it is already hashmap 2 or not so it is already present which means this is not a valid present which means this is not a valid scenario basically both of them has need scenario basically both of them has need uh uh has not to be present inside in any of has not to be present inside in any of the maps the maps right so these two uh Maps would help us right so these two uh Maps would help us basically tell us that no two characters basically tell us that no two characters are corresponding to a similar word or are corresponding to a similar word or two two same words are not corresponding to same words are not corresponding to different characters different characters like in this case dog is being referred like in this case dog is being referred by A and B so if we would have been by A and B so if we would have been using just a single hash map then we using just a single hash map then we would not have been able to solve so would not have been able to solve so that's why the hashmap 2 comes into that's why the hashmap 2 comes into picture that through which we are able picture that through which we are able to look up whether there is a character to look up whether there is a character associated with that particular word associated with that particular word right so right so this is one of the approaches of the this is one of the approaches of the time complexity over here would be the time complexity over here would be the length of a string end of the string okay so and the space complexity is like we are using two maps so twice of what can be the maximum length of this so it can be the number of unique characters present inside the pattern plus the length of the string so basically the unique characters in the pattern plus the length of a string which is s right twice basically two types of that because we are maintaining two maps right so this is one of the approaches but we have a optimized approach to this as well like instead of using two maps can I solve this using a single map or a single data structure so the answer to this is yes because if You observe carefully in the problem it is mentioned that the pattern only contains lowercase English letters right so we can take the advantage of this condition so lowercase English characters which means it will lie between a to z right the pattern characters and how many are these it is 26 right so what we can do is we can create one array so this approach is actually being used at a lot of places where there is already a condition that the string characters are going to lie between 0 to 26 as in like uh per cases of lowercase characters can be present so instead of A to Z if capital A to Z are also present then instead of 26 we can create an array size of 52. but if it is already given that it will be lowercase character so I can create an array of 26 size so indexes will be 0 to 25 so basically each index is going to represent a unique character so this is going to represent a and b e z c and the last index is going to denote Z right so what I am going to do is so suppose this is the string a b b a then comes stock cat cat dog right so I go through this first character a and then check what is the values on top and I am going to initialize all of these values suppose with spaces or any random uh string right so corresponding to a I will find what is the index in this array how we can do that a minus this so this is going to give me the Sky value of the Sky value of a right so I um so it will give me zeroth index so I will go to the zeroth index and check what is the current value so it is currently empty so I will insert dog over here then I will go to B corresponding to that the index will be 1 and I will insert cat in this string array so it is a string array and again for responding to B I will see what is the value it is cat so I will look inside my array I will see that it's already capped so I can ignore that I will go to the next pattern character corresponding to a it is dog I will go inside my array I will see what is the already existing value if it is not there right so it is already log so I can ignore that so once I have reached the end of my pattern so it means that all the characters have been I traded over so I can ignore I can return true from the Loop right so let's try to see what is the how I have coded that so I've already implemented but I will try to explain what's the logic behind that so I've created a string area of 26 size and initialized all the elements of that string array with spaces right then what we need to do is so initially we are given this string right dog space cat space cat space dog so what I have done is I am creating a list of words out of that so instead of list like I can say Vector in C plus plus so what I have done is I've created a list dog cat cat and dog so that would require string passes but if you are using Java then you can directly use a split function which will give you this list right so in C plus plus uh to get the corresponding words out of this string I have written by while loop which like if you are in an interview then enter your might want you to implement this functionality as well like interviewer may ask you to not use the existing STL and instead of that you might have to write this logic yourself right so this logic is nothing but creating a list of or the vector of words in the given string given string s this one right so we have a word list associated with us now right so in one more condition I am checking over here is just that like the size of the list should be equal to the number of connectors in the pattern right so here we can see we have four characters so correspondingly we even having four words over here so if it if it is not the case then we have to return false right so that's the basic check I'm doing over here and uh the this for loop I guess like I've already explained so I'm taking one um character in the pattern at once so that c is equal to pattern of I I am looking for that particular I am looking for that particular character for the first time or not so character for the first time or not so if I am looking for that particular if I am looking for that particular character for the first time character for the first time right so here I am checking right so here I am checking that uh like if the value that uh like if the value if that particular word was already if that particular word was already present in some other index or not right present in some other index or not right so in this example A B B A and uh sorry so in this example A B B A and uh sorry this one a b b a dog dog dog dog right this one a b b a dog dog dog dog right so this was let me just quickly explain so this was let me just quickly explain this example so in this vector 0 1 2 3 we have talked to this 45 so in the zeroth index it will be dog then comes B and this dog right so B is nothing but the first index so I can't directly insert raw in this first index why because dog was already present inside the zeroth index so before inserting I am I treating over the complete array of length 26 whether that particular word was already present inside the array or not it if it was already present then I need to return false right and otherwise if it was not present and then I just directly insert that particular word inside in that particular index so C minus a would give me the index in that particular array ARR and uh if it is not the equal like array of C minus a would give me the index value and and it is not equal to word list of I which means I have to return false right if any of these condition is not uh met then ultimately I am returning true which means I have reached the end of my pattern string and it's already tested but still oh yeah runtime memory usage are fine so as you can see like runtime and memory usage are on a very uh higher side so that's because like we are just using an extra space of 26 length instead of creating two maps that was there in the first Brute Force approach right and um yeah complexity wise as well like if we look over here is the time complexity would be if we have the given string then we are iterating over the complete string and uh in the worst case for every scenario I will be doing that 26 number of times because here I am checking right in this for Loop I'm checking whether that particular word was already present inside in any of the or indices of the error vector or not so in the first case that will be 26 times but that would really happen right it's a Time complexity where it is that and space complexity wise it is just of 26 which is constant so we can ignore that oh one right so we have a reduced space complexity part where the time complexity Still Remains the Same right so that's why memory usage is on 83 level like this yeah so I hope the solution is clear so please let me know if there is a better approach to this problem or if I have made any mistakes over here or any improvements are needed so until next time take care and I will see you thank you | 2024-03-22 14:23:56 | 290 | Word Pattern | LeetCode 290 | Strings | HashMap | 100% Faster |
|
fBFv075BvOY | hey what's up guys this is john again so uh this time 1591 so uh this time 1591 stringed printer number two so this time the stringer the stringed printer will print following the below the two special rules here on each turn right the printer will and this will cover the existing colors and this will cover the existing colors in the in the rectangle in the in the rectangle and second once the printer has used a and second once the printer has used a color then the color same color cannot be used again so which means that one color can only be printed once okay and then you're given like a matrix and the value on the matrix are the targeted values and your task is to check if it's possible to print to print the start matrix by using this string printer so for example this one right so the the so for example this one right so the the target the target target the target matrix is like this so obviously the matrix is like this so obviously the first time first time we need to print one and the second time we need to print one and the second time we'll print we'll print two okay and two okay and the example two is like more complicated the example two is like more complicated one so for this one one so for this one the again right the first the first time the again right the first the first time we'll print we'll print once on all the uh the cells and then once on all the uh the cells and then the set and then we print three the set and then we print three and then we print uh either five or four and then we print uh either five or four it doesn't really matter it doesn't really matter so that that's that and they're like so that that's that and they're like there are a few examples that cannot there are a few examples that cannot print to the final result and print to the final result and there's some constraints here right so there's some constraints here right so i'm i'm like within 60. so how do we approach this this problem so how do we approach this this problem right right the uh i think one thing we might uh the uh i think one thing we might uh we need to observe is that you know for we need to observe is that you know for each of the colors each of the colors and in order to be able to print and in order to be able to print this color it has since it has to be a this color it has since it has to be a rectangle rectangle it means that we need at least for each it means that we need at least for each of the colors we have to print of the colors we have to print within a range right because it uh the within a range right because it uh the printer can only print the uh uh printer can only print the uh uh a rectangle so which means that for each a rectangle so which means that for each color color the first thing we need to do is that the first thing we need to do is that which we need to get uh the border which we need to get uh the border for this color basically the left the for this color basically the left the right right the top and the bottom so which means that we can pre-process uh this matrix and we can use a dictionary or hash map to store the uh the four borders for each color and once we have that i think next thing we have a we have some options but the way i use to solve this problem is that by using a dfs search and to be able to write the dfs logic so we also need to explore some of the examples that can that will return false so for example this one right so for this one we have one two one two one two and one two one so why this one is false right this is because let's say uh we we start we try to start we try to print uh from from left from uh top left corners and then we try to print everything so here if we if you want to print one since the the border for one is is what is from left to right basically is everything it means that we have to print we have to print uh ones all together and then by while we're printing once since we if we want to print two right then we if we want to print two right then we also need to print also need to print uh the entire the entire like the uh uh the entire the entire like the uh array here at the in the entire array here at the in the entire board here but while we're printing two board here but while we're printing two here we see okay here we see okay so there's already a one that we have so there's already a one that we have been previously printed been previously printed and then that's why the answer is it's and then that's why the answer is it's false right false right so another example is like this this one so another example is like this this one so we have one so we have one one one and then three one one one and then three one three again right so first we print one three again right so first we print one and one once we print one there uh the and one once we print one there uh the next one we wanna print is three but next one we wanna print is three but while we're printing three here we see while we're printing three here we see that okay so while printing three we that okay so while printing three we we need to print this one we also need we need to print this one we also need to print this one two to three to print this one two to three but we see okay so what this this number but we see okay so what this this number here is one which have here is one which have which are the ones the colors we have which are the ones the colors we have been printed pro been printed pro previously that's why we need to return previously that's why we need to return false so then we have this conclusion false so then we have this conclusion right right so the conclusion the conclusion is like so the conclusion the conclusion is like this so every time this so every time when we do a dfs print every time let's when we do a dfs print every time let's say we say we start from from one here and start from from one here and we start from one and then we try to we start from one and then we try to print out everything based on the the print out everything based on the the borders borders of the current colors and once we have of the current colors and once we have seen a different seen a different a different colors and then we'll then a different colors and then we'll then we'll start print we'll start print that one we'll start print that that that one we'll start print that that color color basically that's a dfs recursive call basically that's a dfs recursive call and every time when we try to print the and every time when we try to print the colors colors if we have seen a cell that's if we have seen a cell that's that equals to the previously that equals to the previously uh scene cell the colors are uh scene cell the colors are previously printed colors then it means previously printed colors then it means that that it's a count there's a there's a it's a count there's a there's a conflict then we need to return false conflict then we need to return false because for example if if this one since because for example if if this one since it's returned true it's returned true let's see let's say we are printing one let's see let's say we are printing one here and then we are looking here and then we are looking we have a three now the dfs will go we have a three now the dfs will go inside to print inside to print three right so we bring this one this three right so we bring this one this one this one one this one and this one because but there's no ones on the but there's no ones on the on the range of three right on the range of three right because while we're printing three there because while we're printing three there all we can see is all we can see is all we can see is three or four all we can see is three or four right so because the the last one is right so because the the last one is four but it doesn't really matter four but it doesn't really matter because four has not been uh seen because four has not been uh seen or has been printed yet only one has or has been printed yet only one has been printed yet as long as there's no been printed yet as long as there's no ones while traversing uh while trying to ones while traversing uh while trying to print print three then we're we're okay right and three then we're we're okay right and then then so while we're at here that the three so while we're at here that the three has been printed with no issues has been printed with no issues right and then then the last one is four right and then then the last one is four actually actually so while we're seeing four there we'll so while we're seeing four there we'll start printing four start printing four so the four is also okay because there's so the four is also okay because there's no no one or three while printing four one or three while printing four and then five so on so on and so forth so which means that we're going to maintain while we're doing the dfs we're going to maintain the uh like a previously printed colors but basically it's going to be a set and then we decide we just try all the colors if odd colors have passed the dfs track then we're going to return true otherwise as long as there's no color one color that failed and then we know okay there's uh there's going to be a it's going to cool so then let's try to do the coding cool so then let's try to do the coding here here um so like i said i'm going to create um so like i said i'm going to create like a border border like like a border border like as a dictionary to store the uh the as a dictionary to store the uh the butter for each of the colors butter for each of the colors right and then we have a m right and then we have a m the the length of the target grid and then equals the length of the so for i in range of so for i in range of m and for j in range m and for j in range of n so the current color of n so the current color the color is the is the t the color is the is the t i and j right so if i and j right so if if the c is not in the border if the c is not in the border dictionary right so we simply do have dictionary right so we simply do have other colors equals to what the uh basically i'm having four uh elements which is the top down left and the right else else which is update right we update the border of c equals to the what so first one is the left right we could uh bother dot color uh bother dot color dot zero okay right that's the left and dot zero okay right that's the left and the for the right is max right i dot the other c dot now this one is one right then similar for the top one minimum of j dot other then i have like uh the bottom ones then i have like uh the bottom ones maximum j maximum j dot father c dot three yep so that's how we uh do that i think i have a so now i can just simply loop through so now i can just simply loop through the other colors the other colors right so the colors is actually the uh right so the colors is actually the uh it's the set in in the bother the key of it's the set in in the bother the key of of the bothers right so i can just do a of the bothers right so i can just do a this one colors right and then um this one colors right and then um we're going to have like two things so we're going to have like two things so we have the first one is the scene the we have the first one is the scene the same one right the scene the set same one right the scene the set and then we have a in in progress it's and then we have a in in progress it's also a set also a set so we're basically maintaining two sets so we're basically maintaining two sets here here so for color in in the colors so for color in in the colors and if not dfs right if not dfs colors and if not dfs right if not dfs colors then we simply return fast because it then we simply return fast because it means that this color means that this color has a has a conflict which means we need has a has a conflict which means we need to return the to return the the fast otherwise in the end we return the fast otherwise in the end we return true here true here so now the uh the dfs right so for the dfs you know like i said so if each color basically so that one of the exit point an exit entry uh point is the uh if the current one in the in progress right then we just return fast like i said right because if the current one has been uh printed previously and then we just returned fast and then otherwise we just do a we just try to print right visit uh for this color basically we have the border of the color dot zero right that's going to be color dot zero right that's going to be the row the row and the other dot color dot one and the other dot color dot one plus one similar for the uh plus one similar for the uh for columns we have j here it's going to for columns we have j here it's going to be a two be a two and a three okay and then basically if the the if the target.inj it's not that it's not equal to the current colors then we need to do a uh another dfs right but first but first we need to update the process but first we need to update the process actually yeah we need to up uh like add the process um yeah and then we do uh and then later on we'll okay so that's the because you know okay so that's the because you know whenever we need to do a whenever we need to do a recursive dfs car a dfs car here we need recursive dfs car a dfs car here we need to up to up add the current one to this in in add the current one to this in in progress so that later on progress so that later on you know the uh we can use this one to you know the uh we can use this one to act to return files here act to return files here and then basically if not dfs right so if the df has to return false here uh target inj right uh target inj right if this one is false we also return fast if this one is false we also return fast here here and in the end we return true so yeah so basically here i'm doing the uh every time when i when i see a different colors while printing the current colors i'll go i'll go like to print try to print that color okay and while printing that colors right if if the color has like uh has a conflict with the previously printed colors then i simply returned false and as long as there's one uh element that can return false then the the whole thing will need to return false otherwise if everything works fine then i will return true and that's how the how i check the colors okay so that's the the basic logic but if you just leave the code as it is right now it will tle so the reason being is that you know let's say since we had we're doing like a a for loop check here right and for each of the photo pier we do another and we do another like the uh another dfs which means that if we have like a many ones here right for example for for the first the for the first the first one while processing the current colors we while processing the current colors we might also might also like like what uh we like like what uh we we will also try we also print basically we will also try we also print basically process process the nested colors and since we were the nested colors and since we were looping through all the colors because looping through all the colors because one let's say if one let's say if there's like one one here right so if there's like one one here right so if they're like a 10 colors they're like a 10 colors if well and the the first one is the is if well and the the first one is the is the colors that we we process first the colors that we we process first right and then we'll basically while right and then we'll basically while while processing the first colors since while processing the first colors since we have dfs here we have dfs here we will also process all the the nested we will also process all the the nested colors inside colors inside so that's why we need to introduce a so that's why we need to introduce a second second uh second set here to help us uh second set here to help us to not reprocess the same colors to not reprocess the same colors that's why the uh every time right once that's why the uh every time right once a color it has been a color it has been printed successfully which means that uh printed successfully which means that uh the for loop is finished which means the for loop is finished which means that we have print that we have print all the cells for these colors we're all the cells for these colors we're gonna add this color gonna add this color to the thin set and then to the thin set and then on the top right we can just do this on the top right we can just do this if this color has been processed we'll we think we can call it this one or uh let's do this print it print it or uh let's do this print it print it and this one is print printing and this one is print printing printing one then print it printing one then print it so here if the color is has has been so here if the color is has has been printed before printed before then we simply return true right because then we simply return true right because it means that you know it it means that you know it has been processed so we don't need to has been processed so we don't need to check that check that otherwise you know so this one is otherwise you know so this one is printing right and this one and printing right and this one and same thing for this printing printing same thing for this printing printing and this and this print i print it okay yep i think that's that's pretty much it is current oh c yeah right so how about the time and space right so how about the time and space and time and space complexity and time and space complexity so for the time complexity uh so here we so for the time complexity uh so here we have m have m times n right so here's the m times n times n right so here's the m times n but that's not the uh but that's not the dominant dominating time complexity is actually this part so here we have um the first one is the color let's see the first we have a c means the total number of colors and then inside here we have what in each each of the dfs we have a for in each each of the dfs we have a for loop loop okay so the for loop is going to be a c okay so the for loop is going to be a c times times m times n and inside of inside the four loop here we'll also do a another dfs call which means that you know we're going to have like another times c here so this is because we only do the dfs when the color is different than the current one that's why at most we will do a uh the dfs uh c times dfs car using one uh within one loop right that's why the uh the total should be i think c times m times n time times c yeah and so that's the time complexity so for the space complexity it's it's just the uh the border the border and the uh the printed and the printing colors yeah i believe the butter will be the dominating space complexity because this one has like uh has a space so the colors it's going to be as four times c right because for each of the colors we have four elements but for the printed and printing here right it's all basically it's a it's all of c right but now it's this is a four times c so that's the gonna be the the complexity analysis here um cool yeah i think that's that's it so so this so for this problem you know the um two things right so first you have to uh you you need to pre-process the border for each colors so that you can uh use them try to print them out later on and second one is that you know you have to be able to find the uh what's going to be the the condition the condition for for for returning false and with the condition is the uh while printing the current color right and then uh if we see a different colors we'll i will try to print that color instead if any uh if any cell right if any uh if any cell right that on the current path while printing that on the current path while printing the current colors the current colors is the colors we have been printed is the colors we have been printed before before then it's going to be a false otherwise then it's going to be a false otherwise it's going to be true so that's why we it's going to be true so that's why we basically we're introducing two set here basically we're introducing two set here so the so the the first one is the printed which help the first one is the printed which help us to us to record what are the colors we have been record what are the colors we have been printed successfully right then to printed successfully right then to avoid some duplicate duplicated avoid some duplicate duplicated calculation calculation second one is the the printing for the second one is the the printing for the current colors current colors right so if there's a uh right so if there's a uh how many uh colors we have been printed how many uh colors we have been printed before which is our printing before which is our printing and here's like backtracking okay and here's like backtracking okay because you know the i think this this because you know the i think this this place is this part is always kind of place is this part is always kind of obvious because obvious because after printing the current colors right after printing the current colors right we are we are we're not printing that colors right for we're not printing that colors right for example the three example the three and and four and so once the color has and and four and so once the color has been printed been printed successfully and then the uh successfully and then the uh we need to remove it from the current we need to remove it from the current printing set yep i think that will be everything i want to talk about for this problem okay thank you for watching this video guys stay tuned | 2024-03-21 14:48:39 | 1,591 | LeetCode 1591. Strange Printer II |
|
U0qiHUSnSJY | all right let's look at this problem called reconstruct itinerary so you're called reconstruct itinerary so you're given a given a list of tickets uh ticket represent uh list of tickets uh ticket represent uh starting airport and ending airport and starting airport and ending airport and in your list of tickets is for a single in your list of tickets is for a single person and you're also given the person and you're also given the starting station the starting airport so starting station the starting airport so you started from JFK you have to you started from JFK you have to reconstruct the itinerary in the order reconstruct the itinerary in the order and return it so for example in this and return it so for example in this case from these tickets you can create a case from these tickets you can create a directed graph and you know gfp is a directed graph and you know gfp is a starting point so you just Traverse and starting point so you just Traverse and you go to HSC and this is quite clear uh you go to HSC and this is quite clear uh there's one more condition that is given there's one more condition that is given which is if there are multiple which is if there are multiple itineraries you should return the itineraries you should return the itinerary that has the smallest lexical itinerary that has the smallest lexical order when it is a single Stream So what order when it is a single Stream So what let's understand that in the second let's understand that in the second example so in a second example you can example so in a second example you can create two itineraries one as you go create two itineraries one as you go from JFK to SFO SFO from JFK to SFO SFO [Music] but in this case because ATL is smaller so you would prefer this one you have to handle this as well so how do you handle this so the simple way to handle this when you represent this graph in adjacency list like for example here for each node or when you are adding the neighbors you add those numbers in sorted order and you can use your priority view for that so when you look at JFK um you see a ticket from JFK to SFO QT another ticket from JFK to API so let's say first you encounter this JFK to our support so you add this in the priority queue and then when you add eight years because it's bright if you the first element which will give you will be the smallest one so that that is a bit 200 lexical order but just like second order is not sufficient so what I mean by that is look at this look at this example now here let's say a starting airport is given as a so yes you can go from A to B but then you are stuck right so yes you want to give reference to be representatively mean that that will give you the right uh itinerary here in this case the only valid identity is you go from a to c from C back to a and then from A to B so yes you want to give priority to lexical order but that doesn't necessarily mean um then that will give you the right technology so you have to consider both practices order and I want to uh itinerary so let's look at an example to sort of understand how to solve this so I I want to see example of this example so first of all let's try to understand uh let's say these are the different tickets these are different graphs that are given to us we have to find a valid itinerary here we have to find a valid itinerary here so we have to find a valid path that so we have to find a valid path that uses each ticket once and only once and uses each ticket once and only once and the ticket here is Edge right so it sort the ticket here is Edge right so it sort of forms a directed graph which has a of forms a directed graph which has a eulerian path that's what it really eulerian path that's what it really means so let's first understand what means so let's first understand what eulerian path is so let's write out the eulerian path is so let's write out the in degrees and out degrees for each of in degrees and out degrees for each of every node integral is essentially the every node integral is essentially the number of edges coming into the node and number of edges coming into the node and out degrees the number of edges going out degrees the number of edges going out of the node so let's look at a and out of the node so let's look at a and here for example let's assume is a here for example let's assume is a starting table is given to us so from a starting table is given to us so from a how many uh how many edges are coming in just one how many edges are going out you can see there are two right for B how many X's are coming in we can see for B there are two edges coming in and one Edge going out for C even if there are four total edges two are coming in and two are coming out and same is the case for D there are one two three four two coming in and two and then for E there is one coming in and then for E there is one coming in and one coming out and one coming out now we don't have to really look at this now we don't have to really look at this it is already given to us that this a it is already given to us that this a valid itinerary does exist but the sort valid itinerary does exist but the sort of tools so in a directed graph uh a of tools so in a directed graph uh a valid euclidean path exists valid euclidean path exists in two cases one either all the nodes in two cases one either all the nodes have their integral degree equals in have their integral degree equals in this case that's not the case you know this case that's not the case you know for c d and e then individual degree are for c d and e then individual degree are same but for not for a and b so that's same but for not for a and b so that's the other condition if all the nodes the other condition if all the nodes have equal integral outages then you have equal integral outages then you even have a euclidean cycle A and B have exactly one difference in the end degree analytically and in a the out degree is more than b the in degrees mode this tells you there will be a cpedian path it starts from here because this is an extra out degree right so there is one path going out extra and for B there is one path going coming in extra so a will be the starting point we will do the ending point and C and D will the middle once so that is the strategy now we want to sort of also build what you said is the the adjacency is less also build out the adjacentialist presentation right so you and you want to follow the lexical order so from a what all nodes you can go to you you see there are a is an out degree of two so you can go to B and B you put it in sorted order so BND from B you can go to C from C you can go to A and D to give reference to a from B you can go to b and a you can reference to B from e you can go to C that is your adjectives representation of the graph now what do we do we start from a okay so we go a and we keep following this classical you go to First cry which is B so you you go to First cry which is B so you remove this because your Traverse this remove this because your Traverse this and so you go to and so you go to B from B you will go to C so you remove the C from a you go to D from a you go to D we remove this D so you you have an even preference so you you have an even preference electrical order so far and you are not electrical order so far and you are not stuck here it's all good stuck here it's all good from D you go to B from D you go to B and at B are stuck all the edges have and at B are stuck all the edges have not been completed but you are stuck so not been completed but you are stuck so what do you how do you handle it at this what do you how do you handle it at this point so this premises order tells you point so this premises order tells you if where your is your ending point so if where your is your ending point so now let's call this as the final i t in Array you find itinerary you find itinerary B is the one that will be the last to B is the one that will be the last to reach and now from D we went into B so reach and now from D we went into B so what you do is okay B I know is the last what you do is okay B I know is the last five let's remove B and let's continue five let's remove B and let's continue so from D you can further go to E so from D you can further go to E okay so let's do this so from B now I go okay so let's do this so from B now I go to e from e I go to C and now at B there is nothing else and now at B there is nothing else so now that means this is the last most so now that means this is the last most node node so now so now in front of d in front of d asically what you can do is now because asically what you can do is now because everything is empty you could you can everything is empty you could you can just put uh just put uh the entire this video from D to B is the entire this video from D to B is already a path right that essentially already a path right that essentially means that your final path would be you means that your final path would be you add this B here then we'll go to C and you do the same thing again so now see you see if there is any further paths that you could look at they are known here so you will see then you would look at the key and you would see there's any further paths to go at e here there isn't for you and and that is how you sort of build from E then you add C then you add a then you add C and you add p and then you add you have a and select your final path from ABC to go back to a then you go to D then you go to e c d and then B and that's your final path so that's the plate right so how do you have a code for it so essentially first you create this ad essential list with the priority queue then you start from a till you get stuck you keep privacy then you get stuck because where you guys stuck is the last guy and then you continue remove that guys and then you continue again when you get stuck that is your second last guy again then you get to that's the third line square and so on and so forth right let's build out a code for this okay so the first things first you want to build an adjacency list so let's uh hash map a key is the airport name and we are using a priority queue to prefer the lexical order so we use a priority queue um uh what else what else we have uh let's maintain a linked list of spring which is our final itinerary and as you saw here we are sort of and as you saw here we are sort of maintaining a stack right and we've got maintaining a stack right and we've got that we removed that we added it here that we removed that we added it here and then we continued further so for and then we continued further so for that let's maintain a stack right and let's first build the addition how do you build that sense of this um ticket ticket foreign [Music] [Music] destination is destination is one one so if so if adjacency list does not contain the key adjacency list does not contain the key for source then you first add okay so now you are guaranteed that okay so now you are guaranteed that adjacency list dot get Source will give adjacency list dot get Source will give you uh you uh that is a priority queue in that that is a priority queue in that priority queue you add this destination priority queue you add this destination right so your list is complete now what right so your list is complete now what you do you do in the stack in the stack you know the starting point is JFK you know the starting point is JFK that's given to us so the first there is that's given to us so the first there is always JFK so you add JFK and now keep on just traversing and at some keep on just traversing and at some point you might get stuck and we'll point you might get stuck and we'll handle that when you get stuck is when handle that when you get stuck is when you take the first uh the topmost you take the first uh the topmost element on the stack and then continue element on the stack and then continue right so or other while or other while no it's quite okay weekend last equals to well if you're struck how do you know if well if you're struck how do you know if you are stuck right so you're stuck if you are not presentation start if you don't even present content key or if you don't even present content key or the list is empty let's dot get lost Dot either the keys not present if it's present in sample in this case what do you do well in this case you do that so you take the filament out of the stack and out in this route Dot you add it in the route okay let off so you add you can also do like so you take it out you can also do like so you take it out and then you add it right that is good and if that's not the case kind of simple you do kind of simple you do start dot push so you you want to remove the edge right so you you want to remove the edge right we were removing the action now we are we were removing the action now we are looking at for example from JF for looking at for example from JF for example from here from here you went so example from here from here you went so you push into the stack now from a you you push into the stack now from a you want to push B into the stack but you want to push B into the stack but you also want to remove this uh Edge right also want to remove this uh Edge right so what you do is you do let's look at that is it and again obviously stack that is it and again obviously stack won't be empty won't be empty so so you'll either remove it at the end of this you do return group at the end of this you do return group okay let's run it's a runtime error okay it's a runtime error okay if adjacency is not contains key alright accepted submit we can talk about time opacity clearly we can talk about time opacity clearly you know it's just a number of edges so you know it's just a number of edges so slang compressor is just oapy space slang compressor is just oapy space complexity how much elements can be complexity how much elements can be written as tax orp so both times Your written as tax orp so both times Your Capacity is over weak all right | 2024-03-24 10:43:35 | 332 | Reconstruct Itinerary | LeetCode 332 | Java |
|
TIojOkG1E4U | alright guys welcome to our channel code with sunny and in this video i will be with sunny and in this video i will be talking about the heart problem of the talking about the heart problem of the lead code its index is eight five zero lead code its index is eight five zero and it is its name is like rectangle and it is its name is like rectangle area second okay so before moving on to area second okay so before moving on to discuss this problem is like discuss this problem is like i just want to summarize the topics that i just want to summarize the topics that is being related to this one is like is being related to this one is like geometry you need to have the good geometry you need to have the good knowledge of geometry like the figures knowledge of geometry like the figures how the overlapping is being done how we how the overlapping is being done how we are going to handle the overlapping like are going to handle the overlapping like in this problem we have some overlapping in this problem we have some overlapping of figures and we need to calculate the of figures and we need to calculate the area right so and for the case of area right so and for the case of overlapping of figures you need to overlapping of figures you need to consider that area exactly one time okay consider that area exactly one time okay how we are going to handle all that case how we are going to handle all that case and and what would be the best way to code i what would be the best way to code i will tell all of that for now let's will tell all of that for now let's understand this problem okay so we'll be understand this problem okay so we'll be given a list of axis aligned rectangles given a list of axis aligned rectangles okay so each rectangle will be given the okay so each rectangle will be given the four datas like the four datas like the bottom left corner you can see x1 y1 bottom left corner you can see x1 y1 and top right corner x2 y2 right and top right corner x2 y2 right are the coordinates of bottom left are the coordinates of bottom left corner and the coordinates of top right corner and the coordinates of top right corner of the earth rectangle okay so corner of the earth rectangle okay so we'd be given n rectangles find the we'd be given n rectangles find the total area covered total area covered by all rectangles in the plane that is by all rectangles in the plane that is if you draw out the rectangles if you draw out the rectangles then there would be some they'll be then there would be some they'll be occupying some area and we to report the occupying some area and we to report the all the area that is being covered now all the area that is being covered now it is obvious that two or more it is obvious that two or more rectangles have the are going to occupy rectangles have the are going to occupy the same area in the 2d plane then we the same area in the 2d plane then we need to account for that area exactly need to account for that area exactly one time you're not going to count two one time you're not going to count two or more times if you're going to count or more times if you're going to count two or more times this problem should two or more times this problem should not be a hard problem right okay since not be a hard problem right okay since the answer may be too large return it the answer may be too large return it modulo this prime number modulo this prime number okay so i'm going to discuss all the okay so i'm going to discuss all the examples okay so you need not to be examples okay so you need not to be worried about so for now let's look over worried about so for now let's look over the constraints how this is going to the constraints how this is going to help us okay you can see the rectangles help us okay you can see the rectangles length that is the input rectangle that length that is the input rectangle that is the total number of rectangles is 200 is the total number of rectangles is 200 okay so we can have a of n squared okay so we can have a of n squared solution we can have a offensive log of solution we can have a offensive log of n solution right because it is also n solution right because it is also going to satisfy within the given time going to satisfy within the given time constraints uh we can also have n cube constraints uh we can also have n cube solution like it should be around 8 into solution like it should be around 8 into 10 wish to the power 6 and this is like 10 wish to the power 6 and this is like within the within the limited number of iterations and this is limited number of iterations and this is good okay so for now in this uh like in good okay so for now in this uh like in this video i have i'm going to explain this video i have i'm going to explain it out the off and cube solution in the it out the off and cube solution in the best possible way like uh i know the best possible way like uh i know the complexity is like huge we can have both complexity is like huge we can have both n square solution also but to understand n square solution also but to understand this problem to have a deeper feeling this problem to have a deeper feeling about this problem what is actually been about this problem what is actually been happening over here i will recommend to happening over here i will recommend to like to understand the open cube like to understand the open cube solution then we we can optimize that solution then we we can optimize that okay and there is another solution that okay and there is another solution that i am also going to discuss it should be i am also going to discuss it should be like of n cube logarithmic open and like of n cube logarithmic open and logarithmic and that is not good but it logarithmic and that is not good but it has a good complexity i don't know why has a good complexity i don't know why ah we will discuss it later on for now ah we will discuss it later on for now let's try to understand this problem let's try to understand this problem with the help of examples and diagrams with the help of examples and diagrams and then we together find out the best and then we together find out the best solution for this problem so let's move solution for this problem so let's move further okay so let's try to figure out the analyze of example one okay so we'd be given the first rectangle as zero zero two two okay so let's say it is like zero zero that is at this position and it is like 2 and 2 that is 1 2 1 2 it is at this position so the very first rectangle is about okay i'm going to do like that okay so okay i'm going to do like that okay so this is the area that is being covered this is the area that is being covered and this like the answer is going to be and this like the answer is going to be like at least this one also okay but like at least this one also okay but there may be some overlappings let's there may be some overlappings let's discuss it about one zero two three is discuss it about one zero two three is another like one zero so it should be another like one zero so it should be like one like one okay so let me use another color it okay so let me use another color it should be like x one and it is y zero so should be like x one and it is y zero so it is over here it is over here and it's like two three two and it's like two three two one one two and three yeah it is this one so it two and three yeah it is this one so it means that the means that the like the rectangle is going to hold this like the rectangle is going to hold this one area okay now you can see that this one area okay now you can see that this area is being overlapped area is being overlapped okay so we are not going to account for okay so we are not going to account for this area because we have already find this area because we have already find out that area okay so we are always out that area okay so we are always going to consider some unique areas for going to consider some unique areas for the given rectangle it is like only this the given rectangle it is like only this one okay and let's look over the another rectangle one zero three one like its of one and zero and it's of three and one one two three and one okay so this one in this one it means that all the positions over there now you can see that there is also some overlapping so we need to consider only the unique area so we are going to consider only this one okay so these are like the shaded part is like our answer and we need to report that answer so what is the answer you can see one two three four five six i think six should be the answer for this one yes it is the answer okay so it means that you need to account for the like distinct blocks that is being not repeated like if you have been already calculated that area we are not going to do that okay now the thing is like how we are going to manage that and like in a limited time we have to we have to write down the code right so we need to have an efficient way to find out that area and check that these are going to be like accounted for the very first time if it is a repetition you're not going to do that okay now the problem arises when you can see the rectangle so 5 is like 10 raised to the power 9. now if it is around 10 raised to the power 5 you are going to maintain a linear vector or 2d vector or something like that i don't know and you are going to do that easily but here it is like 10 raised to the power 9 and this creates the problem how this creates the problem how we are going to find it out that there is an overlapping over here okay so no need to worry about let's try to understand this okay so consider this example like there okay so consider this example like there is some overlapping you can see over is some overlapping you can see over here then what i am going to do is like here then what i am going to do is like the best way to solve this problem is the best way to solve this problem is like map all those x coordinates which like map all those x coordinates which are distinct right i'm talking about the are distinct right i'm talking about the distinct x coordinates in some vector distinct x coordinates in some vector linear vector like in a sorted linear vector like in a sorted non-decreasing format so you can see 0 non-decreasing format so you can see 0 70 100 220 70 100 220 270 and 320 these are the distinct x 270 and 320 these are the distinct x coordinates you can see 0 70 100 coordinates you can see 0 70 100 220 220 270 and 320 are the distinct x 270 and 320 are the distinct x coordinate similarly we are going to map coordinate similarly we are going to map all the all the distinct y coordinates over here these distinct y coordinates over here these are the y are the y and these are the x and these are the x okay now these are the distinct ones now okay now these are the distinct ones now the thing is like when we have having the thing is like when we have having some rectangle we need to uh include some rectangle we need to uh include that area which are not which have not that area which are not which have not occurred right so mapping these x unique occurred right so mapping these x unique x coordinates like this one and unique y x coordinates like this one and unique y coordinates like this one is going to coordinates like this one is going to help us in the best possible way also help us in the best possible way also note that we cannot maintain a linear note that we cannot maintain a linear size vector of the maximum possible size vector of the maximum possible height orbit because rectangle of ij can height orbit because rectangle of ij can vary up to 10 raised to the power 9 and vary up to 10 raised to the power 9 and if you are going to make a linear vector if you are going to make a linear vector of of like for the x coordinate and y got size like for the x coordinate and y got size to a 10 raised to the power 9 this is to a 10 raised to the power 9 this is not possible right come on okay so we not possible right come on okay so we have to do something interesting and the have to do something interesting and the interesting part is like we are going to interesting part is like we are going to have a unique x coordinate in some have a unique x coordinate in some linear vector unique y coordinates and linear vector unique y coordinates and some linear vector now how we are going some linear vector now how we are going to calculate the areas okay to calculate the areas okay now consider that we're going to have a now consider that we're going to have a like we are talking about the very first like we are talking about the very first rectangle this is being introduced right rectangle this is being introduced right now now okay so you can see that it is going to okay so you can see that it is going to vary from 0 comma 0 to 100 comma 100 vary from 0 comma 0 to 100 comma 100 right right okay so it is going to vary from like x okay so it is going to vary from like x is varying from 0 to is varying from 0 to like 0 up to 100 like 0 up to 100 and y is also varying from 0 to 100 and y is also varying from 0 to 100 okay now we need to include all those okay now we need to include all those areas which are for this rectangle areas which are for this rectangle okay how we are going to do that okay okay how we are going to do that okay the very best way is to like consider the very best way is to like consider every adjacent part 0 to 70 every adjacent part 0 to 70 and consider like and consider like not talking about consider every not talking about consider every adjacent ones adjacent ones like for 0 to 70 there are 0 to 10 like for 0 to 70 there are 0 to 10 adjacent 10 to 30 adjacent and 30 to 70 adjacent 10 to 30 adjacent and 30 to 70 adjacent 7200 adjacent like for every 0 adjacent 7200 adjacent like for every 0 to 70 to 70 x segment we are having different y x segment we are having different y segments as segments as 0 to 10 like uh this is for 10 1 0 to 10 like uh this is for 10 1 like for every 0 to 70 we would have like for every 0 to 70 we would have being uh sorry 0 to 70 only we're having being uh sorry 0 to 70 only we're having uh uh y from 0 to 10 y from 0 to 10 and like from 10 to 30 also like from and like from 10 to 30 also like from this to this we would have be having this to this we would have be having like of this one like of this one and similarly we're having from 30 to 70 and similarly we're having from 30 to 70 so where is 70 or 70 is up to this one so where is 70 or 70 is up to this one we would be having this one and it's we would be having this one and it's 7200 where is 70 and it is hundred we 7200 where is 70 and it is hundred we would be having this and you can see would be having this and you can see that we are accounting for only the that we are accounting for only the distinct ones still this rectangle distinct ones still this rectangle contains much more area which is not contains much more area which is not covered we are going to introduce it covered we are going to introduce it later on you can see i'm talking about later on you can see i'm talking about only 0 to 70 part what about 70 200 we only 0 to 70 part what about 70 200 we would be discussing later on okay so for would be discussing later on okay so for 0 to 70 we'd be dividing each segment 0 to 70 we'd be dividing each segment from 0 to 100 where from 0 to 100 where the y coordinate lies into some the y coordinate lies into some different parts you can see from 0 to 10 different parts you can see from 0 to 10 from 10 to 30 30 to 70 and from 7200 from 10 to 30 30 to 70 and from 7200 okay now for every okay now for every adjacent coordinates difference in the x adjacent coordinates difference in the x part we are going to find out the every part we are going to find out the every coordinate difference in the y part and coordinate difference in the y part and we are having the length also grabbing we are having the length also grabbing the width so our answer would be the width so our answer would be incremented by length into width for the incremented by length into width for the current rectangle okay now like if let current rectangle okay now like if let me just do some brute force like if we me just do some brute force like if we are only dealing with 0 to 70 what is are only dealing with 0 to 70 what is the difference in x okay difference is x the difference in x okay difference is x is 70 minus 0 is 70 minus 0 it is it would be 17 only difference in it is it would be 17 only difference in y would be like y would be like 0 to 10 in this case our answer would be 0 to 10 in this case our answer would be incremented by 17 to 10 and again uh incremented by 17 to 10 and again uh like again in the next case 17 to 10 like again in the next case 17 to 10 difference of 10 and 30 is 20 and again difference of 10 and 30 is 20 and again the next 30 and 70 so 17 to 40 the next 30 and 70 so 17 to 40 and then again 1700 so it would be and then again 1700 so it would be incremented by 17 to 30. incremented by 17 to 30. these all are the answers that should be these all are the answers that should be included when x is going to hold this included when x is going to hold this range okay now the x like the adjacent range okay now the x like the adjacent ones in the x can vary from more ones in the x can vary from more different cases like we have deal with 0 different cases like we have deal with 0 to 70 we are going to deal with 7200 to 70 we are going to deal with 7200 like for this part okay so x like y coordinates is also going to vary from 0 to 10 10 to 30 and like 30 to 70 also and similarly from 70 to 100 also and so on okay now this is not the like this was the very much easiest part now when we try to introduce the new rectangle like of this one okay so now this creates some confusion like there's some overlapping also let's try to understand that how we are going to now consider the case like this is being now consider the case like this is being involved like this rectangle from this involved like this rectangle from this one to this one and from one to this one and from like this one to this one now you can like this one to this one now you can see for this rectangle it starts at 70 x see for this rectangle it starts at 70 x coordinate and ends at coordinate and ends at 270 like this part 270 like this part we need to account for every we need to account for every possible areas okay possible areas okay and let me check it out if there is an and let me check it out if there is an overlapping also and it's y corner overlapping also and it's y corner starts from 30 and it goes up to starts from 30 and it goes up to 130 130 like of this one like of this one okay now uh when you try to explore okay now uh when you try to explore every possible adjacent x coordinate every possible adjacent x coordinate like from 70 to 100 you can see and for like from 70 to 100 you can see and for 7200 we are exploring like 30 to 70 y 7200 we are exploring like 30 to 70 y and 7200 this one and 100 to 130 now and 7200 this one and 100 to 130 now when we are at 30 to 70 you can see that when we are at 30 to 70 you can see that uh uh for every like for 7200 and for every like for 7200 and this is for x and for this is for y like this is for x and for this is for y like if we find out the 70 to 100 keys if we find out the 70 to 100 keys uh where is that 70 yes and where is uh where is that 70 yes and where is that 100 like for this part that 100 like for this part and uh what about the okay so and uh what about the okay so what about this 30 to 70 and where is what about this 30 to 70 and where is the 30 the 30 y and this is the 30 y y and this is the 30 y and uh where is that 70 and uh where is that 70 yeah this is the 70 point yeah this is the 70 point okay now the thing is like when we are okay now the thing is like when we are just having just having this as our answer for this current case this as our answer for this current case you can see that this has already been you can see that this has already been calculated calculated okay why this has already been okay why this has already been calculated okay the quite noticeable calculated okay the quite noticeable like quite noticeable thing over here is like quite noticeable thing over here is like when we are calculating 0 to 100 like when we are calculating 0 to 100 and like for this very first rectangle 0 and like for this very first rectangle 0 200 and y is also varying from 0 to 100 200 and y is also varying from 0 to 100 okay in that case okay in that case for every adjacent x you can see that we for every adjacent x you can see that we are going to visit 7200 in this one also are going to visit 7200 in this one also and we are also visiting 30 to 70 in and we are also visiting 30 to 70 in this one also this one also okay so in that case we have already okay so in that case we have already find out that area okay but now in this find out that area okay but now in this case also we are trying to visit from 72 case also we are trying to visit from 72 to 17 the difference of x and in the to 17 the difference of x and in the case for y we are visiting 30 to 130 case for y we are visiting 30 to 130 also in this case also for adjacent also in this case also for adjacent difference of 7200 like for the 7200 difference of 7200 like for the 7200 segment segment in case of x we are again visiting 30 to in case of x we are again visiting 30 to 70 and this is like when we try to 70 and this is like when we try to include this area this will give us a include this area this will give us a wrong answer because this has been wrong answer because this has been calculated twice calculated twice we need to take it we need to take it out that this should be visited exactly out that this should be visited exactly one time one time okay so if this is already visited this okay so if this is already visited this state has already been occurred we are state has already been occurred we are not going to find out that area not going to find out that area otherwise find out that this area and otherwise find out that this area and included your answer like in the case of included your answer like in the case of 7200 i'm talking about consider the case 7200 i'm talking about consider the case for 22 20 to 270 okay in this segment we for 22 20 to 270 okay in this segment we need to include the answers for every y need to include the answers for every y at every adjacent consecutive y from 30 at every adjacent consecutive y from 30 to 70 70 200 like it is the case of 2220 to 70 70 200 like it is the case of 2220 but it is at 220 yeah this is and it's but it is at 220 yeah this is and it's for 270 and why is going to vary from for 270 and why is going to vary from this one to this one this one to this one okay yeah i'm right okay so in in for okay yeah i'm right okay so in in for that case we are going to include this that case we are going to include this area every time like you can see this is area every time like you can see this is not calculated yet okay and if this is not calculated yet okay and if this is being called calculated we are going to being called calculated we are going to mark these cells as visited how it is mark these cells as visited how it is going to be done i will explain in the going to be done i will explain in the coding part and mark this cell as we did coding part and mark this cell as we did and when we are going to encounter these and when we are going to encounter these cells again we are going to discard that cells again we are going to discard that cell because you have already calculated cell because you have already calculated that area that area okay now the coding part is like very okay now the coding part is like very really very much simple if you consider really very much simple if you consider like if you have understood understand like if you have understood understand all these concepts how the overlapping all these concepts how the overlapping is being occurred and how we are going is being occurred and how we are going to find out the area we are going to map to find out the area we are going to map out all the distinct x coordinate in the out all the distinct x coordinate in the linear vector linear vector and similarly y coordinate and similarly y coordinate coordinates and we are going to account coordinates and we are going to account for every adjacent difference of for every adjacent difference of x coordinates and y coordinates for x coordinates and y coordinates for every rectangle that we are going to get every rectangle that we are going to get okay so let's move further to the coding okay so let's move further to the coding part to understand this i have many i have submitted many times i have many i have submitted many times to improve the complexity okay so let me to improve the complexity okay so let me first talk about this latest one okay so what i have done is like this is ll fall as long long and this is the modulus prime number and like first i have mapped all the unique x coordinates and y coordinates you can see that for every rectangle i have rated for that and take out their x take out their y and include into a set okay now this part is like assigning the indexes like uh we are going to map all those unique x into some vector like here you can see vector int x value vector id y value you can see that this is like x dot begin up to x like all those lm unique x which are present in this set and similarly the unique y we are going to store it in a vector like when we try to fit some element and we need to know its index also right efficiently that's why i'm using an unordered map to map every unique x as well as every unique y by giving some unique index to it okay you can see over there okay so what we are going to do is like we are also going to maintain a visited vector of the like unique x size and unique y size okay and this is for checking it out whether we have reached this state already or not okay i trade for every rectangle pick out the corresponding x coordinate if we have some like we are getting some unique value right and we are going to find out what is the coordinate of that unique x in our vector x val you can see start of x okay is going to give us the starting coordinate of this current unique value and it is going to go up to the next starting chord like for the current rectangle if you are not understanding it clearly like suppose we have from 0 0 to 100 comma 100 what is the starting coordinate of this one it is 0 and ending coordinate it is up to 100 okay so it will give us the value coordinate like the index starting index of this 0 and the starting index of this 100 okay for the current rectangle you can see v2 will be given as this position okay and it will give us the coordinate we are going to iterate for every adjacent ones you can see the start of x is starting with the current index of this unique value and it goes up to of v2 like a start of x less than the index of v2 and it goes on and similarly for the case of y you can see coordinate of y it will give us the index note that c o r d underscore x as well as c o r d underscore y will give us the index of that value which is so that unique value that which is present in our linear vector where it is present directly in the index okay that's why i've used another map to map every unique value and assign its index now consider the case like when we are talking about some adjacent keys like let's say 0 to 70 then what we are going to do we are checking out if the start of x and the start of y is already visited like if current state has been visited we have already found out the area then we are not going to do that otherwise find out the width width would be y x value of this start of x plus one that is that like if you are at this one we are going to have the 70 as the start of x plus 1 index 70 minus 0 you can see and similarly this was the width and heat would be like y value of start of y plus 1 minus this one this is the width of the current one and this is the height of the current one we need to include the area answered been incremented by the product of this one note that we are going to take care of the modulus because of the overflows like the value may exceed from that prime number we need to take the modulus with that and mark this as visited okay and finally written on the answer this will give you all test cases first now the thing is like we have some more optimized solution like of this one or let me talk about this 28 msi solving that okay so what i have done is like the concept is like similar we are going to use the lower bound technique okay so you can see that we are going to map every x unique x into some coordinate of x in a linear vector similarly in this one and we are going to have a visited vector also now for every uh like in the previous case we are using the concept of index rate we are not going to use here we are going to use the concept of value like it will start from the current value and it will goes up to till it is not equal to the v2 that let that is like the next value okay in the vector you can see it is for the coordinate of x okay now similarly for the y case also and pick out the difference like the current uh where is the present value like its index start of x minus the begin iterator similarly start of y minus the e nitrate note that here start of an x and start of y are the i triggers okay in the like you are taking the lower bond only you're not fetching out the index and it goes until it like the next value is not equal to v2 and we need to find out the width as well as say we are going to fetch out the next element and with the current element is start of x similarly start of y and start of y also next element of start of y and start off y and find out the product and increment your answer if this state is not with the trick this will also give you all test cases first okay so if you have any doubts do let me know in the comment section of the video okay okay okay so like one thing i also forget the one like time and space complexity so this case like when we are mapping the indexes so it should be like time complexity like of n cube you can see for these three loops worst case would be like of n cube similarly space complexity would be like of n square and in this case also we are using have to have a lower bound also concept so in this case we are going to have a time complexity of o and cube log of n log of n and similarly uh yeah and the space complexity would be like of n square okay i am leaving up to you to understand this in detail if you have any doubts do let me know in the comment section of the video okay and i will recommend or i will ask if you like this video share this video and subscribe to youtube channel for latest updates thank | 2024-03-22 16:13:37 | 850 | Rectangle Area II | Geometry | Maths | Line Sweep | 850 LeetCode | Day 22 |
|
nP_ns3uSh80 | hey if you're welcome back to the channel I hope you guys are doing channel I hope you guys are doing extremely well so this is another video extremely well so this is another video from the Strivers A to Z DSA course just from the Strivers A to Z DSA course just in case you're for the first time here in case you're for the first time here this is world's most in-depth course in this is world's most in-depth course in DS algo why do I see that this cost us DS algo why do I see that this cost us 456 modules by the end of the post you 456 modules by the end of the post you would have sold more than 400 plus would have sold more than 400 plus problems in DS algo and you can go problems in DS algo and you can go across the entire internet you can buy across the entire internet you can buy any of the paid courses none of them any of the paid courses none of them will be covering DS algo in such step so will be covering DS algo in such step so one thing that I can assure you is once one thing that I can assure you is once you complete the entire post you can you complete the entire post you can actually clear any of the DS algorithms actually clear any of the DS algorithms in any of the companies in any part of in any of the companies in any part of the world so till now we have covered uh the world so till now we have covered uh dell certain arrays of certain array of dell certain arrays of certain array of zeros ones and twos and in this video zeros ones and twos and in this video I'll be covering majority element so I'll be covering majority element so what does the problem majority element what does the problem majority element States it states that you'll be given an States it states that you'll be given an array of integers now your task is to array of integers now your task is to find me the element that appears more find me the element that appears more than n by two times very important than n by two times very important lining more than n by 2 not equal to two lining more than n by 2 not equal to two it has to be more than n by 2. Imagine n it has to be more than n by 2. Imagine n is eight then it should appear more than is eight then it should appear more than four times imagine n is 9 in that case 9 four times imagine n is 9 in that case 9 by 2 will take the floor value it is by 2 will take the floor value it is four so it should appear more than four four so it should appear more than four times got it so in this array if I ask times got it so in this array if I ask you which is the majority element how you which is the majority element how many like what's the length of the array many like what's the length of the array three four five six seven seven is the three four five six seven seven is the length of the array can I say two length of the array can I say two appears for four times which is greater appears for four times which is greater than n by 2 so 4 over here is your than n by 2 so 4 over here is your answer and this is what you have to tell answer and this is what you have to tell me given an array tell me the element me given an array tell me the element that appears more than n by 2 times so that appears more than n by 2 times so what will be the Brute Force solution to what will be the Brute Force solution to this particular problem it's going to be this particular problem it's going to be very simple I'll pick up an element and very simple I'll pick up an element and then I'll scan through the entire array then I'll scan through the entire array basically do a searching through the basically do a searching through the entire array and I'll count plus plus entire array and I'll count plus plus and if at the end of the day the count and if at the end of the day the count appears to be greater than n by 2 for appears to be greater than n by 2 for any of the element that is my answer any of the element that is my answer first I'll pick up two next I'll pick up first I'll pick up two next I'll pick up two next I'll pick up 3 and scan through two next I'll pick up 3 and scan through the entire array next I'll pick up 3 and the entire array next I'll pick up 3 and scan through the entire array this is scan through the entire array this is what the Brute Force solution will be what the Brute Force solution will be and the code will look something like and the code will look something like this so it's very simple you just this so it's very simple you just iterate through the entire array for the iterate through the entire array for the first time pick up two and scan through first time pick up two and scan through the entire array and keep a check and the entire array and keep a check and count after you have scanned through the count after you have scanned through the entire array by taking array of I you entire array by taking array of I you check it the count is greater than n by check it the count is greater than n by 2 if it is then you return array of I 2 if it is then you return array of I and and forward like out of the for Loop you can forward like out of the for Loop you can return -1 just in case there is no return -1 just in case there is no majority element so this is how the majority element so this is how the Brute Force solution will look like what Brute Force solution will look like what will be the time complexity obviously we will be the time complexity obviously we are using couple of Loops so it is we go are using couple of Loops so it is we go of n square and when you give the of n square and when you give the solution to the interviewer the solution to the interviewer the interviewer will not be happy and will interviewer will not be happy and will ask you to optimize it this is when ask you to optimize it this is when you'll be giving the better solution so you'll be giving the better solution so what will be the better solution what will be the better solution The Brute is taking n Square so we know The Brute is taking n Square so we know one thing for sure the better solution one thing for sure the better solution will be somewhere of the order n log n will be somewhere of the order n log n or B go of n or 2N but it is definitely or B go of n or 2N but it is definitely going to be better than n n Square so if going to be better than n n Square so if I have to think what are we actually I have to think what are we actually doing we are counting we are counting doing we are counting we are counting and we're looking for which element and we're looking for which element appears more than n by two times so appears more than n by two times so yes yes we can use hashing it's very yes yes we can use hashing it's very simple if there is a count we have to simple if there is a count we have to keep a track of how many times a Dockers keep a track of how many times a Dockers the only technique that comes up to my the only technique that comes up to my mind is hashing that is what I will be mind is hashing that is what I will be doing so what I'll do is I will declare doing so what I'll do is I will declare a hashma with the element and the count a hashma with the element and the count where the element is my key and the where the element is my key and the count is my value so this will be the count is my value so this will be the representation in the map for a clear n representation in the map for a clear n value now what I'll do is I'll be like value now what I'll do is I'll be like let's scan through the array it is two let's scan through the array it is two so I'll put that 2 and I'll probably so I'll put that 2 and I'll probably tell him you okay once then I'll move tell him you okay once then I'll move and then I'll say you okay twice then and then I'll say you okay twice then I'll move and there's a three I'll say a I'll move and there's a three I'll say a doctors once then I'll move and there's doctors once then I'll move and there's a three it occurs twice then I'll move a three it occurs twice then I'll move one occurs once then I'll move two one occurs once then I'll move two occurs twice then I'll move two occurs occurs twice then I'll move two occurs four times so once you have completed four times so once you have completed the entire iteration now it's time to the entire iteration now it's time to iterate in the map yes it's time to iterate in the map yes it's time to iterate in the map so if I iterate in iterate in the map so if I iterate in the map you will see that the map you will see that this particular Guy 2 occurs four times this particular Guy 2 occurs four times which is greater than n by 2 which is which is greater than n by 2 which is three so two is your answer so just I three so two is your answer so just I trade in the map and see which element trade in the map and see which element is occurring more than n by two times so is occurring more than n by two times so let's quickly quote the better solution let's quickly quote the better solution of the problem link will be in the of the problem link will be in the description so we need a map to keep the description so we need a map to keep the count cell declare a map okay what is count cell declare a map okay what is the next thing we have to iterate so the next thing we have to iterate so let's quickly iterate and now once am I let's quickly iterate and now once am I trading I'll say ma what's the element trading I'll say ma what's the element vfi do a plus plus so with this vfi do a plus plus so with this iteration I will be marking it in the iteration I will be marking it in the map now what is the next job I trading map now what is the next job I trading the map and see which is more than n by the map and see which is more than n by two times so this is how you iterate two times so this is how you iterate in the map in C plus plus the Java port in the map in C plus plus the Java port and the python code is in the and the python code is in the description and now you say ID dot description and now you say ID dot second because that is the value second because that is the value is greater than are you greater than V is greater than are you greater than V Dot size Y2 if you are then near the Dot size Y2 if you are then near the majority element and you know the key is majority element and you know the key is very simple it's at the first place so very simple it's at the first place so the key will be the first place if after the key will be the first place if after this there was no one you can simply say this there was no one you can simply say return -1 return -1 and now we will quickly go and run this and now we will quickly go and run this off and see if it is running fine okay off and see if it is running fine okay looks like it is not why is it not tap looks like it is not why is it not tap was not declared let's quickly go and was not declared let's quickly go and declare hashing clue everything is declare hashing clue everything is running absolutely fine now it's over running absolutely fine now it's over the time complexity can I say the first the time complexity can I say the first Loop is running for bego of N and Loop is running for bego of N and there's a ordered map used which is there's a ordered map used which is which is going to take logarithmic of n which is going to take logarithmic of n if you use something like unordered map if you use something like unordered map then this logarithmic of n will go off then this logarithmic of n will go off only in case of average and best case in only in case of average and best case in case of worst case case of worst case another map ends up taking the ego of another map ends up taking the ego of end time within itself so that is an N end time within itself so that is an N login and what is how many elements are login and what is how many elements are there in the map imagine you're given an there in the map imagine you're given an array something like this then each of array something like this then each of these elements will be in the map so these elements will be in the map so thereby the worst case the map might end thereby the worst case the map might end up taking n so what is the total time up taking n so what is the total time complexity can I say it as we go of n complexity can I say it as we go of n log n again depending on which map log n again depending on which map you're using and a big go of N2 Traverse you're using and a big go of N2 Traverse in the in the map ever the space complexity we go of n map ever the space complexity we go of n because you are storing all the elements because you are storing all the elements in a map data structure so this will in a map data structure so this will only happen if the array contains all only happen if the array contains all unique elements remember this unique elements remember this so the moment you give this hashing so the moment you give this hashing solution to the interview he'll be like solution to the interview he'll be like hey wait you are using an additional hey wait you are using an additional space complexity can you please optimize space complexity can you please optimize this that's when you'll be talking about this that's when you'll be talking about the most optimal algorithm and that will the most optimal algorithm and that will be using something as the Moose voting be using something as the Moose voting algorithm algorithm now sitting in an interview you cannot now sitting in an interview you cannot invent this algorithm so you have to invent this algorithm so you have to know this algorithm beforehand so you know this algorithm beforehand so you might be thinking but does that mean we might be thinking but does that mean we have to mark it up no the interviewer have to mark it up no the interviewer will be grilling you on thought process will be grilling you on thought process and intuition if you mug up the and intuition if you mug up the algorithm and you just present it line algorithm and you just present it line by line you'll understand that you have by line you'll understand that you have marked up the algorithm so please make marked up the algorithm so please make sure you understand the thought process sure you understand the thought process intuition and the algorithm in depth so intuition and the algorithm in depth so please make sure you watch the video please make sure you watch the video till the end because you're going to till the end because you're going to take away a lot of things when the video take away a lot of things when the video ends ends so how will I be explaining this so how will I be explaining this particular algorithm what I'll do is particular algorithm what I'll do is I'll do a Dryden of the algorithm and I'll do a Dryden of the algorithm and during The Dryden I'll be sharing the during The Dryden I'll be sharing the thought process and the intuition behind thought process and the intuition behind every step that this algorithm does so every step that this algorithm does so that it sticks to your mind okay that it sticks to your mind okay so what is the algorithm all about it's so what is the algorithm all about it's very simple it's about two variables very simple it's about two variables element element and Dot initially count is zero and you and Dot initially count is zero and you can say initially the element is not can say initially the element is not initialized and we start iterating so initialized and we start iterating so whenever we are iterating and we are the whenever we are iterating and we are the first element or whatever if the count first element or whatever if the count is zero that means we haven't taken any is zero that means we haven't taken any array please hear this out properly we array please hear this out properly we still haven't taken any array so you still haven't taken any array so you will be like okay I will take seven and will be like okay I will take seven and I'll increase the count to 1. so what I I'll increase the count to 1. so what I did was I said I will consider this 7 to did was I said I will consider this 7 to be my answer I'm just taking a be my answer I'm just taking a hypothetical assumption that 7 is my hypothetical assumption that 7 is my answer and the Countess one and now answer and the Countess one and now let's start moving we again move to let's start moving we again move to seven like seven now this occurs twice seven like seven now this occurs twice five five no it is not seven no it is not seven so you reduce the count remember this so you reduce the count remember this count is not storing how many times count is not storing how many times seven appears it doesn't seven appears it doesn't have some other significance which I'll have some other significance which I'll say next again seven say next again seven increase next again five degrees next increase next again five degrees next one degrees one degrees so whenever you find 7 you increase so whenever you find 7 you increase because 7 was your element whenever you because 7 was your element whenever you find anything apart from Seven you find anything apart from Seven you decrease now you are reaching zero until decrease now you are reaching zero until how much till this portion let's how much till this portion let's understand what so if you take seven understand what so if you take seven seven five seven five one this is an seven five seven five one this is an array rather this is an array and the array rather this is an array and the count over here is zero what does the count over here is zero what does the count signify so you took the element count signify so you took the element seven how many times does it appear seven how many times does it appear three times three times how many times the author elements how many times the author elements appears where other includes five and appears where other includes five and one the other element appears three one the other element appears three times this is the reason when there was times this is the reason when there was a seven you did a plus plus so there a seven you did a plus plus so there were three plus plus done and when there were three plus plus done and when there was five five one there was a minus was five five one there was a minus minus minus 10. so 3 plus 3 minus ended minus minus 10. so 3 plus 3 minus ended up giving you a count of zero can I say up giving you a count of zero can I say something for sure if I just consider something for sure if I just consider this array just consider this array 7 is this array just consider this array 7 is definitely not my major retirement why definitely not my major retirement why if seven was my majority element if seven was my majority element how can you cancel because for if an how can you cancel because for if an element appears more than n by two times element appears more than n by two times there is only one limit which appears there is only one limit which appears more than n by two times and you cannot more than n by two times and you cannot cancel it all if there are six elements cancel it all if there are six elements and seven appears four times can you and seven appears four times can you cancel four to cancel 4 you need four cancel four to cancel 4 you need four more so it's not possible since 7 more so it's not possible since 7 appeared three times in a six length appeared three times in a six length array which is not greater than n by 2 array which is not greater than n by 2 it is equal to equal to n by 2 so it got it is equal to equal to n by 2 so it got canceled so something that I can canceled so something that I can assurely say is till here 7 is not my assurely say is till here 7 is not my majority element till here it's not so majority element till here it's not so this cannot be considered as an answer this cannot be considered as an answer but what I will do is I'll move ahead but what I will do is I'll move ahead and I'll move to 5 okay the moment I and I'll move to 5 okay the moment I move to 5 I find count is zero so what move to 5 I find count is zero so what I'll do is I will just quickly say okay I'll do is I will just quickly say okay listen count is 0 so can you please take listen count is 0 so can you please take this as my new majority element and this as my new majority element and probably I'll start checking from here probably I'll start checking from here and my count will be one perfect so I and my count will be one perfect so I will take five I'll make the count one will take five I'll make the count one let's move seven it's not equivalent so let's move seven it's not equivalent so I'll just make it zero I just make it I'll just make it zero I just make it back zero so this time the array back zero so this time the array finishes here and the count becomes zero finishes here and the count becomes zero again eminent if I just take this again eminent if I just take this particular array can 5 be the majority particular array can 5 be the majority no that's why next we'll move ahead no that's why next we'll move ahead the moment we move ahead what will the moment we move ahead what will happen happen since count is 0 it will again since count is 0 it will again initialize count to 1 and element to be initialize count to 1 and element to be five and we will start the array again five and we will start the array again from here and this time again let's move from here and this time again let's move it's five increment it is seven it's five increment it is seven decrement it is seven decrement so can I decrement it is seven decrement so can I see see in this particular array what happened in this particular array what happened five five seven seven what I can say is five five seven seven what I can say is hey 5 was occurring twice seven hours hey 5 was occurring twice seven hours occurring occurring twice so it brought cancer thereby count twice so it brought cancer thereby count was Zero thereby 5 also cannot be my was Zero thereby 5 also cannot be my answer so till now whoever I have answer so till now whoever I have considered as a majority got canceled by considered as a majority got canceled by similar elements so till now no one has similar elements so till now no one has dominated we are still looking for dominated we are still looking for someone who is dominating got it someone who is dominating got it everyone has still no cancer let's go everyone has still no cancer let's go ahead what is the count value Crown's ahead what is the count value Crown's value is zero now so let's move it value is zero now so let's move it we are at account zero so again we start we are at account zero so again we start the count will again become one and this the count will again become one and this element still stays as five this time element still stays as five this time we'll move ahead count becomes 2 7 will we'll move ahead count becomes 2 7 will move out count becomes three this term move out count becomes three this term will move ahead count becomes four and will move ahead count becomes four and we can say we have ended the iteration we can say we have ended the iteration we have ended the iteration so since we we have ended the iteration so since we have ended the iteration there is an have ended the iteration there is an element five this count has no element five this count has no significance but we have an element five significance but we have an element five this element 5 will be your maturity this element 5 will be your maturity element if there exists a majority element if there exists a majority element why because everyone else got element why because everyone else got canceled off within itself so if there canceled off within itself so if there is someone still remaining who did not is someone still remaining who did not got canceled then that is my answer but got canceled then that is my answer but am I sure that element 5 is the majority am I sure that element 5 is the majority element what I said if there exists a element what I said if there exists a majority limit it will be five and no majority limit it will be five and no one else if if there is a majority one else if if there is a majority element it will be five and no one else element it will be five and no one else if there doesn't then okay fine for if there doesn't then okay fine for example if the last portion was example if the last portion was something like one one one something like one one one in that case you'd have bought one and in that case you'd have bought one and the count would have been four but is the count would have been four but is one the majority element if you see one one the majority element if you see one just appears four times maybe five just appears four times maybe five that's it one app is five times and when that's it one app is five times and when you look at the length of the array it you look at the length of the array it is six two four and four which is eight is six two four and four which is eight plus four twelve it's a 16 length array plus four twelve it's a 16 length array someone has to appear more than eight someone has to appear more than eight times to be majority and since it is times to be majority and since it is five let's see 5 is so let's see how five let's see 5 is so let's see how many times five is once twice twice four many times five is once twice twice four five six seven eight nine five appears five six seven eight nine five appears nine times out of which four times when nine times out of which four times when not canceled four times when not not canceled four times when not canceled but the other times it was canceled but the other times it was canceled so the other five times zeros canceled so the other five times zeros canceled got it so I can say five is my canceled got it so I can say five is my major element it's a very simple process major element it's a very simple process the first process is to apply moose the first process is to apply moose voting algo voting algo okay about the second process verify if okay about the second process verify if the element that you got the element the element that you got the element that you got is the majority or not how that you got is the majority or not how do you do it whatever the element is in do you do it whatever the element is in this case the element was 5 just iterate this case the element was 5 just iterate through the array again and see how many through the array again and see how many times 5 appears this time it will come times 5 appears this time it will come out to be 9 which is greater than the out to be 9 which is greater than the length 16 by 2. so that's why the 5 is length 16 by 2. so that's why the 5 is if it doesn't then it is not got it so I if it doesn't then it is not got it so I hope you've understood the intuition hope you've understood the intuition it's very simple if someone appears more it's very simple if someone appears more than n by two times it will not get than n by two times it will not get canceled quite simple right that's the canceled quite simple right that's the intuition so coming back to the code intuition so coming back to the code editor again the problem link will be in editor again the problem link will be in the description so what do we need we the description so what do we need we need account zero and we can keep an need account zero and we can keep an element normally now let's quickly start element normally now let's quickly start off with zero and probably V Dot size off with zero and probably V Dot size yes and how can I say first thing that I yes and how can I say first thing that I will check is what if the count is 0. if will check is what if the count is 0. if the count is 0 I know for sure this is the count is 0 I know for sure this is where where I'm starting a check for a new section I'm starting a check for a new section so ground will be one and the element so ground will be one and the element will be V of I right but what if the will be V of I right but what if the count is not zero in that case I will count is not zero in that case I will check if V of I is equal to equal to the check if V of I is equal to equal to the element that I was thinking it's it's element that I was thinking it's it's the majority if it is please increase if the majority if it is please increase if it is not okay let's reduce it is not okay let's reduce simple three lines if the count is zero simple three lines if the count is zero we just assign and we move I plus plus we just assign and we move I plus plus if it is equal equivalent we just if it is equal equivalent we just increase count and we move if it is not increase count and we move if it is not then we decrease and then we move so then we decrease and then we move so what will happen is when you're what will happen is when you're decreasing if the curve becomes 0 when decreasing if the curve becomes 0 when you increase and when you come back the you increase and when you come back the count will be checked with 0 and it will count will be checked with 0 and it will be replaced with the newer limit and it be replaced with the newer limit and it will start a new section quite simple will start a new section quite simple and once you've got the element just and once you've got the element just iterate over here iterate over here and V Dot size all right plus plus and and V Dot size all right plus plus and you say Hey listen if V of I is you say Hey listen if V of I is equivalent to element probably you can equivalent to element probably you can keep keep something like something like counter one equal to zero and you can counter one equal to zero and you can say counter one plus plus if at the end say counter one plus plus if at the end of the day counter one is greater than V of the day counter one is greater than V Dot size by 2 again you can store B dot Dot size by 2 again you can store B dot size in some variable this particular size in some variable this particular element is the answer or else you can element is the answer or else you can say the answer is minus one or whatever say the answer is minus one or whatever they are asking you to return so what they are asking you to return so what I'll do is now I'll quickly go and run I'll do is now I'll quickly go and run this off and see if it is running fine this off and see if it is running fine no it does or it'll be counter one plus no it does or it'll be counter one plus plus counter one done and let's quickly plus counter one done and let's quickly submit this off I hope it does run now submit this off I hope it does run now remember one thing whatever is the value remember one thing whatever is the value of counter at the end it doesn't of counter at the end it doesn't represents anything so we have to talk represents anything so we have to talk about the time complexity how much a about the time complexity how much a single Loop single Loop and three Fields so it's a single Loop and three Fields so it's a single Loop so whenever it's a single Loop you know so whenever it's a single Loop you know the time complexity is very simple it's the time complexity is very simple it's we go off n for the burst iteration of we go off n for the burst iteration of the most voting algo and if they are the most voting algo and if they are stating that the the array might have or stating that the the array might have or might not have a majority limit then you might not have a majority limit then you go and verify this step will not be done go and verify this step will not be done if the problem states that their own if the problem states that their own ways exist a majority element then this ways exist a majority element then this step will never be done okay you only do step will never be done okay you only do the step if the prop if the array might the step if the prop if the array might not have a majority element got it so not have a majority element got it so this will be the time complexity and we this will be the time complexity and we are not using any extra space so this are not using any extra space so this will be the space complexity of the most will be the space complexity of the most optimal solution coming back to the optimal solution coming back to the sheet I can say that this particular sheet I can say that this particular problem is done and if you understood problem is done and if you understood everything please please do with that everything please please do with that like button is just one like it won't like button is just one like it won't cost you anything please do consider cost you anything please do consider hitting that like button and look at hitting that like button and look at your tradition do comment understood so your tradition do comment understood so that I understand that you understanding that I understand that you understanding everything and if you're new to our everything and if you're new to our Channel please please do consider Channel please please do consider subscribing to us because it's like 1 23 subscribing to us because it's like 1 23 am in the morning and after my office am in the morning and after my office hours I'm recording this video so if you hours I'm recording this video so if you if you consider subscribing to me that if you consider subscribing to me that will motivate me to make such more will motivate me to make such more videos is broken don't ever forget you're | 2024-03-21 14:02:04 | 169 | Majority Element I | Brute-Better-Optimal | Moore's Voting Algorithm | Intuition 🔥|Brute to Optimal |
|
We_xKjlNUOE | hey hey everybody this is larry this is me going with q4 of the me going with q4 of the uh weekly contest 224 uh cat and mouse uh weekly contest 224 uh cat and mouse 2. so i actually 2. so i actually thought this one was a little bit easier thought this one was a little bit easier than q3 than q3 for me but uh but that is not the for me but uh but that is not the the general uh consensus so i don't know the general uh consensus so i don't know about that about that uh only 49 people solved it this problem uh only 49 people solved it this problem um um but for me and i there might be other but for me and i there might be other ways to do it uh because there are this ways to do it uh because there are this is just is just to be honest um scanning over a few to be honest um scanning over a few solutions which we can also do in a solutions which we can also do in a little bit little bit um you know it is just straight up game um you know it is just straight up game theory and that's my solution theory and that's my solution uh hit the like button hit the subscribe uh hit the like button hit the subscribe button join me on discord let me know button join me on discord let me know what you think about this problem this what you think about this problem this very hard problem very hard problem so um so for this one there are two so um so for this one there are two observations that i made observations that i made um one is that um one is that it doesn't make sense for the mouse to it doesn't make sense for the mouse to stand still so stand still so that way it eliminates some of the that way it eliminates some of the psychos i don't know psychos i don't know if it's that helpful to be honest but if it's that helpful to be honest but that was one of my initial dots that was one of my initial dots and then the second one was that uh the and then the second one was that uh the mouse cannot get to within a thousand mouse cannot get to within a thousand turns the cat wins but it turns out that turns the cat wins but it turns out that it's actually um it's actually um not even as bad as that it turns out not even as bad as that it turns out that there is a case do i have it here i didn't i don't i lost the case but so it turns out that the worst case is actually not that not a thousand so you can cash it in a much more straightforward way so let's say you have a mouse next to the cat and you do it one by one the actual actually the worst case is something like this oops um nope basically sit uh sit sagging uh all the way oops uh that's pretty much the idea and basically what i did during the contest and you could watch me solve it live afterwards um did i tell you to hit the like button yet i don't remember uh if you didn't hit the like button hit the subscribe button and join me on discord and everything i don't know today's a long day basically i don't even know if this is length eight so maybe i'm off by one but that's still the same idea which is that um so what i did was that i i got this test case and then i just counted them out um because if we uh you know we base the idea off that the mouse will always move then the longest way that it could get to the end is about like 70 moves which is about like the distance is about like 35 or something like that and then 35 times two for the cat and the mouse so actually in my my code i have a magic consonant that's 80. and after that it actually is just straight up uh game theory um and my code is actually i want to say it's very queen version of the game theory um and we will go over it together but this is basically the idea behind it and i would also say that if you don't um if you don't know game theory this is actually a little bit tricky to go over i would definitely [Music] uh i would definitely recommend you know understanding game fear and how it works um i'm gonna go over it for sure a little bit but probably not as in-depth as you know something that you know like you need the background a little bit i don't want to make it sound like this is easy anyone can do it i mean anyone can do it but you just have to learn to write things first um and i you know and i don't want to make this like a huge lecture because game theory can get a little bit hairy so okay so then so but the intuitive sense is that okay i just i reduce this to dynamic programming kind of i have a cache um and i keep track of and my states are kind of weird but we'll go over together so my end result is okay can the mouse win if the mouse is you know in in the mouse location given that the cat is in this location and the turn number is zero um and i have like some pre-processing stuff that puts you know the mouse and the cats and the robots in the right place and then now here's the mouse win function this should be very straightforward um in terms of understanding i hope um like i said the key thing is just cutting it off that turn is greater than 80. um and then here this is just already relatively straightforward thing of okay if i'm the mouse i'm going to try this move right if i move to a place you know i'm trying to figure out with my current location my current state of the world is a winning state it is a winning state if i i'm at on top of the food which is the base case um it is a losing state if the turn is you know too far in the future which i said is 80. um you know if if we if we are able to get to a another similar state in which the cat cannot win then this is a winning state that's basically the idea um because if i'm able to go to a move where the cat cannot win then i'm going to take that move because the cat cannot win and then you kind of do that recursively um we'll talk about the cat win function i actually separate them out um not everyone does it this way but i feel like this is a this makes it way more readable but uh but basically okay given the mouse wind function i literally look at every direction and this is just you know up down left right um hmm that's interesting actually this is unnecessary so maybe i made it even slower that's uh because i forgot that i actually go into the other direction anyway um but i was thinking that maybe i i jump into the wrong direction so actually this is a little bit even slower so i could actually reduce this to be faster by doing this uh though so that's actually whoopsie daisies uh because directions should already take care of the directions so i don't have to do negative jumps in the other direction but i think while in the contest and it's still passed so it's still fast enough um but in any way so now looking at this new code um you know this is just basically okay i have a direction and i'm gonna move mouse jump distance away um if if the new space is on the food space then i return true because that means that i'm one move away from true uh if it goes out of bounds uh i break out the loop because that means that you know i jumped out of bounds and i don't need to go you know loop anymore um if this is a war then we also break because we cannot jump over a wall and this is why we have to make sure that we jump in the right order um and then if those things are not true then we will try to jump here if we jump here and the cat cannot win then that means that we're going to jump there because the cat cannot win um that's basically the idea and then we'll go look at the cat one as well i i did a little copy and paste so the s thing doesn't make sense here too for some reason i thought i had i could do a negative jump but actually let me change that so that is a little bit uh but yeah but now this is the cat jump uh but yeah but now this is the cat jump code code uh so we go over each state can the cab uh so we go over each state can the cab win is this a win is this a state in which the cat can win it it the state in which the cat can win it it the cat can win if we could get to the foot cat can win if we could get to the foot first which is true first which is true uh if it is in the same space as the uh if it is in the same space as the mouse then the cat wins mouse then the cat wins um otherwise and we you could do um otherwise and we you could do something about turn but i i something about turn but i i i leave it to the mouse so it's fine i i leave it to the mouse so it's fine i don't think it matters that much don't think it matters that much uh but yeah so the key thing the other uh but yeah so the key thing the other thing is that note that um we have to thing is that note that um we have to move move so i actually made this observation so i actually made this observation before i made the turn i think now that before i made the turn i think now that with the turn with the turn um you know it's not that necessary um you know it's not that necessary actually but actually but but i just wanted to make sure that uh but i just wanted to make sure that uh you know you know um you know it could stay in the same um you know it could stay in the same space um because we want to space um because we want to do that where on the where on the mouse do that where on the where on the mouse um um it always for me it just made sense that it always for me it just made sense that the mouse always had to move and the cat the mouse always had to move and the cat could stay could stay in the same space if it doesn't have to in the same space if it doesn't have to move meaning that it could just block move meaning that it could just block uh or something like that that's why i uh or something like that that's why i checked for it here but otherwise it's checked for it here but otherwise it's the same thing which is that the same thing which is that the cat this is a winning state for the the cat this is a winning state for the cat cat if it makes a move and that move if it makes a move and that move means that the mouse does not win means that the mouse does not win um so this is kind of a recursive uh um so this is kind of a recursive uh logic and f uh logic and f uh understanding there and that's pretty understanding there and that's pretty much it um again much it um again you know uh we do the cat jump distance you know uh we do the cat jump distance thing uh we check that with this next thing uh we check that with this next you know if it's on the food then the you know if it's on the food then the cab wins if the new space is where the cab wins if the new space is where the mouse is then you also win mouse is then you also win you know you cannot jump over um you you know you cannot jump over um you cannot jump outside cannot jump outside and you cannot jump over walls otherwise and you cannot jump over walls otherwise you check whether you know if the mouse you check whether you know if the mouse cannot win cannot win once you move there then it is true also once you move there then it is true also the mouse cannot win if you just do the mouse cannot win if you just do nothing then it's also true nothing then it's also true otherwise this is a four state because otherwise this is a four state because that means that that means that just every move you make uh the mouse just every move you make uh the mouse will win will win so that's basically the idea and that's so that's basically the idea and that's pretty much it with the game theory pretty much it with the game theory um and and that basically is the um and and that basically is the recursive function recursive function uh the dynamic programming function um uh the dynamic programming function um [Music] [Music] but yeah um but yeah um let's see yeah so the complexity um i'm let's see yeah so the complexity um i'm gonna only do the complexity for the gonna only do the complexity for the mouse it should be the same for the mouse it should be the same for the for the cat um so what are the number of for the cat um so what are the number of possible inputs well this is eight this possible inputs well this is eight this is eight this is eight this is eight is eight this is eight this is eight right so right so rose times column is equal to eight rose times column is equal to eight times eight which is 64. times eight which is 64. um and then we have you know mouse mouse um and then we have you know mouse mouse bow bow times column is equal to 64. cat times column is equal to 64. cat rose times column is 064. so rose times column is 064. so so yeah and then turn as we kind of have so yeah and then turn as we kind of have a bound here it could be only be 80 a bound here it could be only be 80 right and actually it's half of that but right and actually it's half of that but um but yeah so then now the complexity um but yeah so then now the complexity just just uh the space complexity anyway it's just uh the space complexity anyway it's just this which is 64 this which is 64 times 64 times 80 which is about 300 000 times 64 times 80 which is about 300 000 uh i mean you know um yeah uh i mean you know um yeah right um so that's going to be fast enough so that's our complexity um [Music] in terms of space for sure and and for each one of these we have you know directions so yeah so we have four directions times uh the number of mouse jumps which is i think also i mean at once it could be eight so it could be also 32 uh so then the worst case time complexity is just you know all this together which is this times 32 which is equal to roughly me plugging into a calculator uh about 10 ml right so yeah and if you want to think about complexity it's just o times r times c uh times you know square because of the both sides uh times uh max turn which is in this case 80ish and and this is the space complexity and then the time complexity is this times uh four which are of course we can rule out and times um you know r plus c because um because that's how far the mouse jump can be in the worst case and again the four drops out so then this is the final complexity which is yeah so this is the time complexion and this is the space complexity which i think the the test case is a little bit generous otherwise i don't think this should be passing uh especially given the number of test cases that they have um because uh so yeah doing this um i definitely had doubts about this uh problem as i was solving it because uh i wasn't sure that this was gonna be fast enough because um it depends on the number of test cases that they have because for each individual test case i'm actually confident that they will pass but in the worst case it might not because uh or in the worst one case it will pass but in lead code is the total amount of time you take for all the test cases so i was worried about the number of test cases as a result um but otherwise um yeah and i got a wrong answer because i i thought the worst case was actually a spiral but it turns out that this was a little bit uh longer so i should have used 80 instead because i it was a smaller constant because i did a spiral i counted the spiral and it was like 25 steps or something like that but apparently it wasn't far enough um so yeah um that's all i have for this problem uh it's a very tricky game theory problem um to get the complexity right so um so yeah let me know what you think uh every second counts for this problem so yeah let watch me stop it during the next next ah dumb mistakes ah dumb mistakes let's see okay well only one person got let's see okay well only one person got this so that means that this so that means that my ranking reply based on this uh q3 my ranking reply based on this uh q3 which i didn't do really fast oh which i didn't do really fast oh late curse well done um well a lot of late curse well done um well a lot of people did this very quickly i don't people did this very quickly i don't know know smart people and i have two penalties smart people and i have two penalties on top that's not good okay let's focus on top that's not good okay let's focus uh but this is gonna be hard for him if uh but this is gonna be hard for him if it takes it takes two good people 20 minutes and well alex two good people 20 minutes and well alex well done okay focus that well done okay focus that what am i doing okay i mean cheesy answer is just mini max i mean cheesy answer is just mini max but i don't think that's right but i don't think that's right or like not enough the only 64 space those states those states trying to do some kind of crazy mimics that shouldn't be that hard that shouldn't be that hard maybe let's see okay so the 64 times 64 times two so 800 states what is that what are the states oh my god this is so annoying to write okay so the winning state is okay so the winning state is we find f after they move okay just go to i'm surprised not more people gotten this so i think maybe this could be i don't get it this is just mini max so hmm that's not a good sign you i think the assumption maybe we need to request something i don't think this is going to be we'll see if it's fast enough uh uh the most always wants to move i think so and now we so and now we can go you okay you okay so make sure we turn something you ready i have a typo i have a typo oh where does this x even come from wow how come it's not complaining i even use x somewhere so there's a cycle of sorts so there's a cycle of sorts [Music] [Music] alright get rid of this cycle alright get rid of this cycle from it going back and forth we've got hmm i don't know why i did it with dpi financial i've done it with should have done it with a graph search perhaps a thousand though that's gonna perhaps a thousand though that's gonna make it big i don't think it's going to be fast i don't think it's going to be fast enough to that's the problem is true force true true force was true true force force why is this i gotta return true for this uh what's the input cat jump is two jump here one move here and then mouse just jumps i don't get way back oh they cannot jump over the wall i oh they cannot jump over the wall i think i miss my tap okay think i miss my tap okay that's not hard i think that's going to be too many states to 4 million it's going to time i can even try that if it somehow doesn't time limit i would sum it but i don't think there's no way this isn't time limit so this is the game theory way of doing it because otherwise they just got stuck on can i cheat i reduce this by like it's fast enough okay can you do some kind of funky proof can you do some kind of funky proof maybe like just the crazy one is the one that loops so what's that would that look like well i have half an hour decided that i don't get it it's fine maybe so then uh people like messaging me during this time i don't know how to turn it off on a mac i'm not gonna lie please stop messaging me okay oh my god even with it i don't know how to turn this thing off i don't know how to turn this thing off can can you turn off can can you turn off messenger okay so what's that two that's six seven eight nine ten dollars 636. this should be good enough right it's fast enough i don't know probably it's fast enough i don't know probably not but not but worth a shot hmm this is force no should be true oh wait no because of the cat chases after the first jump that's actually a good uh let's give it a try who knows that worse let's give it a try who knows that worse over time limit because i don't know how this helped otherwise oh wrong answer um i think this is similar to mine nice of them to give me that this test nice of them to give me that this test cases though the answer is one what does that what does one mean one means that so maybe this is the worst case so this so maybe this is the worst case so this is one two three four is one two three four six seven six seven 15 15 plus 9 24 plus another 9 is 33 oh it's 33 each so that's 70 maybe now i'm like what was the answer expected true okay what was the answer expected true okay well well let's give it another go maybe too slow still but okay well i don't know if that's cheating but uh thanks for watching everybody uh hit the like button hit the subscribe button join me on discord and ask me questions about this problem or other problems uh have a good year and all that stuff and i will see you | 2024-03-20 17:42:01 | 1,728 | 1728. Cat and Mouse II (Leetcode Hard) |
|
XblA2DKBOSI | Work in this area Ajay will have to Ajay will have to [Music] That a [ Music] Hello Hello one and welcome to new video English video by going to discuss problem number 90 from from the problem problem 000 agree here and From the From the From the name of the Laker to one point that and from the railway station duty reduce 2002 number of clans given till minus one ok example2 which is ours which is which is ours which is ours meaning and here here put here put our name For top one, if we check For top one, if we check For top one, if we check then what will happen, then our today's question is then what will happen, then our today's question is if we check if we check which row for answer one, what will happen in row one, so which row for answer one, what will happen in row one, so here we will here we will put it in place of put it in place of put it in place of submit and submit and 20 so 20 so see here what we will do 1000 and soon here will be gone name 1000 and soon here will be gone name shop names of three which instead of numbers of shop names of three which instead of numbers of five don't five don't threaten If If we do the fragrance, then when we see the answer ad here for Kapoor, then what is this ad of ours and set our normal number 420 1234, so here we subscribe one two three and lastly 504 and if we see 504 and if we see 40 504 506 Like 504 506 Like we give it that this is given to us as an example Hello, we are that this is given to us as an example Hello, we are given to this 505 1234 Now we have to make our answer so first of all we have to answer here for answer answer off if we if ours is then ours ours then ours ours these people These set the set the name of 80 work as Saturday or will have to be removed name of 80 work as Saturday or will have to be removed from the name, from the name, what are the five elements for this option, so what will June June 2012, so Ho Ho Ho ka see this place for Toubro for 2014 ka see this place for Toubro for 2014 if we are if we are 1234 1234 then our this is ours this is ours so for this we will village approach village approach loot first of all we will make this who false a This is our size of salt This is our size of salt This is our size of salt pudding, its size and hello, it's fine, like pudding, its size and hello, it's fine, like this is ours, then where do we get this is ours, then where do we get our our time from, we have been time from, we have been fold it at fold it at number number eight eight and like if this follow is finished. and like if this follow is finished. and like if this follow is finished. its time from time to its time from time to time, which will be clear, okay if we talk about its space complexity, then Space Congress is taking such an express which has been a If he is If he is If he is taking our speed on the same side, then this is the then this is the problem. this is our code, first of all, this is our code, first of all, I have taken it as per okay, I will enter it, first of all, I have taken the salt, subscribe this, subscribe this, this is another form of his name, Jhalar Slide this is another form of his name, Jhalar Slide Distribution, Distribution, what should we do? what should we do? what should we do? make a loop that come as soon as possible [music] appoint like we will finish the solution together and finish it like we will finish it appoint and appoint and subscribe your answer and what is the result subscribe your answer and what is the result and this is our success and this is our success and this is our success Andhe Se and those who Andhe Se and those who do Meghnad 3000 work do Meghnad 3000 work subscribe time complexity of notification for this problem and we do this paste, we do this, instead of making a new one, instead of making a new one, update the same rally, update the same rally, then what should we do? then what should we do? then what should we do? we have to make these changes, first of all we will take out our N which is the size of the people who subscribe our channel, after that we have to change the change here that when we something like that here, then something like that here, then on this on this on this know which value is the first here, that is, share and with that, if we share and with that, if we can come out with the final, then you can subscribe to our channel, so we are here that we will give so we are here that we will give value in every position. value in every position. value in every position. then we can do something like this, name small, we will multiply, small, we will multiply, number at i, we will multiply and number at i, we will multiply and what we will do what we will do in this, in this, village amazon in this and Okay, we will take this and Okay, we will take this and Okay, we will take this and as we get this, we will cut into it as we get this, we will cut into it number 2012 three 500 800 800 to to 1000 times unity is 0 which is our first element, hello what will it go and ours will go something like this if you for some After calculating, what will we do? We should have got We should have got We should have got that i means nine number set i, we should have got the answer in one of the times index, we should have got, so this is like we will do, so we can type 06 here, so For 2012, how much is this, how much do we want here, if from here we want what is the value that we don't want from here, we will divide the thirteenth, from the end, if we divide it like this, then we are getting two, so there If we want the value of If we want the value of If we want the value of what was already here, here we will have the what was already here, here we will have the valley. If we valley. If we take the percentage but the cent end, then we will get the value, take the percentage but the cent end, then we will get the value, meaning if we take the turn of thirteen of those, this is its original of those, this is its original divide divided Do some work, Do some work, Do some work, if you subscribe, he can do it in any flat. if you subscribe, he can do it in any flat. Our Ghaghra Subscribe 1234 Naveen Said 5185 K0 12345 2014, if we divide the education and get it, then we will get six * 4 plus, which is original velvet seat andhe, adding us to this, he will make it andhe, adding us to this, he will make it 20%. 20%. 20%. and that is our complete hoga five yeh to jab aap 5.5 par cent end kya hoga five yeh to jab aap 5.5 par cent end kya hoga 5th 6th thirty plus plus humko hoga 5th 6th thirty plus plus humko nikal naam set 20123 4000 traditional We will do 14% We will do 14% We will do 14% so we will quickly if we want this here so we will quickly if we want this here which one we will do then which one we will do then now what will we do for our Naan here we have into three plus plus tha here we have into three plus plus tha na religion set here and we will get its % throw Hey, we will get the % throw Hey, we will get the % throw Hey, we will get the fourth because the fourth because the map of 6042 is map of 6042 is 1618 1618 incomplete and if we want it, then we will incomplete and if we want it, then we will finally divide it from terrorism, which will finally divide it from terrorism, which will be our channel, this problem problem be our channel, this problem problem problem, we are here, we are an actress problem, we are here, we are an actress in the name, so here we are in the name, so here we are look for the solution for the time complexity of space and see Ghaghra Ghaghra Raj Kaam Hai Hua Tha Name of the set Name of the shop number Set I percent N A plus This should be the first institute Please Please Please share this formula inside and after that we like our complete is finished then doctor and i20 and plus and we hate table hate table and after that we will get this complete so let's and after that we will get this complete so let's see let's see let's remove our old solution on our fearless this remove our old solution on our fearless this remove our old solution on our fearless this we have to start a potato here, where from where to where, we have to start a potato here, where from where to where, Chadana is equal to zero six transaction size and we will increment it by Ajay, time, For For For which thing which thing we will remove it and into a which is our we will remove it and into a which is our norms of norms of name set, name set, we will have to take it, we will have to take it, we will have to take it, we will have to take it, okay and after that, like we have to add it here, From till the end and till the end and that and inside that what we have to do is keep that and inside that what we have to do is keep doing a sentiment and here doing a sentiment and here what we have to do is and our potatoes now after that we will do our and our potatoes now after that we will do our and our potatoes now after that we will do our return this number. Ok, we will return this particular chapter note solution of youth and we used very less space than 3000 people, we used very less space than 3000 people, then you must have understood the solution and if you have found the then you must have understood the solution and if you have found the solution. solution. solution. with your friends and if you want to practice regular problems then you can join our channel [music] | 2024-03-25 13:07:41 | 1,920 | 1920. Build Array from Permutation | Zero to FAANG Kunal | Assignment Solution | Leetcode | Shapnesh |
|
DCTPOYrghIc | hi my name is david today we're going to do number one seven nine zero do number one seven nine zero check if one string swap can make check if one string swap can make strings equal strings equal this is an easy level problem on the this is an easy level problem on the code and we're gonna solve it in code and we're gonna solve it in javascript javascript we're given a function that takes in two we're given a function that takes in two strings strings s1 and s2 and we want to return true or s1 and s2 and we want to return true or false false if we can make a string swap and they've if we can make a string swap and they've defined this swap defined this swap as if you can swap at most one string as if you can swap at most one string swap swap on exactly one of the strings otherwise on exactly one of the strings otherwise return false return false so for example we have this two strings so for example we have this two strings here here if we know that we can swap b and k just if we know that we can swap b and k just one swap one swap they're equal so we return true and here they're equal so we return true and here we we return false because it's impossible to return false because it's impossible to make them equal make them equal and here is also another edge case where and here is also another edge case where they're both already equal they're both already equal so no swaps so it says so no swaps so it says at most one string swap so it's zero at most one string swap so it's zero swaps so it's still swaps so it's still true so in order to solve this problem true so in order to solve this problem there's two things we need to check there's two things we need to check the first thing is that they have to the first thing is that they have to have the same have the same letters and the letters have to appear letters and the letters have to appear the same amount of times the same amount of times so they can be in a match because this so they can be in a match because this is is impossible because they don't have the impossible because they don't have the same same letters and the second thing we ought to letters and the second thing we ought to do is do is create account for how many swaps there create account for how many swaps there so we know that so we know that if there's only two positions different if there's only two positions different that's one swap that's one swap and if it if it makes more than that we and if it if it makes more than that we know we return false know we return false so the first thing we want to do is that so the first thing we want to do is that we want to create we want to create a char array and this is a variable and this is a general strategy where we keep we create an array of 26 indexes and every time we see a letter it increments to that index value and then index value and then we also want to create a swap we also want to create a swap variable and that's going to keep track variable and that's going to keep track of how many swaps we're doing of how many swaps we're doing next we want to fill this chart array next we want to fill this chart array up so we create we loop through s1 the value to the corresponding the value to the corresponding char array and i'll show this in code char array and i'll show this in code this this idea took me a while to grasp this this idea took me a while to grasp but but i'll show you including make more sense i'll show you including make more sense and then and then so we got the char array filled up so so we got the char array filled up so now we have to loop through s2 and inside of this we want to see if it's inside of it if it's not if it's not inside of if this letter in s2 is not inside of it we return false knowing that it's possible current the value current the value inside char array inside char array and then is not we return false current value isn't it the value in charge array the value in charge array because the amount of times of it occurs because the amount of times of it occurs matters as well matters as well and then also we can combine this to the and then also we can combine this to the other part is that we other part is that we check the swap so if check the swap so if condition if condition if current s current index value i'll just current s current index value i'll just put in put in kind of code s1 i does not equal to it this means we need does not equal to it this means we need a swap and then we have a last condition condition if swap is greater than 2. and now lastly if we make it through and now lastly if we make it through this we this we return true so the all these are return true so the all these are conditions to make it return the second conditions to make it return the second condition will condition will check if it will make it return false check if it will make it return false and if it doesn't we return true and if it doesn't we return true and i also i had and i also i had three different loops at first but i three different loops at first but i learned that we can just combine this learned that we can just combine this one with this one one with this one so you'll be going a little bit twice so you'll be going a little bit twice so to create it to do it in code let so to create it to do it in code let char array equals new char array equals new array that is 26 index long and we fill array that is 26 index long and we fill it it starting with zero and we create this starting with zero and we create this swap variable that swap and it starts swap variable that swap and it starts off at zero off at zero and now we loop through s1 for that i and now we loop through s1 for that i equals zero equals zero i is less than s1 dot length i is less than s1 dot length i plus plus and inside of it we fill out i plus plus and inside of it we fill out this this char array so that char array so that temp and this is what i'm going to add temp and this is what i'm going to add to the chart array we have to change it to the chart array we have to change it to chart code to chart code so the idea is that we get so the idea is that we get s1 so this gets the letter and we change it and then we have to minus because it's and then we have to minus because it's hardcoded as a lot of more than just hardcoded as a lot of more than just the letters and it's also only low case the letters and it's also only low case too so that too so that shortens it a lot we got shortens it a lot we got subtracted from the a and just kind of subtracted from the a and just kind of that general idea that general idea and we just copy this and then we want to fill this out up on the in the array so try array where we get that temp we just plus plus and i'll console log this so you have an idea so you can see it and make sure i get it right you see so bank every the b we increment you see so bank every the b we increment one here for the second one here for the second this represents b this is a and k this represents b this is a and k and so forth and now we want to loop and so forth and now we want to loop through through it again they're the same length so it it again they're the same length so it doesn't matter but we can just do s2 doesn't matter but we can just do s2 for easier read i equals zero for easier read i equals zero i is less than s2 dot length i is less than s2 dot length i plus plus and we do the same thing let i plus plus and we do the same thing let 10 10 where we do s2 if this is equal to zero it means that it's not in it so we can't do this problem so return else so it isn't it we want to decrement else so it isn't it we want to decrement it it as well to keep track of the count as well to keep track of the count inside of to make sure that count inside of to make sure that count matches and then matches and then we create the other condition the swap we create the other condition the swap condition if s1 index i is equal to s2 index i doesn't equal to it we and then lastly if swap is greater than and then lastly if swap is greater than two two we return false and it makes it through we return false and it makes it through all this so we just return true all this so we just return true and that's it great so do we're doing a loop through here two we're doing a loop through here two loops but they're the same ones they're loops but they're the same ones they're not nested not nested so it's oven and then the space so it's oven and then the space complexity so this this is sufficient because it's constant is a constant 26 variable this is constant so it's going so that is how you solve this problem so that is how you solve this problem thank you | 2024-03-22 14:44:11 | 1,790 | How to Solve "1790 Check if One String Swap Can Make Strings Equal" on LeetCode? - Javascript |
|
v5ZBYBOwi7g | Jhal Hello Everyone Welcome To My Channel Police Question Is Reverse Entry Question Is Reverse Entry To Computer Channel Please subscribe To Computer Channel Please subscribe this Channel Notification On This Channel this Channel Notification On This Channel Indian Tech Help You With Your Infidelity The Indian Tech Help You With Your Infidelity The Question Is Right The Function Question Is Right The Function Demonstration In Its Ring Is Given By Adding Demonstration In Its Ring Is Given By Adding Actors Actors That Both Tape Express For That Both Tape Express For That Both Tape Express For Must For This Modifying Input Tray Correction System Printable Characters Is A Flu Example Born Again With Fellow Indian Outfit Videos And Example Number To The Giver Is Not And Furious Dahan Of Women Is Not Let's Can solve this Can solve this Can solve this question up to date will see the code is question up to date will see the code is high tech na are obtained that and high tech na are obtained that and Neetu systematic symptoms minute yaar ki vijendra yudhishthir always one is used absolutely inbuilt reverse on yaar absolutely inbuilt reverse on yaar that a can simply that a can simply is or prevails is or prevails that in it that in it that in it Format Of Vihar Incident Solve This Problem S E Will Tell Ka MP3 Same Science That Target Person All And Will Start From The End Of The Governor D That In These Girls Admit Temp That Angry Will Start Feeling And Temperature Lutiya Lutiya Lutiya mein tel put and tagged aa tere ko calendar mein tel put and tagged aa tere ko calendar blue and english with ki film ki and will get all blue and english with ki film ki and will get all reverse format and reverse format and vaikuntha but in this case 10 complexity of question is can they question is can they perform this in english improved toss perform this in english improved toss complexity complexity complexity 52.21 Starting from 52.21 Starting from ki and ki ki and ki in one form in one form happened pure first point at this point happened pure first point at this point in guest in guest ki intact roti length of ki intact roti length of ki sexual article - work ki sexual article - work select edwin limit select edwin limit i left leg limit tract i left leg limit tract tomorrow tomorrow tomorrow world this the left world this the left and right that when misal the mid point is solved and is high voltage dahej ka price point se zap both of you and wickets vs eng in the time Right index Right index Right index and values for not develop and values for not develop a co an interview with writing axis pe a co an interview with writing axis pe ki sabhi welcome ho anti veer kam hair hai ki sabhi welcome ho anti veer kam hair hai shri navdurga in movies left point to shri navdurga in movies left point to right 51512 alex 500ml feint welcome welcome right 51512 alex 500ml feint welcome welcome to me nine idols paint ki selwyn kam hai two Welcome To Your Knowledge Navi Welcome To Your Knowledge Navi Welcome To Your Knowledge Navi Mumbai Life Mein Tubelight Android Phone Mumbai Life Mein Tubelight Android Phone Tablet Samaai Last Point Is Se Zor Again Will Spoil Were That Login Me Left With Comment Light Bill Comment Ko Again Will Destroy 06 Name Electronic Comment Oye Yaar I Don't Have Innovative That 10th 219 Alex Kontouris Comment Pati Android Jhaal Normal Life Interview Amazing Site Will Jhaal Normal Life Interview Amazing Site Will Commit And That Agnivesh Commit And That Agnivesh Now And Bye Me Now And Bye Me Tension Will Stop Hair y55l Mode Hain Tension Will Stop Hair y55l Mode Hain Ride Point To The Length Of This Point And This Ride Point To The Length Of This Point And This Condition Will Not Satisfied E Condition Will Not Satisfied E Tomorrow Morning Stopping Edit NCI Will Have 200 Tomorrow Morning Stopping Edit NCI Will Have 200 Beds Blood Bottles During This Time Beds Blood Bottles During This Time Elections Will Be A How To Elections Will Be A How To Open Time End Of Birth Place That Previous Dominate In English Sentence Complexities Of Beneficial As Well As Malefic And Back To Characters And What Is Equal Complexities Complexities Complexities How to Open Sudhir Vipin Sood This How to Open Sudhir Vipin Sood This Question Let's Move to What is the Work Number for Question Let's Move to What is the Work Number for Significant to be Replicated Significant to be Replicated Interviewer The Giver - 1 Interviewer The Giver - 1 Bluetooth Setting Mobile Popular Left and Bluetooth Setting Mobile Popular Left and Right Painting of Velvet Ka But Text Right Painting of Velvet Ka But Text and Taken Away Their Rights and Wasted with Ours and Taken Away Their Rights and Wasted with Ours Right and left after clean sweep in Right and left after clean sweep in love letter love letter side me left to right love letter love letter side me left to right and right the volume to plus to subscribe to and right the volume to plus to subscribe to jhaal edit ko text message solution for this problem love you can find the ko dinner description love you can find the ko dinner description give this video give this video give this video when thank you so much for watching our | 2024-03-24 11:04:21 | 344 | Reverse a String | reverse string leetcode | reverse string python | leetcode 344 |
|
BzTIOsC0xWM | Tiger, in this video, we will find the solution to this in minimum questions. We have the solution to this in minimum questions. We have the complete matrix in front of us. Sorry, complete matrix in front of us. Sorry, inside the maths, that Bigg Boss has been given. Friends, inside the maths, that Bigg Boss has been given. Friends, you will have to pay to fix it and you have to you will have to pay to fix it and you have to carry the topless button. There are many of carry the topless button. There are many of you. you. you. you can use any number of buses and I too am of course you can go, you can go like this but very probably, you have to What will we do inside this, will we What will we do inside this, will we What will we do inside this, will we make stories, so this is this make stories, so this is this time, this is how much time and a, we breathe kumkum and tell that we will keep the empty land twice, so close, one is coming original and one is whatever we have got. Okay yes, this is coming. Okay yes, this is coming. That I have found a Jaunpur whose name is That I have found a Jaunpur whose name is original, whose name is we will make original, whose name is we will make BP video, so BP video, so if I make it empty then it will remain mine, if I make it empty then it will remain mine, all my centers have also initially fallen on vegetables, all of you have been examined, so what do we do? all of you have been examined, so what do we do? all of you have been examined, so what do we do? our difficult stage was that till the time I find and delete it, I will stitch it in the thoughts about our interest in the tablet, we will get information and storage and its meaning, then we had to think, well, solving the direction problem, family If it used to be, then while I am If it used to be, then while I am If it used to be, then while I am deleting these cells, you should consider meeting the DP person that if you have recharged the phone, then I will tell you what is available at that if you have recharged the phone, then I will tell you what is available at any place, what would you have read about the any place, what would you have read about the cheapest routes to know the destination from there. cheapest routes to know the destination from there. cheapest routes to know the destination from there. price of Rs. 1000 must be lying there, on the other side, I am telling you that what is cooked in the serial, this is the best way to go to Sheshan, how much money will it cost, there is a shorter way than this, which will cost less money, how much money will it cost, You must have read what you must have read on this channel. Don't know how You must have read what you must have read on this channel. Don't know how You must have read what you must have read on this channel. Don't know how many people many people live here. From here, who knows how many people live here. The live here. From here, who knows how many people live here. The best thing that is proposed inside them is best thing that is proposed inside them is how much money do I make on this. It will start here how much money do I make on this. It will start here if I make a big sign. if I make a big sign. if I make a big sign. now we cover it, no problem, find out about their love, where is the small problem, the big role is, my face is not hidden, that going from here to here will cost the least amount, that there would be happy duty here, even if it was ₹1, that there would be happy duty here, even if it was ₹1, it would be far away. it would be far away. it would be far away. seems to be on Sardar, then the smallest compliance is here, if you send the biggest party then it will come from here, it is cheaper and if it comes from here and most of the accidents happen, If you If you If you come to the poll related to this then the problem will be from bottom to top. come to the poll related to this then the problem will be from bottom to top. We will travel round the world while We will travel round the world while Yuvraj will do Swiss roll. If we Yuvraj will do Swiss roll. If we try again then I will give it. Okay, now the try again then I will give it. Okay, now the scheme will be applicable that it will scheme will be applicable that it will come from here, it is cheaper and at the same time. come from here, it is cheaper and at the same time. come from here, it is cheaper and at the same time. costing two rupees, so if you are from here, then you will become tied to here, see, it cannot be increased or taken and beyond this, two more rupees are spent, so there is an option, see, I am yours, it is a simple thing, you think If we want to go, then we can go to as many shops as we can, let's If we want to go, then we can go to as many shops as we can, let's If we want to go, then we can go to as many shops as we can, let's say we can buy a piece say we can buy a piece from here, we can buy water for ₹ 1 from here and we from here, we can buy water for ₹ 1 from here and we can buy the market from here and we can buy the market from here and we spend minimum amount of money. Okay, so whatever you want. spend minimum amount of money. Okay, so whatever you want. Go to the place and there is another one too in this dry Go to the place and there is another one too in this dry luck will shine so retired understands this so luck will shine so retired understands this so I am giving it to you also but pay attention I am giving it to you also but pay attention that if we assume this then I that if we assume this then I can go to dayan to go to the source and destination can go to dayan to go to the source and destination and in going there you have to and in going there you have to and in going there you have to and you can go to I-2, our blood pressure is wide spread when we go there and our blood pressure can be 120 when we go there, or we can go to Delhi from I-20 right there, we can drink alcohol in DJ joint If we do then where would you like to If we do then where would you like to If we do then where would you like to go, you would like it the most I go, you would like it the most I hope you would like to go there Come hope you would like to go there Come make love darling, one of your festivals make love darling, one of your festivals is at the root and there are quiet s from there is at the root and there are quiet s from there You will improve at the place where You will improve at the place where both of these are minimum. both of these are minimum. both of these are minimum. and there will be a laddu fight and this will be our answer. So much money will be spent that I will listen to Haridwar. See, as brother talks about going from Chandigarh to Delhi, Chandigarh is there, we have to go to Delhi, from Chandigarh we assume that we In this case, we In this case, we In this case, we can go to Ambala, let's assume and the song can go to Ambala, let's assume and the song comes, ' comes, ' Brother, it doesn't come, we can go to Saharanpur. Brother, it doesn't come, we can go to Saharanpur. However, while going to Yamunanagar, we However, while going to Yamunanagar, we take our Ghaghra as the owner, take our Ghaghra as the owner, from Yamunanagar to Delhi, half of it is from now and from Yamunanagar to Delhi, half of it is from now and from Saharanpur to Delhi. from Saharanpur to Delhi. from Saharanpur to Delhi. take it from here, then we will take it from here, and if it is made from here, then we will take it. Okay, so I hope that you have understood the basic romance, so brother, this is a preposition, only the dead and young If you are If you are If you are paying from above there then it will be 8 rupees for this channel and paying from above there then it will be 8 rupees for this channel and further from the telescope, it will be 8 rupees. If you further from the telescope, it will be 8 rupees. If you picked it up from here, you will get Durga Sun Tan from here. Now do picked it up from here, you will get Durga Sun Tan from here. Now do n't understand this trick, General Mutual, it n't understand this trick, General Mutual, it will be paid within a couple of rupees, so I understand. will be paid within a couple of rupees, so I understand. will be paid within a couple of rupees, so I understand. come then that current from death will come here where if the question problem is solved in this program then it is better then it will be fine with the money always through this YouTube because when you start understanding later then you will be Only Only Only one can go and from here it is costing you ₹10. one can go and from here it is costing you ₹10. From here it is costing globally From here it is costing globally and in this year if you have your own flight then and in this year if you have your own flight then it has to be in zoo or airport. it has to be in zoo or airport. Now we will focus on this. From here only Now we will focus on this. From here only go here. go here. go here. here, now from here we will do it here near you and we can also go down there, sweets 2025, this romance in bed, 25 friends, eyes on this, now let's talk about here. now let's talk about here. now let's talk about here. one option can go down, so we will remove it from there and then listen to standing here, being famous, this is the first place where there is an option to understand something different, If you If you If you go from here then we will go from here then we will take 11. If you go from here, then if they came here from here, they take 11. If you go from here, then if they came here from here, they spend these days and spend these days and come here, then we can also go from here to here and from here to here and come come here, then we can also go from here to here and from here to here and come down here. promise is Rs 1010 per promise is Rs 1010 per ki, now if we talk about it here then look, ki, now if we talk about it here then look, he is going to be hit on the round, he he is going to be hit on the round, he can reach here in the round, he passes both the legs here, if he reached can reach here in the round, he passes both the legs here, if he reached here for ₹ 2, then he will be hit 11 here for ₹ 2, then he will be hit 11 in the race, he is needed here because if he will be hit in the race, he is needed here because if he will be hit He will milk and 65 and will go to the place from where the He will milk and 65 and will go to the place from where the money is taken. These settings are 216 money is taken. These settings are 216 that now I have studied in school. Three value in these are in Shift Industries Ltd. Indore. Miding is in miding 523. If you are in Shift Industries Ltd. Indore. Miding is in miding 523. If you subscribe here one by one, here you are in these subscribe here one by one, here you are in these temples. because this means that subscribe this channel, subscribe to know because this means that subscribe this channel, subscribe to know and this indicates that if you want to do this, then we will discuss on three or 18 because it that if you want to do this, then we will discuss on three or 18 because it will be cheaper from here, then you can cut it from here, will be cheaper from here, then you can cut it from here, whose is it, why is this center? whose is it, why is this center? whose is it, why is this center? damaged, we could reach here by spending three rupees and from here, TV-18 is available, we could tie it to China too, but from here, the family members would prefer to spend three rupees in the middle, and from here, three will move away, if The combination of these two is the The combination of these two is the The combination of these two is the sleep of victory for the memory people here, the sleep of victory for the memory people here, the meeting of these two plus sure, the main plus one of these two, meeting of these two plus sure, the main plus one of these two, it is clear that it is it is clear that it is just eight, with it or not, 1719 flask just eight, with it or not, 1719 flask 680, I have seen these two 3130 1000 stories 680, I have seen these two 3130 1000 stories 90 90 90 minutes 1268 fill you are so full so now just comment below here both my 2019 plus accessibility then I 000000 this I think oneplus 3 to 4 minutes cornflour plus on the back is the same on both sides that is Pada Twentyeight 409 Pada Twentyeight 409 Pada Twentyeight 409 Plus Vanshmani otherwise you will be a viewer that yes, Plus Vanshmani otherwise you will be a viewer that yes, from here there is no problem on either side, you from here there is no problem on either side, you can go down here 225 27 can go down here 225 27 Recipe of both 464 days I have 0005 This is my Recipe of both 464 days I have 0005 This is my story for class ninth from 1000 This is two so story for class ninth from 1000 This is two so below below below a plus six 06 - one five plus minus plus subscribe, subscribe, almond or almond or hard in to-do so we will make our own hard in to-do so we will make our own channel which is Ajay's How many days are there, how many How many days are there, how many How many days are there, how many columns are there for Ajay that I had made him my ideal, what resolutions are coming that I have looted and taken input in it, Ajay has been called, I have found this in the report, then I called Deepika in the morning itself. Made it and here is my Deepika, it should be as big as it is, it should be as big as can say in giant and semi, okay, I will make it from the banks to do it like this, we are you Now it will be seen that we will roll it from here to there, from Now it will be seen that we will roll it from here to there, from Now it will be seen that we will roll it from here to there, from bottom to top, they enter bottom to top, they enter equal to BP dot length - 120 - - - 10 - I equal to BP dot length - 120 - - - 10 - I like the good ones as I like the good ones as I say, separate them from the last, do do do do, we are the last. what do we do in the last row, just what do we do in the last row, just prepare this bill for the next rally, prepare this bill for the next rally, here is 10 Ujjain, when 1981 is here is 10 Ujjain, when 1981 is out, then there is an option to give inch plus minus point out, then there is an option to give inch plus minus point questions, just go down from the last ones. questions, just go down from the last ones. questions, just go down from the last ones. like it was broken here, Khurram Plus 98100 can live above and below it, then center sites one to two, now what happens in the rest of the area, India is in a plight in the rest of the area, like if you It will be It will be It will be small, it will have to be added here, okay, small, it will have to be added here, okay, so I will look at the things carefully in four parts, so I will look at the things carefully in four parts, now this one that has come is on one of our teams now this one that has come is on one of our teams and its use is also simple, so it means and its use is also simple, so it means we are in the last we are in the last voice mail Celsius, that is, just for planting team. voice mail Celsius, that is, just for planting team. voice mail Celsius, that is, just for planting team. we are then we are in the last row, this is we are then we are in the last row, this is our column on this team, the last last is the last our column on this team, the last last is the last problem of this restaurant style problem of this restaurant style Meghwal, if you are in the last then you simply Meghwal, if you are in the last then you simply cannot go, if you are in the last only cannot go, if you are in the last only and only then from where you get so much money. and only then from where you get so much money. From here you will find From here you will find that our recipe is in the that our recipe is in the mosque, how much money will it cost from there, mosque, how much money will it cost from there, it is lying in the middle and how much money will it cost on our spot, it is lying it is lying in the middle and how much money will it cost on our spot, it is lying there, what is it in the vertical case, I am a what is it in the vertical case, I am a what is it in the vertical case, I am a can go to that place, which is that place? Doppler Shivam Jain, so held, how much money will it cost, I got it in the DP, I plus tells the reason, I plus one happily, which is the best, how much money will it cost, it is And And And how much money will it cost me to go there, Arya how much money will it cost me to go there, Arya is lying in the size. Okay, now if you have two is lying in the size. Okay, now if you have two options, you can go, then you will have to take options, you can go, then you will have to take Clash Of The Amazing, where can you go and Clash Of The Amazing, where can you go and in that, Ajay is confused Ud input ma'am Ud input ma'am Ud input ma'am do it small 23114 subscribe to do it small 23114 subscribe to also there is no damage submit this also there is no damage submit this that they bowl correct answer commissioners have to | 2024-03-20 11:01:46 | 64 | Minimum Cost Path Dynamic Programming Explained with Code | Leetcode #64 |
|
dPYHqRHpzWw | [Music] and good afternoon to all of you today and good afternoon to all of you today we have problem which name is reduction we have problem which name is reduction operation to make the array element operation to make the array element equal lead code B8 87 problem so before equal lead code B8 87 problem so before going forward in this video please make going forward in this video please make sure that you have like And subscribe to sure that you have like And subscribe to this Channel and also it's my advice to this Channel and also it's my advice to all of you that please read the problem all of you that please read the problem carefully and try to build up the code carefully and try to build up the code and try to do the code also then it will and try to do the code also then it will be beneficial for you and if you simply be beneficial for you and if you simply see this video and then do the code it see this video and then do the code it will not be beneficial for you so do The will not be beneficial for you so do The Code by yourself then see this video Code by yourself then see this video let's read the problem statement we have let's read the problem statement we have given an integer array nums our goal is given an integer array nums our goal is to make all elements in nums equal to to make all elements in nums equal to complete one option follow these steps complete one option follow these steps so these are some steps that we have to so these are some steps that we have to follow find the largest value of nums follow find the largest value of nums let's index I and its value be largest let's index I and its value be largest and we have to find the next largest and we have to find the next largest that is just smaller than means strictly that is just smaller than means strictly smaller than the largest value and we smaller than the largest value and we have to convert nums of I to next have to convert nums of I to next largest means largest value to next largest means largest value to next largest value next largest value is the largest value next largest value is the just smaller than the largest value so just smaller than the largest value so let's uh see the let's directly go on let's uh see the let's directly go on the approach part for this let's see so we have we have a array which is 513 so firstly we have to find the largest element so I have some methods to find the largest element I can use priority CU sets also and map also so I'm using the priority CU then it will be 531 because it is in priority CU if I use a Max then it will be in increasing order then it will be 531 so we have in this 531 our largest element is five and our next largest element that is the just smaller than the largest element means strictly smaller than the largest element so next largest element will be three so we have to convert the largest element to next largest element means we have to convert 5 through 5 to 3 then it will be 3 3 1 now we can see there are two threes me number of count of three equals to two so we have to convert all three to one so how we can create we can create a map so that we can count the frequency also so the the frequency of three is two and the frequency of one is 1 so we can convert the three which is the largest element to the next largest element that is the one so this will be one and uh what we will do here we have done the first uh conversion so it our answer will be one now we will add our in our answer that will be means 1 + 2 that will be three then three will be our answer because uh we can see that frequency of 3 = to 2 if we convert three see here here three is coming two times so we have to convert the three so it will be 1 + 1 2 and our final answer will be three so let's take another example here we have given this array so if we use the priority CU then it will be the order of the array will be 3 22 1 1 so now we can create the frequency we can use the map so Three is coming only one time two is coming only two times and one is coming two times so now this is done so our largest element is three and our next largest element is two so we will convert the largest element to next largest element means we have to convert three to two so it will be two and the frequency of this new largest new value is one so we we will add this in our answer then it will be one now we can see our frequency of two is three and the frequency of one is two because we have we have not done any operation in this so it will be save so one is coming two times and one is two is coming three times so now our largest element is two and our next largest element is one so we have to convert largest to next largest then it will be one so we have to add the frequency in our answer so will 1 + 3 4 our final final output will be one comma five because one is coming five times and we have not given any in next largest element so we will stop here and our answer will be four so let's discuss about time and dis space complexity for this so we can see we are using priority Q so it will be n log n and we are Al also using uh map then it will be big go of and so let's uh add these two big of n log n plus big of n so it will be big of n log n and space complexity will be big of and because we are using the map so we can reduce the space because we we are using the map why we are using the map we are using two data structure in one question so we can optimize this so we can optimize big and space complexity I talking about space complexity so big and to big of Logan so how we can do this big of log and big of bun also so let's see we have the given arrays 32211 so what I will do is I will create a count count variable and our I will create answer variable that I have to return so I will not do anything with our answer variable so I will do the operations with our count variable so whenever I I will find the transformation I I will add count I will add one in count means like initially I will add one in count so as you can see I have found the transformation so I will add this in our answer so it will be one now I will this this three will convert to two now I will go forward and I will see another transformation so here's the transformation so we can see two is coming three times so I will add three in this so it will be 1 + 3 = 4 so let's see the code so that we can understand properly so let's discuss about time and space complex for this why it is optimized solution because here we can we are using the we will sort this actually we'll sort this in decreasing order you can sort this in increasing order also so that in that particular question that you have to Traverse from the back I will Traverse from the start so I I will use the reverse order of sorting and in that method the time complexity will be go anog and that is same as a previous time complexity but the space complexity here is B of log n because we are sorting and we are storing some elements or it it can be big of one also so big of log n is the time complexity for this let's uh see the code for this so in this what I will do is I create int nals to nums do size I'll sort in reverse order you can sort in uh increasing order then you have to Traverse from the back I'm starting from the start I am traversing from the start variable start pointer so I have to sort this in a reverse order means in decreasing order so sort how we can do nums do ran ran comma nums dot R and that will give me the reverse order of reverse decreasing order means decreasing order of 4 AR now I what I will do I will create in answer that I have to return and int count varable I am starting from in count equals to 1 why I'm starting from count equals to one let's see for in I = 1 to I less than n then I ++ now I'm traversing from the start and I will check if nums of I is not equals to nums of IUS 1 then I will add this count in our answer variable answer plus equals to count and other in otherwise what I will do I'll increase the count because let let uh let's see in this I have increased of kind I have changed this three to two and I have increased the count lights burn then two then three and uh here I have I found the transformation so I add this count in our answer so it will be four now what I'll do I'll return return our answer so in this code what I have done is I have created our answer variable that I have to return and count because I will increase the count again and again when whenever I feel I I found the transformation and I why am I starting from the I = to 1 because I have to check the previous element of also if that uh current element or previous element is not sa then I will increase the I will add that count in our answer so I have initially added the count in our answer then otherwise I will increase the count code yeah it is working perfect let's code yeah it is working perfect let's submit this as you can see it is working perfect as I have told you as I have already told you that the time complexity for this is we of anog because we are only sorting that and space complexity B go of n big of log n sorry because some somehow we are storing some elements in that array or it can be big of one it depends on so if you find this helpful then please like share and subscribe and if you know another approaches for this I have already told you about another approach that priority Q map you can also do that approach and uh let's see | 2024-03-25 11:58:13 | 1,887 | Reduction Operations To Make the array Element Equal Leetcode 1887🔥 |
|
7_4BbPy1-FE | hey hey everybody this is larry this is day three of the august leco day day three of the august leco day challenge hit the like button hit the challenge hit the like button hit the subscribe button join me on discord let subscribe button join me on discord let me know what you think about today's me know what you think about today's problem problem uh yeah uh yeah just a random quick update i did trivia just a random quick update i did trivia night here in new york there's a trivia night here in new york there's a trivia league uh definitely recommend everyone league uh definitely recommend everyone to trivia but i did it with a bunch of to trivia but i did it with a bunch of my friends this is loading really slowly my friends this is loading really slowly um um and yeah and we finished second place and yeah and we finished second place today it was a good comeback we were today it was a good comeback we were down down down a lot from the first round but we down a lot from the first round but we kind of four our way back and got kind of four our way back and got i guess more free alcohol which is good i guess more free alcohol which is good what is going on but yeah so i'm having what is going on but yeah so i'm having a good swell day also a little bit a good swell day also a little bit uh burst in a good way uh burst in a good way and as soon as i can open these uh what and as soon as i can open these uh what is going on here is going on here well uh yeah running into some technical well uh yeah running into some technical difficulties but hope everyone's doing difficulties but hope everyone's doing all right on this fine uh tuesday or all right on this fine uh tuesday or wednesday depending on when you're wednesday depending on when you're watching this let me click on this again watching this let me click on this again oh there we go now it's loading that's oh there we go now it's loading that's really weird anyway really weird anyway yeah let's let's look at today's farm yeah let's let's look at today's farm and as usual as i would say i do plan to and as usual as i would say i do plan to do a bonus question after this a random do a bonus question after this a random question i haven't sell before so question i haven't sell before so definitely you know hit the subscribe definitely you know hit the subscribe button and hit the bell and get notified button and hit the bell and get notified on those problems as well anyway today's on those problems as well anyway today's problem is problem is my calendar one or my candle eye my calendar one or my candle eye you're implementing a program to use as you're implementing a program to use as you can there new event if it doesn't you can there new event if it doesn't cause a double booking so double booking cause a double booking so double booking is something about intersection is something about intersection and start to end okay and start to end okay um so you just do start and end and um so you just do start and end and youtube start doing it with 10 to the youtube start doing it with 10 to the nine okay nine okay so the one thing that so the one thing that you would recognize here is that there's you would recognize here is that there's a sort of um [Music] there's a sort of um how do i say this there's a sort of like uh um structure there's a sort of structure in which um [Music] you know it's very binary searchable is what i was going to say and you would do uh in the sense that because we don't have to we i guess even when we move stuff it's okay but because we only add stuff we can definitely um do a binary search and then change it and then add stuff um and it's by now binary search is not the right or well binary search is part of the answer the other part of that binary search is having a binary binary search structure and that structure is going to be very often a binary tree so okay so i i think i spoke too quickly about the binary search but for a reason that you'll see in a second but if you do it in a binary tree or maybe a segment tree type thing um this would be perfectly well i guess you can do segment three because it goes up to ten to the nine but but yeah but that's basically the idea is this binary search tree and a balanced binary search three will allow you to do a read and uh and an ad in of one time or whatever right oh sorry oh of luck end time obviously i don't know why i misspoke like as i made my trying a little bit but yeah the way that i'm gonna do it is with sorted list which is kind of a magical thing from from python from python so yeah and idea we have to be a little so yeah and idea we have to be a little bit careful but it really is pretty bit careful but it really is pretty straightforward i think we let's see we straightforward i think we let's see we want to binary search want to binary search how do we want to bind themselves we how do we want to bind themselves we want to binary search to start want to binary search to start um um because basically what we want to store because basically what we want to store is the left and the right and then here is the left and the right and then here what we want to do what we want to do is is just do a binary search and then look to just do a binary search and then look to the left look to the right to see if the left look to the right to see if they intersect with either of those ones they intersect with either of those ones i think that would be good enough i think that would be good enough um i could be wrong but um i could be wrong but yeah um yeah um maybe you have to do an extra one if you maybe you have to do an extra one if you really want to be safe like two on the really want to be safe like two on the left two on the right left two on the right but i think one should be but i think one should be good because you wanna you wanna see if good because you wanna you wanna see if your current segment clips with the one your current segment clips with the one on the left or the one on the right on the left or the one on the right right and if it's if it matches exactly right and if it's if it matches exactly then you encrypt the one on the right then you encrypt the one on the right but if you don't but if you don't match it then it's gonna be the one on match it then it's gonna be the one on the left um depending or like the left um depending or like yeah yeah otherwise it's going to be the one on otherwise it's going to be the one on the left and then you'll just have to the left and then you'll just have to check i think that should be good but check i think that should be good but yeah so if so now we have self.sl of yeah so if so now we have self.sl of index so okay so well first we have to check that index is less than length of self.sl less than strictly if this is the case and uh okay so this is the case then let's check this so then here i'm just going to call left right is you go to self.setup index and then what happens right then we check whether it overlaps so if the [Music] or um [Music] then it overlaps then it overlaps yeah is it inclusive exclusive oh it's okay muted stuff but uh okay muted stuff but uh okay so this is actually so we just have okay so this is actually so we just have to be a little bit careful but i think to be a little bit careful but i think we can just minus one on the end sign we can just minus one on the end sign should be okay because it does it's a co should be okay because it does it's a co open range so yeah then if this is the open range so yeah then if this is the case when we return force otherwise we case when we return force otherwise we do sub dot sl dot add of uh start and do sub dot sl dot add of uh start and actually we forgot to do so this is one actually we forgot to do so this is one of them and then the other one is of them and then the other one is is is if index minus one is greater than zero if index minus one is greater than zero uh yeah uh yeah then left right is equal and then we try then left right is equal and then we try to we just do the same thing to we just do the same thing but for index minus one maybe we could but for index minus one maybe we could use the helper here uh we add and then use the helper here uh we add and then return true and i think this should be return true and i think this should be good good maybe i have my oh wait we have to do n maybe i have my oh wait we have to do n minus one to make it inclusive just minus one to make it inclusive just slightly easier for me let's see okay that looks good let's give it a submit i it's very easy to have it off by one so we'll see apparently last time i had two wrong answers and this one i have one wrong answer so maybe i should be a little bit careful but honestly some of it is just me being lazy but uh okay so let's see what the discrepancy is or maybe i hope that it's a minor discrepancy and not just like some major thing but i like to click on diff so okay 47 33 41 uh did i return the wrong thing oh no i returned the right idea i mean okay so let's see so we have 47.50 then we have 2341 then we have 39.45 which is bad 33.42 which is also bad and then 25 32 which is good and then and then oh i see oh i see uh that's just sloppy because i did n uh that's just sloppy because i did n minus one because i want it to be minus one because i want it to be inclusive but that also means that this inclusive but that also means that this end should be inclusive right so because end should be inclusive right so because this this 25 clips this one it thinks it this this 25 clips this one it thinks it overlaps but it doesn't so um i just overlaps but it doesn't so um i just need to be better about this or need to be better about this or consistent about this um consistent about this um that was just sloppy let's see if that that was just sloppy let's see if that fixes it fixes it oh it still is wrong huh oh it still is wrong huh oh and then now is the last one oh and then now is the last one let's see so yeah so okay so let's say this was uh corrected to be true is the oh this is it no this is right and then 3a let's see uh and then 8 13. it's okay and then 1827. oh i knew that this was going to be the case ah but i i was i thought that maybe i could be lazy on this one but i was just wrong so what happens here is that uh yeah i mean i just needed to do the whole thing um okay let me actually rewrite this a little bit uh to make it inclusive so now this is more clear and i actually thought that i needed to do this but i couldn't prove it but i was just lazy and then i thought that uh um yeah and this should be good i think um yeah and this should be good i think especially now that we are oh well this especially now that we are oh well this one's wrong because now we want to one's wrong because now we want to uh because we didn't subtract one uh because we didn't subtract one just so happens that that was right but just so happens that that was right but okay let's give it a quick submit again okay let's give it a quick submit again um again this is just me being lazy um again this is just me being lazy maybe i could have came up with more maybe i could have came up with more cases but this is good so yeah i was cases but this is good so yeah i was just literally sloppy with two things just literally sloppy with two things one is one is um not paying attention about the um not paying attention about the inclusive exclusiveness which is inclusive exclusiveness which is something that happens a lot so maybe i something that happens a lot so maybe i need to be better about and this is the need to be better about and this is the type of farm that i don't know why i'm type of farm that i don't know why i'm rushing that much but still um rushing that much but still um need to be better and this this one i need to be better and this this one i knew but i thought that maybe i could knew but i thought that maybe i could get away with it because maybe i think i get away with it because maybe i think i miscounted in my head but um yeah so miscounted in my head but um yeah so what's complexity here well we're to do what's complexity here well we're to do two binary search and one binary ish two binary search and one binary ish insert a log event insert so this is insert a log event insert so this is going to be o of log n and that's pretty going to be o of log n and that's pretty much it of n space of n log n time and much it of n space of n log n time and yeah yeah that's why i have this one let me know that's why i have this one let me know what you think stay good stay healthy to what you think stay good stay healthy to good mental health i'll see you later good mental health i'll see you later and take care remember i'm going to do a and take care remember i'm going to do a bonus one after this so bonus one after this so definitely check that out uh give me definitely check that out uh give me some love and support i want to because some love and support i want to because what i did last time okay i'm not gonna what i did last time okay i'm not gonna i guess i had the same i i guess i had the same i oh i did a binary search on both i think oh i did a binary search on both i think that would have been a little bit that would have been a little bit trickier but um and as you can see with trickier but um and as you can see with the wrong answers okay anyway the wrong answers okay anyway stay tuned bye | 2024-03-21 11:40:08 | 729 | 729. My Calendar I - Day 3/31 Leetcode August Challenge |
|
rQauFDgDauM | Hello gas welcome to me YouTube channel so today we are going to solve the problem seven six solve the problem seven six seven your nice string so seven your nice string so what is the question that I have been what is the question that I have been given a string and the characters have to be given a string and the characters have to be rearranged in such a way that any two rearranged in such a way that any two characters characters characters with adjustment is fine as it is, so now it is A. B. So this cannot happen. Even if you do it, keep only one. Still keep it. Then two A. A will go. If this is not Will return. Will return. Will return. Okay, so this is a question, Okay, so this is a question, so what will be its root four solution? Let's so what will be its root four solution? Let's see by leaving the time constant. Okay, for see by leaving the time constant. Okay, for now, let's leave the time constant, no matter now, let's leave the time constant, no matter how much it is, it doesn't matter, just find out the how much it is, it doesn't matter, just find out the basic solution, like if A is B, then If it happens then it is three permutations and it can also be that it is from both the characters so a little less permutation is being made but then take out the head, okay time complex time complex is too much, so now this is too much, so now this is too much, so now this ? So, for example, on this example, I have to rearrange it in such a way that no adjacent one should remain equal. Okay, so how can we think about this? So see how many distinct characters I have in this, then then then higher frequency, what will happen to it that it will get adjacent And the character which has low frequency, so the one with And the character which has low frequency, so the one with low frequency is low frequency is doing the one with low frequency, there is A next to it doing the one with low frequency, there is A next to it in adjustment, now that one with low frequency in adjustment, now that one with low frequency is two and is two and mother, take A, B was A, so now we have taken B. What back did I have [music] If I finished it, it would have been profitable, but in 1 lakh less Bastar, it has less relief than a few, if it is with some character, then what will we do in this too, that we are what will we do in this too, that we are whose maximum character. whose maximum character. whose maximum character. first, it is beneficial that while doing it till the last, its frequency will reduce, if it is high then we will have to finish it first, otherwise it will go back to the last, so we will do the same, we will take the one with high frequency first, B-2 at one place, okay, at one place, okay, now what is my shortage, I will do 1000 and the second one which has higher frequency, do 1000 and the second one which has higher frequency, why because I will have to why because I will have to finish both of them quickly otherwise. finish both of them quickly otherwise. finish both of them quickly otherwise. if we don't finish it first, then Ed, we took it first, and still, and yet, and the alien is fine here and there, it went back quickly, from the beginning, you take it from A, less, let's put it from B first, then like put it. Then we put one more big and then another big and then how much did A get 2 2 4 3 5 5 It happened that if A is more then if we make adjustments to it then we will get more benefit and then The second maximum character The second maximum character The second maximum character which will be the second last to be created will have to be eliminated first, which will be the second last to be created will have to be eliminated first, so we will take the maximum and the second so we will take the maximum and the second maximum again and again maximum again and again from this and then we will create it, from this and then we will create it, so as you see, we will take the maximum character, so as you see, we will take the maximum character, first we will take A, how much of first we will take A, how much of this child do I have? this child do I have? this child do I have? open, we will finish first because there are chances that he will go back ok, it became less, then it became three, now look, again ok, it became less, then it became three, now look, again B came, B is done, ok, so what to do, It will come out It will come out It will come out fine and after taking it in the loop itself, then we will fine and after taking it in the loop itself, then we will connect both of them and then we will mine the connect both of them and then we will mine the frequency of both, so see if frequency of both, so see if we can do better than this, we will we can do better than this, we will raid the loop again and again, then find out the maximum second maximum and then raid the loop again and again, then find out the maximum second maximum and then do the frequency, do the frequency, then it would be better than this. then it would be better than this. then it would be better than this. transaction? Okay, so for this, if I have three, two, one, now what data structure do I have in now what data structure do I have in which there is always maximum relief at the top, which there is always maximum relief at the top, how do we enter it? how do we enter it? how do we enter it? and then we will keep on addressing, we will and then we will keep on addressing, we will take maximum second maximum and then we will do 20 mines till we keep doing it take maximum second maximum and then we will do 20 mines till we keep doing it as long as there are two characters as long as there are two characters inside it then it is fine so inside it then it is fine so like if we take the first then it should also be like that the Gone one by one, okay, still then A and B zero, now how can this also happen zero, now how can this also happen in the last, okay, so in the last, okay, so what will we do for each of the A's, we will take them out and add them outside the loop, what will we do for each of the A's, we will take them out and add them outside the loop, okay so that okay so that okay so that but you have to put a condition that which of the two characters has a child, add it, now see, you can optimize it a little more, how now take mother, I have this can never happen. How much is N in it? So we will not be able to keep 426 plus in it. So if any character is more than N + 1/2 then we cannot keep it. So let's see its code. The code is also very easy. There is nothing much so see what we did Optimize by finding out the frequency Optimize by finding out the frequency Optimize by finding out the frequency and maybe in the beginning it should be said and maybe in the beginning it should be said that if the frequency of any character is that if the frequency of any character is more than n+1/2, more than n+1/2, how to do this, A and E are and its para is first and second. and its para is first and second. and its para is first and second. its frequency and the second one will have its character. Okay, the character should also be known whose character is that which we have popped above. So keep it first because you can do it in any way, But it does, But it does, But it does, okay, so we keep the frequency on it, the okay, so we keep the frequency on it, the computer will compare, the one with the maximum frequency will be kept in the open, okay, so top, the one with maximum will top, the one with maximum will remain first, so whatever is the maximum, now again and again remain first, so whatever is the maximum, now again and again I I I maximum and in which second, so take out the maximum and it will be added later by doing minus one, it will be added later by doing minus one, but if you do not pop the time, then again it will but if you do not pop the time, then again it will give the maximum, this give the maximum, this character is okay. character is okay. character is okay. another character besides this then we pop it and then this del is got the second character. Now what did we do in the answer, when we were pushing here, for how long was we pushing? when we were pushing here, for how long was we pushing? when we were pushing here, for how long was we pushing? now if it has become zero then there is no benefit in putting zero again with zero frequency. If the zero one has become zero again in the line then give greater one, only then we will ask again after doing minus one the Ok, in Ok, in Ok, in this way the same was done in p2 also. Now this way the same was done in p2 also. Now see what will happen in this method. We are see what will happen in this method. We are going with a valid key. In the beginning it will be going with a valid key. In the beginning it will be impossible only if the frequency of any one is impossible only if the frequency of any one is more than n+1/2. more than n+1/2. more than n+1/2. how will invalid ever come here, it is okay below this, this is where we return these valid ones, so whatever is made here will always be your valid cut, so why are we adding it here, Take a character that went back, like this Take a character that went back, like this Take a character that went back, like this one came back like A A B B, this one one came back like A A B B, this one came first and then again relief from both now becomes zero but relief from both now becomes zero but not from both because in the first time both of them would have not from both because in the first time both of them would have been a sin and then the second time. been a sin and then the second time. Both of these become zero together, so if there Both of these become zero together, so if there is one, that means there is an extra character, it has to be added. Okay, then what is its time complexity? Okay, then what is its time complexity? | 2024-03-21 16:09:53 | 767 | Reorganize String| Google | Heap+Hashmap | Leetcode Challenge | Leetcode 767| Medium |
|
nZSXWXzn1aM | Aa Gayi Ab School And Welcome To Brothers Pages In This Video You Will See The Question Unique In This Video You Will See The Question Unique Part-2 Situated At The Top Left Corner Part-2 Situated At The Top Left Corner And Download The Bottom Right Corner Of Northern Part Of Speech And Travels And Tours And Travels Distraction Or Dash Kholo Know Why Can't You Travel With Know Why Can't You Travel With Know Why Can't You Travel With Specific And So You Can Travel Part-1 Subscribe Possible Unique Sin Robot Top Left Corner You Need To Read And Write The Thing 's Problem subscribe and subscribe subscribe the Of the last point the festival subscribe the Of the last point the festival is is this this this all possible predictions for all the sense secondary I will find out the past decreases that particular point and adding amazed at how do you do solution to the great and definitely possible for you definitely possible for you definitely possible for you Plus Plus One Comment The Conjuring R0 N0 Tak Olympic Record Calling Function On These Tourists And C Where Attraction Can Improve Your Life Will Give Me The On The Great Subscribe To Exhibition Setting To Dinner Finally Give Me The On The Great Subscribe To Exhibition Setting To Dinner Finally Give Me The On The Great Subscribe To Exhibition Setting To Dinner Finally past white navratri diet hai to aapne one column kunwar natwar singh dang ding to aapne one column kunwar natwar singh dang ding dang is digit hai 210 mein united condition me ram setting back ismail one column harisingh out of the bond and above great value is an object in the Just returning from this point to that is the Just returning from this point to that is the Just returning from this point to that is the water problem does not come to the point to point and doing part plus one class 10th hua ke ahmedabad based dak par bichh diye se subscribe give you have enrolled in kollam Used for Used for Used for using back and intermediate result re turn of the same size add top grade in his leadership quality killers will not with its in finally absolutely dad on the great and in finally absolutely dad on the great and bring water and returned and the last salute bring water and returned and the last salute cigarette and approach undhiyu Subscribe & 2019 - Simply Written On Co Unmute Calculator n And Meditative Value Of The Rupee Fall Will Impact Today's Edition After Departures From Right Hand Is Used In Addition To Return To Power & Subscribe The Amazing Waterproof See You Subscribe The Amazing Waterproof See You That That That downloads from particular point to this point I will be coming from left to stop them from the road and columns right to reach is this point tours from all parts of the year from top to bottom Many Unique Pa Many Unique Pa Many Unique Pa Possible From This Point To The Point Will Possible From This Point To The Point Will Be Taking One Arrested By Others Which You Be Taking One Arrested By Others Which You Will Not Be Knowing You Will Update You Can Read And Subscribe To Who Is The First Sale And 10 Starting Salary In This Just 1000 Know Where Possible To You Are You Will Only Be Updated On Kar Do That You Will Behave In Condition Score This Post Vacant Post Column And For All The Shamil How To Know The First Come First Will That Navneet To See The Condition When They Can Feel That Navneet To See The Condition When They Can Feel 140 140 140 Subject And Said Its Previous Subject And Said Its Previous Celebration Reachable In Case Of Previous Role Celebration Reachable In Case Of Previous Role And Previous Column Name Not Doing - - - - And Previous Column Name Not Doing - - - - Give The Value Of Karan Se At Least 108 Seervi notification other edition of life in a hua hai hua hai main finally fuel just written in the bottom right corner hai hua hai hai pehle front is code india getting upset result list up ministers and not submitted for the time complexity over this Where's Going Uber Slow Trick Where's Going Uber Slow Trick Where's Going Uber Slow Trick Butter Space Complexity Extra and A | 2024-03-20 10:55:22 | 63 | Unique Paths II | Live Coding with Explanation | Leetcode - 63 |
|
ofLNGwUFkys | hello friends so today in this video we're gonna discuss a problem from lead we're gonna discuss a problem from lead code which is a medium problem code which is a medium problem problem name is partition into minimum problem name is partition into minimum number of number of deci binary numbers so the code is very deci binary numbers so the code is very simple i'll first tell you what the simple i'll first tell you what the problem statement is telling you to do problem statement is telling you to do it states that you are given a decimal it states that you are given a decimal number in number in desi binary form or a number in deci desi binary form or a number in deci binary form binary form is a number which consists of only zero is a number which consists of only zero and one okay so as you can see any and one okay so as you can see any number which consists of zeros and ones number which consists of zeros and ones are called deci binary number now you are called deci binary number now you are given a string are given a string s that consists of a positive decimal s that consists of a positive decimal integer so you are given some integer integer so you are given some integer which is like 32 or like this number or which is like 32 or like this number or very large number very large number in a form of a string so now you have to in a form of a string so now you have to represent represent that integer into minimum number of deci that integer into minimum number of deci binary numbers so you have to represent binary numbers so you have to represent this number into the minimum number of this number into the minimum number of decimal numbers decimal numbers how much minimum number you have to use how much minimum number you have to use that's the problem that's the problem so now what you can see in this problem so now what you can see in this problem is every number can be represented by is every number can be represented by only zeros and ones only zeros and ones and if you add them then you can get and if you add them then you can get that number okay that number okay so now what you can easily understand is so now what you can easily understand is if you want to get a two here okay then if you want to get a two here okay then every number which you have any two every number which you have any two numbers will be having one one at this numbers will be having one one at this position and one will be having zeros position and one will be having zeros because when you add all of these because when you add all of these numbers numbers these two will this one will add and these two will this one will add and become two and all of these one one one become two and all of these one one one will add and give three will add and give three what you simply find here is this number what you simply find here is this number three three which is the maximum among all of these which is the maximum among all of these digits is the number of ones required digits is the number of ones required so if i have three then i should have so if i have three then i should have three numbers three numbers all having one one one okay in this as all having one one one okay in this as you can see you can see i should be having eight numbers such i should be having eight numbers such that this position should be one that this position should be one in all the numbers but in the in this in all the numbers but in the in this position position you can put only two now like two you can put only two now like two numbers to be having numbers to be having uh like one and one and other should be uh like one and one and other should be zero what i mean by this is let's assume zero what i mean by this is let's assume i have some number i have some number which is equal to okay let's change it which is equal to okay let's change it out out i have an outline yeah i have an outline yeah so let's see if i want let's see here uh so let's see if i want let's see here uh 32 32 so if for a third number what you can so if for a third number what you can easily see here is easily see here is for all the numbers on the first for all the numbers on the first position there should be one one one position there should be one one one but for the second position what you can but for the second position what you can do here is you can put do here is you can put like one number has been zero and other like one number has been zero and other two numbers having one so that the sum two numbers having one so that the sum will be 32 will be 32 okay so as you can see it means that okay so as you can see it means that three is here so it means that three is here so it means that there should be three numbers because if there should be three numbers because if i have less than three numbers i have less than three numbers then i cannot get three here because then i cannot get three here because for getting three here there should be for getting three here there should be three like there should be at least three like there should be at least three numbers three numbers so that everyone should be having one so that everyone should be having one then only i can get a three at this then only i can get a three at this point point for two i like because this number is for two i like because this number is less than less than three then for this two what i can do is three then for this two what i can do is i can i can make any two numbers one and just leave make any two numbers one and just leave out the one number which is zero out the one number which is zero maybe it is zero here again so what i maybe it is zero here again so what i can do i can make all of them zero can do i can make all of them zero so the simple technique what you can see so the simple technique what you can see here is i should be having the minimum here is i should be having the minimum number of number of numbers required is the maximum among numbers required is the maximum among all the digits all the digits because the maximum number i can get is because the maximum number i can get is like the maximum digit i can get is nine like the maximum digit i can get is nine so in maximum of nine numbers i can make so in maximum of nine numbers i can make every number because every number because if i want to make lectures 92 then what if i want to make lectures 92 then what i can do here is i can do here is i can make nine numbers all having one i can make nine numbers all having one one one one one and only two numbers i can make one one and only two numbers i can make one one one one and other them should be zero zero zero and other them should be zero zero zero so that it should be nine and they so that it should be nine and they should be two should be two i will get the point so what you can i will get the point so what you can simply do in this problem is just simply do in this problem is just iterate over iterate over all the integers or like all the all the integers or like all the characters in this string characters in this string and then find out what is the maximum and then find out what is the maximum integer integer that convert that character into integer that convert that character into integer and find out which is the maximum and find out which is the maximum integer integer and that's the number of uh numbers and that's the number of uh numbers actually you are required to form the actually you are required to form the total number of total number of uh like total number of desi binary uh like total number of desi binary numbers required to make this numbers required to make this string number i hope you understand the string number i hope you understand the logical quote for this problem if you logical quote for this problem if you have any doubts you can mention on i'll have any doubts you can mention on i'll see you next time until then keep see you next time until then keep quoting and bye | 2024-03-20 14:12:08 | 1,689 | 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers | Leetcode Medium | CODE EXPLAINER |
|
E6_eab7P_UU | hi i am shim gupta and today we are solving i am shim gupta and today we are solving some of all odd length summaries some of all odd length summaries it is a easy level problem on lead code it is a easy level problem on lead code uh uh problem is very straightforward like uh problem is very straightforward like uh they give us a vector they give us a vector i have to i have to return the sum i have to i have to return the sum of all odd length of all odd length odd length subsequence of this array odd length subsequence of this array like uh what will be the odd subsequence like uh what will be the odd subsequence let uh let uh see from this see from this explanation explanation uh one will be the subsequence four two uh one will be the subsequence four two five three five three and uh and uh and another odd length subsequence will and another odd length subsequence will be be three length a length of three three length a length of three where one four two where one four two can be a subsequence four to five can be a subsequence four to five will uh we have one of them and will uh we have one of them and two five three two five three and uh here is the last one which is the and uh here is the last one which is the length of 5 so it is also the odd length length of 5 so it is also the odd length so we have to return the sum of all or so we have to return the sum of all or odd length subsequences odd length subsequences right so right so yeah yeah so let us let's start so let us let's start okay so um okay so um [Music] [Music] for doing this question uh i will i will for doing this question uh i will i will i will be using prefix i will be using prefix prefix sum prefix sum and i will create a prefix vector where and i will create a prefix vector where i stored the sum of the running sum of i stored the sum of the running sum of the the vector vector let's create one first of all let's let's create one first of all let's declare the size declare the size of the given array of the given array and for the same size i will be creating a prefix some prefix sum array where i will be storing the running sum of the vector right so let's assign letter sign the first element of this sum will be the first element of the given array okay so right let's create a variable sum and we will store our sum of all the odd length subsequences and return this sum and at the final as a final result okay so uh okay so let's traverse through the vector and okay so okay so pre pre some some prism of prism of i i will be will be will be the will be the sum of will be the sum of the previous index plus and let's store and let's store the the sum of this array okay in the sum vector actually uh here in this step i calculated the sum of these five subsequences of length one so iterating through this i can see the sum of these five because it is a length of one so i just created a sum variable initiated with the first element and iterates iteration start with the one till the end then i will i will be having the sum of all these five subsequences right okay this is the one thing and the next thing is this prefix sum array um as you all know that what is prefix i i hope you all know but let me give you a brief about what is the prefix sum array like uh prefix summary of the uh let's let's understand from this one example like example uh i have an array uh any of values 1 comma 2 comma 3 right and if i want to create a prefix sum array for the for this a vector so what will i have to do i will create a same size of a vector as a um three three named as pre named it as a three okay so uh in this vector i will be storing one at a first index and one plus two at a second index one plus two so um so um this is uh what what will uh what what this is uh what what will uh what what will be this uh uh will be this uh uh where do i use this i will be using it where do i use this i will be using it uh for calculating the sum of the ranges uh for calculating the sum of the ranges like if i if i want to like if i if i want to uh want to have a sum of these two uh want to have a sum of these two numbers then i will directly return this numbers then i will directly return this index of this vector index of this vector it will it it has a sum of these two it will it it has a sum of these two elements so elements so i will directly return that uh this i will directly return that uh this index in our order of o of index in our order of o of one right one right of one of one okay this is a very small vector so um we don't we don't have we don't see the proper use of this prefix sum but suppose our array of a very big number so in the in that case a prefix sum array will help us so to uh to solve a bigger problem we created a prefix sum array okay so now let's after creating this okay i'm actually okay i'm actually uh it is a length uh odd length so uh i uh it is a length uh odd length so uh i started it with initialize it with two started it with initialize it with two and uh i i incremented in every iteration i increment the value of i with two so i so in this manner i will be having the odd length j j j will be started from j will be started from zero zero and the condition that i can put here uh and the condition that i can put here uh g n g n um j plus plus um j plus plus okay second loop is okay second loop is in in the second loop uh we will be in in the second loop uh we will be checking that checking that if if j equals to zero right if if j equals to zero right in that case in that case i will be directly uh i will be directly uh return i will directly sum the value of return i will directly sum the value of three of i three of i three sum of i right please sum i three sum of i right please sum i okay pretty soon okay so um otherwise if not true then i will be summing the value of i plus j my bad my bad sub 3 sum okay free sum of j minus 1 okay so let's understand why this is working like uh if i have to if i have to calculate the sum of uh some of this two these two values so how do i you you use this prefix some array to calculate the sum of two or three so what will i do i will access this element and minus minus uh the iv minus like like uh at the this this index the sum will the sum that is stored here is the sum of first index second index and third index right from our a array first index plus second index plus third index it is the sum of third index right so um so if i have to calculate the sum of these two numbers so what will i do like one plus two plus three so i will subtract i will subtract the uh the second index the index before the second index like this is the sec at the second index from this point to this point i will be having the sum of uh some of those two indexes so uh so what will i do there is an extra one here so that's why i want to in this manner i will be having the sum in this manner i will be having the sum of of uh uh 2 plus 3 right like 1 plus 2 plus 3 2 plus 3 right like 1 plus 2 plus 3 minus minus the index before the index before the second like the second like i want to i want to calculate calculate the the sum of the range range sum of the range range for uh first for uh first comma comma second index this is the range that this second index this is the range that this is the range is the range uh in which i want to uh in which i want to calculate the sum calculate the sum right right in our air in our air this is a one index one first index in this is a one index one first index in the second index so i want to calculate the second index so i want to calculate the sum of this two indexes the sum of this two indexes inclusively right so inclusively right so yeah so i want to yeah so i want to do this so for doing this do this so for doing this what will i do what will i do i will be i will be [Music] [Music] doing doing this in this manner 3 of 3 of second this in this manner 3 of 3 of second minus minus three of zero y zero uh because uh one is uh is already summed up at a second index so i want to subtract this value so that's why this uh i i'm subtracting this value okay so from this value subtracting this like 1 1 plus 2 plus 2 plus 3 minus plus 3 minus 1 1 so in this manner so in this manner what we left with what we left with 2 plus 3 and this is what i want to 2 plus 3 and this is what i want to calculate right calculate right like 2 plus 3 right so this this is how like 2 plus 3 right so this this is how it's working it's working okay so great okay so great okay okay so now uh so now uh our sum variable having the sum of our sum variable having the sum of all the odd length subsequences of the all the odd length subsequences of the vector right so now return vector right so now return return return what happening caps return i guess i guess um okay i guess this will work um okay i guess this will work let's check okay okay okay okay let's check this on the other test okay let's check this on the other test cases great okay now let's submit okay so the uh suda uh our solution get okay so the uh suda uh our solution get accepted so thank you for watching accepted so thank you for watching that's it for this video | 2024-03-21 14:43:00 | 1,588 | Leetcode : Sum of All Odd length Subarray | prefix sum |
|
JnXUZ4DN_xw | welcome to tim's leco challenge this problem is called binary search tree problem is called binary search tree iterator iterator implement the bst iterator class that implement the bst iterator class that represents an iterator over the in order represents an iterator over the in order traversal of a binary search tree now traversal of a binary search tree now what is the in order traversal of a what is the in order traversal of a binary search tree if you recall it's binary search tree if you recall it's basically basically the leftmost then the the leftmost then the node itself and then the rightmost node itself and then the rightmost that's going to give us actually the that's going to give us actually the sorted order of our bst sorted order of our bst essentially we want to form a class essentially we want to form a class that's going to that's going to kind of mimic the recursive call kind of mimic the recursive call but we have two functions here we could but we have two functions here we could return a has next which is a boolean of return a has next which is a boolean of whether or not there is another node whether or not there is another node available or the next which returns the available or the next which returns the value of this current node and then value of this current node and then moves the pointer to the right so this moves the pointer to the right so this kind of makes it seem like the best way kind of makes it seem like the best way to do this is to do this is to to append our append our node values into an array doing it in node values into an array doing it in order traversal using like a recursive order traversal using like a recursive function and then write functions for function and then write functions for has next and next and you know that has next and next and you know that would be pretty would be pretty easy but let's try something else let's easy but let's try something else let's instead try to instead try to try to simulate the recursive try to simulate the recursive stack here uh using this iterator so if stack here uh using this iterator so if we were to do this in order how would we were to do this in order how would this recursive stack look essentially we this recursive stack look essentially we would go remember in a in order would go remember in a in order traversal we go left and then this node traversal we go left and then this node and then the right node right and then the right node right well if that's the case then we would go well if that's the case then we would go left and if there's anything to the left left and if there's anything to the left again we'll go left and then we'll again we'll go left and then we'll put onto this recursive stack all the put onto this recursive stack all the lefts and the very last one when the lefts and the very last one when the where there is no left node anymore where there is no left node anymore that's the smallest value that's the smallest value right so what's the next one after that right so what's the next one after that well it's the one that's on top which well it's the one that's on top which would be like on this recursive stack would be like on this recursive stack whatever is on top of that whatever is on top of that but but we have to also make sure to add we have to also make sure to add the right node of this node onto our the right node of this node onto our stack as well stack as well because we can't just because we can't just not not uh assume that there's no more left uh assume that there's no more left there is going to be more on the right there is going to be more on the right side and to that right side there might side and to that right side there might be more on the left side again be more on the left side again so basically what we'll have to do is so basically what we'll have to do is once we pop off the once we pop off the the smallest node we'll check to see if the smallest node we'll check to see if there was a there was a there's a value to the right of this there's a value to the right of this node and there is node and there is we will add that and then we'll also add we will add that and then we'll also add everything to the left to kind of mimic everything to the left to kind of mimic that recursive call that recursive call so i'll show you what i mean so i'll show you what i mean let's just say we had let's just say we had our bsd iterator and we have this tree our bsd iterator and we have this tree nodes i'll clear up a little bit what we'll do is we're gonna have a stack here and this is gonna kind of simulate the recursion i'll be empty at first and if this is in order we're gonna go left left left left as long as there's a left one right so we'll have just mimic that we'll say cur current node is equal to the root while there's a curve we're going to add to our stack this this uh tree node and then we're going to go to the left say left and that at the very top of the stack should be the smallest number so here it's say seven then we go here and that'll be three and then that ends our uh current recursion right now what do we do when we go next well we clearly we have to pop off whatever is on our stack right so make sure that there's a stack to begin with if not self.stacked then we just return um i don't know we turn none i guess otherwise we're going to pop off whatever's on ourselves but before we return this value but before we return this value we want to make sure to add on to our we want to make sure to add on to our stack here stack here okay okay whatever this is here there could be some values to the right and because think about if there's and because think about if there's something to the right of this it would something to the right of this it would be 4 or b5 or v6 and if that was the be 4 or b5 or v6 and if that was the case that's not on our stack yet so we case that's not on our stack yet so we have to add that but it's not just that have to add that but it's not just that we also need to add everything to the we also need to add everything to the left as well to make sure that the next left as well to make sure that the next one is indeed the next number that's one is indeed the next number that's going to be going to be greater than this number so greater than this number so what i'll do is let's just have current what i'll do is let's just have current pointer pointing at the candidate we'll pointer pointing at the candidate we'll say if there's occur dot right well say if there's occur dot right well uh uh well let's make curry equal to kurt all well let's make curry equal to kurt all right right otherwise if there's not then curve will otherwise if there's not then curve will sequel none sequel none and we're going to mimic the same thing and we're going to mimic the same thing here we'll say here we'll say uh while cur uh while cur just add add it and then go all the way just add add it and then go all the way left again left again and the very top one should be the next and the very top one should be the next number that's where this has next all number that's where this has next all this really is is whether our stack is this really is is whether our stack is empty or not the stack shouldn't be empty or not the stack shouldn't be empty if there's more nodes coming down empty if there's more nodes coming down the pipeline so what's the return the pipeline so what's the return self.stack whether that's equal to an self.stack whether that's equal to an empty list or not all right so let's make sure this works here and there we go so this is just a old n and there we go so this is just a old n time complexity time complexity and because of our stack i suppose it's and because of our stack i suppose it's also all then space complexity but uh but yeah i i kind of like this problem because um it kind of simulates the recursive uh stack if you were to do this recursively and kind of just gives you a nice idea of like how it looks like uh you can certainly just put it into an array and you know return the index numbers like that but uh what's the front of that right all right thanks for watching my channel | 2024-03-21 14:07:16 | 173 | Leetcode - Binary Search Tree Iterator (Python) |
|
qDtzkSaHaI4 | hello friends so today we are going to discuss another lead code problem discuss another lead code problem the problem is uni valued binary tree the problem is uni valued binary tree so what is the problem description so we so what is the problem description so we are given a binary are given a binary tree and we have to check whether the tree and we have to check whether the tree is uni value so tree is uni value so what does it mean univolu means what so what does it mean univolu means what so if if every node in the tree has the same every node in the tree has the same value and what we have to written is we value and what we have to written is we have to return the boolean value have to return the boolean value so it can be either true or false so so it can be either true or false so let's take an example one let's take an example one so here if we see from the top and if we so here if we see from the top and if we go go down the bottom from at the left side down the bottom from at the left side and and similarly at the right side so we can similarly at the right side so we can see see what are the value of the root node that what are the value of the root node that is the one and we are having is the one and we are having its children's and its grandchildren all its children's and its grandchildren all are having the same value are having the same value so that's why for the example one so that's why for the example one the output is true now let's see the output is true now let's see the another example 2 so here if we can the another example 2 so here if we can see see the root value is 2 then its children the root value is 2 then its children value left and right is again 2 value left and right is again 2 but if we see the left children and left but if we see the left children and left of of left children so it has the value of 5 left children so it has the value of 5 and that's why and that's why it is returning as a false so it is returning as a false so it's a pretty straightforward problem it's a pretty straightforward problem so let's get into the code part so here so let's get into the code part so here we are given a function we are given a function is unique value and which accepts is unique value and which accepts a three node that is a root node as a a three node that is a root node as a parameter parameter so what we are doing here so let's say so what we are doing here so let's say if our tree is if our tree is empty at the initial state so we just empty at the initial state so we just have to simply return have to simply return true because empty tree has a true because empty tree has a nothing so that's why it is a true now nothing so that's why it is a true now what we are doing is we have created a what we are doing is we have created a pre-order function over here pre-order function over here and it has two parameters one is the and it has two parameters one is the three node and another its current value three node and another its current value so so what it does is so it's basically a what it does is so it's basically a simple simple left traversal and a right traversal of left traversal and a right traversal of the tree the tree so inside this function what we are so inside this function what we are doing is we are again doing the same doing is we are again doing the same check check if the tree node value or if the tree node value or if the root is none then we are simply if the root is none then we are simply returning true returning true and let's say what so initially if we and let's say what so initially if we see over here for the example see over here for the example if you can consider any of the example if you can consider any of the example let's say if you consider the example let's say if you consider the example one over here one over here so initially this prime that is previous so initially this prime that is previous value that is a one value that is a one so we are checking over here with so we are checking over here with so whether this root value is equal to so whether this root value is equal to equal to previous so here equal to previous so here the root is one and again the previous the root is one and again the previous value is also one so value is also one so this condition doesn't get satisfied so this condition doesn't get satisfied so here it goes here it goes to this block so here what we are doing to this block so here what we are doing is we are simply is we are simply doing the left order traversal and we doing the left order traversal and we are doing are doing the right order traversal and we are the right order traversal and we are making sure that whether we are getting making sure that whether we are getting true true value if both the sides are true true value if both the sides are true true it means we are finding the similar it means we are finding the similar value value on the left of the tree and similar on the left of the tree and similar value or the same value value or the same value on the right side of the tree in that on the right side of the tree in that case only it will return case only it will return the true and finally we will get the the true and finally we will get the output as a true over here output as a true over here okay and in case if it doesn't get okay and in case if it doesn't get matched matched so either of the tree will return the so either of the tree will return the false at this line false at this line so let's say for example at the right so let's say for example at the right side side in example 2 if we get the in example 2 if we get the true as a response over here but in true as a response over here but in terms of if we see the left terms of if we see the left child of child so in that case or we can child of child so in that case or we can say grandchild say grandchild so here 2 will not get so here 2 will not get matched with the 5 and that's why it matched with the 5 and that's why it will return the false so will return the false so false from the left side that is a false false from the left side that is a false and and true from the right side but again it is true from the right side but again it is a condition a condition and conditional operator so it will not and conditional operator so it will not go to execute the right part because the go to execute the right part because the first first condition is false so implicitly it will condition is false so implicitly it will return the false as an return the false as an output so let me quickly run this output so let me quickly run this and let's see the output okay so here the solution is super fast and the runtime is 0 millisecond which is a faster than 100 java submission and let's see the test case coverage so we can see it has covered all the 72 test cases over here now let's come to the time complexity and the space complexity of this algorithm so we are not initializing anything new or any kind of data structure so time complexity is uh sorry the space complexity is big of 1 and in terms of the time complexity so we are going down the bottom of the tree so that is a time complexity is big of height of the tree so we can consider it as a big of h or big o of n whatever it is suitable so i have posted the solution on github and i have uploaded the link in the description section below so if you like this video please do like and share this video and comment this video and stay tuned for the next one thank | 2024-03-25 14:03:46 | 965 | 965. Univalued Binary Tree LeetCode Tree Based Problem |
|
ZLysYrrEzV8 | hey everyone welcome back and let's solve our more lead code problem today solve our more lead code problem today so today we're going to solve lead code so today we're going to solve lead code uh 1751 which is going to be the maximum uh 1751 which is going to be the maximum number of events that can be attended number of events that can be attended too uh so we're given an array of events too uh so we're given an array of events where each event consists of three value where each event consists of three value or three values which is the start date or three values which is the start date the end day and the value and uh the the end day and the value and uh the event stats at the start date so let's event stats at the start date so let's take this example uh so it starts on day take this example uh so it starts on day one ends on day two and it has a value one ends on day two and it has a value or we get a profit of four by attending or we get a profit of four by attending this uh similarly the other event stats this uh similarly the other event stats on this day ends on this day and we get on this day ends on this day and we get a profit of this so we have an even list a profit of this so we have an even list like this and the K is the upper bound like this and the K is the upper bound on the number of events which we can on the number of events which we can attend so we have to attend uh two attend so we have to attend uh two events we cannot do more than that and events we cannot do more than that and we want to maximize the total uh the we want to maximize the total uh the total value of the profit which we can total value of the profit which we can do by attending this event so return the do by attending this event so return the maximum some of the values that you can maximum some of the values that you can receive by attending demons now whenever receive by attending demons now whenever we have something like maximize or we have something like maximize or minimize then just just make sure that minimize then just just make sure that it's it's something which is probably it's it's something which is probably going to involve dynamic programming and going to involve dynamic programming and for this particular instance it also we for this particular instance it also we also see that uh it involves intervals also see that uh it involves intervals kind of a thing so when you get kind of a thing so when you get something like intervals uh think about something like intervals uh think about sorting when you see something like sorting when you see something like maximizing on minimizing think of GB is maximizing on minimizing think of GB is probably going to be one of those so probably going to be one of those so it's this problem also is involves it's this problem also is involves sorting also and DP as well so similarly sorting also and DP as well so similarly let's have a look at one event example let's have a look at one event example just to understand uh this better so we just to understand uh this better so we have these events and the value of K is have these events and the value of K is 2. so how many events can we attend so 2. so how many events can we attend so there's one more condition which is there's one more condition which is given that if you're attending given that if you're attending particular events you can't really uh particular events you can't really uh start an event which ends on the same start an event which ends on the same suppose if you attend this event uh you suppose if you attend this event uh you can't really uh go ahead and attend this can't really uh go ahead and attend this because this is going to end on day because this is going to end on day three and the next next event should be three and the next next event should be definitely be more than this okay so for definitely be more than this okay so for to you to be able to attend this event to you to be able to attend this event the start date has to be greater than or the start date has to be greater than or strictly more than the end date for this strictly more than the end date for this event so it has to be at least four for event so it has to be at least four for you to be able to attend this so if we you to be able to attend this so if we can try all possible different can try all possible different combinations but uh this is the answer combinations but uh this is the answer or this is the event which is gonna do or this is the event which is gonna do the one which will be attending we can't the one which will be attending we can't really take this also because it ends on really take this also because it ends on day two this starts on day two so yeah day two this starts on day two so yeah it should not be overlapping okay it it should not be overlapping okay it should be a strictly increasing uh for should be a strictly increasing uh for you to be able to attend that so that's you to be able to attend that so that's the answer for this problem uh now let's the answer for this problem uh now let's have a look at the constraint okay so uh have a look at the constraint okay so uh we see that uh we're given a constraint we see that uh we're given a constraint in this manner okay K times events that in this manner okay K times events that length has to be less than this value length has to be less than this value which is usually five times ten to the which is usually five times ten to the power five or ten to the power 6 in this power five or ten to the power 6 in this case now this gives us some idea that case now this gives us some idea that our state has to be uh comprising the our state has to be uh comprising the value of K and also the events total value of K and also the events total length or the indices so these are some length or the indices so these are some essential uh things which we can see essential uh things which we can see from here and the approach we will be from here and the approach we will be taking for this is going to be the taking for this is going to be the knapsack zero one kind for DP uh we'll knapsack zero one kind for DP uh we'll also need to store these intervals also need to store these intervals because uh we will be starting out from because uh we will be starting out from the first one and then we can just move the first one and then we can just move on based on the start time we're going on based on the start time we're going to start this entire events list and to start this entire events list and then we're gonna go ahead perform binary then we're gonna go ahead perform binary search to find the next possible uh search to find the next possible uh interval of the state which we can interval of the state which we can transition transition to and then it transition transition to and then it will try to maximize the total uh profit will try to maximize the total uh profit which we can get by attending these which we can get by attending these events so let's hit the drawing board events so let's hit the drawing board and see what's the approach which we'll and see what's the approach which we'll be taking for this problem [Music] thank you all right guys so uh we have the given list and the first step over here would be to sort this given list by the starting value so what I mean is the start time you'll be sorting this uh given list of the events and once that is done we will be using this for State transition and also for performing the binary search so that we can find the next optimal state which we want to transition to now the state for this uh recursive dp01 Maps app kind of a problem will consist of two values one would be the index and the next one would be the value of K currently at this age so K is going to reduce by one by one so it's three it'll go to two one and then we'll stop once it reaches uh zero so these are the two values which will consist of the state and we will start off with the first element itself so we'll start off with uh zero comma the value of K which is three and we're going to move ahead from this value now uh at each index or at for each element we have two options either we take that or we don't so let's suppose we can take two possible routes from here okay so let's suppose we take this value so we're going to add the value okay are we going to take the value for this even which is a one in this case we're going to take one over here and then we're gonna move on to the next state now uh notice that for finding a next stage we're giving a condition that the start value of that state has to be uh at least bigger or it has to be strictly more than the end value for this particular event okay so in this case suppose it's one in this case now if I want to move on to some other uh event it has to be greater than one so at least two should be the start value of the next event which I want to attend or which I want to take so we're gonna do a binary search on this segment okay the one starting from here reason being it's sorted and the next reason is it will help us bring down search to log of N and yeah that's the core concept over here in this question so we'll have to do a binary search to find such value which is strictly more than the end value of the current event which I'm attending so we see that it's still only in this case Okay so we're gonna move on to that particular uh event and now the state here in this case would be one which will be the index now of your own and game will go down by one so it will be two in this case it's okay so we're at the same similarly if we didn't choose to move uh to to uh take this event we can just move ahead we can just increment I and we can just keep the state same as before right now suppose we're on this state uh I can take this event so I'll just take that and I'll add two which is the value we have over here the value over here and then I can just move on to one more uh state which is two comma one and Y2 because it has this three is strictly increasing then the N value which we have over here of two right so we can move to the set similarly I can skip this so in that case I can just move on to two comma two and that's how State transition works for this particular case okay I'm at zero one two I'm at three comma 3 automatically now I need to move on to the next particular event and I can definitely do that so with a value of three I move on to 3 comma zero but I have to stop over here because K is now zero and we're going to stop our recursion at that point itself so that's one value which we got over here that's one two and three so this is one of the uh possible answers but we're trying to maximize that so that's why we use the DP approach over here now coming on to this brand suppose here also we have two options either we take or we don't so I'm just gonna skip some of the states which uh we won't really get the optimal answer on and I'm just gonna go with the most optimal uh possible uh sequence okay so from this um I'm at okay so now I'm at one so this particular one uh I want to take this value so I'm just going to take this value I'm just gonna take two and I'm gonna move on to the next step which is two comma two and from this 2 comma 2 I can move on again by taking this value to I will take three and now I will move on from this to this one okay so for sorry I'll rather move from this to the next one so now I can move on to the state for uh comma one or rather sorry it will be uh it will be three comma one which is that state and I'm again gonna take that value which is four and I cannot really go any further from here because uh that's basically the end of the list and we're just gonna return from that recursive call now notice that we are actually able to uh get the most optimal answer in this case so if you see this Branch the total was one plus two plus three that's six uh however on this particular uh case Okay uh now this will be zero now if I go down this path uh my answer would be uh zero plus two plus three plus four and that comes to uh nine right so that is the most optimal uh answer for this case and our uh recursive function is just gonna maximize this value and yeah we're gonna just return nine as the final answer for this uh problem so yeah we're gonna use a recursive function now notice that these states are repetitive okay so we have to come 2 and we have state overlapping sub problems as we can see so whenever you have overlapping sub problems it means that you're going to use dynamic programming so we're going to use memoization and we're going to Cache the values for these sub problems and that will essentially help us speed up the performance of our uh this this recursive calls right so that's the kind of solution which we'll be implementing now if I just talk about the uh Diamond space complexity for this problem so uh notice that uh if you talk about the time complexity so we're doing it in a recursive fashion okay and then the first thing which we're doing right away is uh we're solving this uh entire error right so it takes o of n log of n complexity of just saw this and we're using a recursive function which is called for each event and each value of K now the number of recursive calls depends on the number of events and also the value of K and in the worst case each event is considered for each value of K resulting in total of n times K uh recursive calls and we have the bisect uh function as well but just call within the solves to find the next event and that starts after the current event ends and that will have an O of a log of n complexity for the binary search so the overall time complexity uh is the sum of all these values so that is a big go of n log n plus n times K Times log of n so that is the overall time complexity uh talking about the space complexity the even list is stored as an instance variable uh you'll see in that in the code and so it does not really contribute to the space complexity because you're getting that as one of the inputs uh the space complexity of the recursive function it's determined by the maximum recursion depth right and which is K so each recursive call consumes an additional space on the call stack therefore the space complexity would be a big O of K for the recursion depth and uh yeah we're also uh storing uh for basically caching those values but then that's that's going to save us some value so yeah we can say that uh the space complexity is going to be o of K for the space and for time we have already calculated that this is the time complexity so yeah that's about it the solution and let's now have a look at the code for the problem and that will help you better understand the entire implementation all right guys so now let's have a look at the code from the problem so the first thing is I'll be uh using or I'll be putting things in the init for this just to keep the recursive uh function uh easier to read so we have the events over here now coming to the max value uh I'm just gonna solve these events okay and by default it would be sorting it by the first value which is the start time and so it works for us else we would have used a key with some sort of a Lambda to be able to do that now I'm just going to put this events in the instance variable and then we're just gonna return our recursive function which is going to be solved starting would be zero comma K the first index and we have the entire K with us now let's go move to the core function which is going to be the solve and over here let's let's put the base cases first so if I is greater than length of uh events then we'll be returning uh zero and if K is also uh less than or equal to zero we can't really move forward so we're just going to return 0 in this case so these are the base conditions now uh we have two options okay so B uh we have two options uh either uh we can take events at I or not okay so these are the two options uh so let's see how we write the code for that so first we're gonna take uh s e and B which is going to start and then the value for the current event or the index we're one so these are the three values and then we're just gonna find the possible State or the index we can move to so we're just going to use the internal bisect uh method which python provides uh in another another case you can just uh use your own uh yeah implementation of the binary search now what this basically does it it will go over this eye table or this list in this case and it will find the index where I can put on this value now we're just comparing the start times remember and it has to be strictly more than the current end time so that's why we are using e plus one we don't use e because uh that would just give us an overlapping value we want to find for E plus one because we want it to be higher than the current end time so that doesn't catch and just just take care of that otherwise it will give you the wrong answer so that is one thing and then we will just return the maximum okay so as the question says we want to maximize the value so we have two options we take this uh particular event so in that case we're just going to add the value and then we're going to move ahead and solve it for J and K is going to be reduced because we are have attended an event in the other case we can just move ahead because we're not using this particular uh event okay so we're just gonna move in to the next index okay we're just we're not going to go to J because since we're not attending this we can safely move ahead to the next particular index as well so it's going to be I plus 1 comma K in this case k won't get reduced and that's about it so that's the entire implementation for this um problem let's try to run this it should work okay it works and now one more catch we'll have to uh kind of uh be able to Cache this okay so you can either use a cache okay so you can use a self.cache uh which is going to be a dictionary uh where you can use ink as the states and then you can just check it in the solve and you just return if the value is already there in the cache okay another easier way in Python is just use the cache decorator that's going to Cache things for you that's it but yeah you can always go ahead and use the cache if you want and that should work and now let's try to submit this it should work and perfect it works so yeah we're done with this question and yeah that was it thank you so much for making it this much through the video in case you have any questions queries or any problems with this or any suggestions please leave that down in the comments below and I'm just gonna meet you guys very soon with some other video and also please share this video like the video and also subscribe to the channel it's going to help us a lot and we're gonna come back with a lot of content around system design object oriented programming and also more lethal problems until then goodbye and have a great day [Music] | 2024-03-22 11:50:39 | 1,751 | Leetcode 1751 | Events Attended | Hard DP | Python | Daily Challenge |
|
zvBxnudTZmw | hey hey everybody this is Larry this is day 20th or gen 20th I'm trying to do day 20th or gen 20th I'm trying to do more uh basically we've done the pro or more uh basically we've done the pro or I've done the prom that the daily uh I've done the prom that the daily uh prom is and I'm trying to get my money's prom is and I'm trying to get my money's worth by picking one random PR I haven't worth by picking one random PR I haven't done before and today's random PR is 998 done before and today's random PR is 998 maximum binary tree 2 it's a medium prom maximum binary tree 2 it's a medium prom uh and apparently has a lot of downloads uh and apparently has a lot of downloads so we'll see how this goes uh a maximum so we'll see how this goes uh a maximum tree is a tree where every no has a tree is a tree where every no has a value greater than any other node in the value greater than any other node in the sub isn't that just a heap that's a he I sub isn't that just a heap that's a he I mean I guess a heap is a it's a is it mean I guess a heap is a it's a is it complete or I forget the term for it but complete or I forget the term for it but a he it does fit this description though a he it does fit this description though it may not be the general version of it may not be the general version of this but any case uh you're given the this but any case uh you're given the the root of a maximum binary TR and the root of a maximum binary TR and integer value just as the previous just integer value just as the previous just a previous form should I do a previous a previous form should I do a previous one one first all right I guess I should do the first all right I guess I should do the previous one first I don't know all right let's just do this one first and then I'll make a second video doing this one maybe all right let's just do this one first uh so if you're watching this you may be confused about the title bit and how I get here but makes sense right so okay Maxim create a no value is Maxim okay yeah yeah yeah recurs build this upgrade okay so just repeatedly get the max right so how what is the idea well what is the tree what oh so basically if you're given but see that's the part that I don't think oh uh oh Subway prefix okay I see I see I didn't really read this correctly uh all the numbers are unique all right I mean this this is pretty straightforward what does this remind me of I mean I I guess this is just like um like I mean it's not quite the same but it is the the same idea with like sorting structures right um but yeah it's not that bad um so the way that we can think about it uh so we'll just have a construction thing and then here we want the left right um and yeah yeah left right what is that it yeah I guess that's it right and basically what this does is recursively node yeah right and here basically we node yeah right and here basically we have and I think you can actually have and I think you can actually um I I'll talk about the complexity um I I'll talk about the complexity later but I hope that it is not n well later but I hope that it is not n well okay it is going to be n square but n okay it is going to be n square but n square is fast enough is this not n square is fast enough is this not n Square no that's I don't know sorry I'm Square no that's I don't know sorry I'm jumping around a little bit but yeah jumping around a little bit but yeah this is going to be n Square in the this is going to be n Square in the worst case but you can actually do it in worst case but you can actually do it in much faster if you're really slick about much faster if you're really slick about it um and you can do this in you can do this in linear time but that's a ridiculous solution but in any case okay but yeah and I'll explain why in a little bit but or how in a little bit but yeah so then here we have the max value is equal to just Max from nums sub left to right um I think right but plus one to make it inclusive cuz I like it to be inclusive here I like my function to be inclusive um I don't know it it doesn't have to be it's just that that's the way I like it right so then um yeah and then now we have um yeah and then now we have nums index of this number we probably nums index of this number we probably could actually do this like much cleaner could actually do this like much cleaner just add some lazy I'm just lazy uh okay just add some lazy I'm just lazy uh okay fine uh fine uh no yeah okay let's just do it in a non no yeah okay let's just do it in a non La way l so okay so max is equal to num La way l so okay so max is equal to num sub left um max index is equal left I sub left um max index is equal left I guess Max index is fine right and then guess Max index is fine right and then now we have for I and range from left now we have for I and range from left plus one to right + one because we want plus one to right + one because we want to right inclusive uh if num sub I is to right inclusive uh if num sub I is greater than num sub Max index greater than num sub Max index then maximum index is equal I something then maximum index is equal I something like that right so now we have the like that right so now we have the maximum index then now we can maximum index then now we can construct left Max index minus one so construct left Max index minus one so this is going to be the left um so this this is going to be the left um so this is the left note oh that actually over is the left note oh that actually over Shadows the variable so left node right Shadows the variable so left node right right node is equal to construct right right node is equal to construct right uh um max index plus one right and um uh um max index plus one right and um and yeah and then now we can return a and yeah and then now we can return a new node a tree node where the value is new node a tree node where the value is equal to the max so num sub Max index uh equal to the max so num sub Max index uh left node right node right and of course left node right node right and of course we actually have to change the base case we actually have to change the base case scenario a little bit which is that if scenario a little bit which is that if left is greater than right then we left is greater than right then we return none I think that should be good return none I think that should be good right and then now we just have to right and then now we just have to return return construct um zero and then n right or n construct um zero and then n right or n minus one and it will give us AIT hopefully this is fast enough and it looks Gucci and we're good but yeah uh so a couple things I mean I did this pretty quickly but hopefully everything kind of follows um but we just recursively look at the sub away which is what they tell you the prefix and the subx um and we have to get the index for the maximum Index right um so what's the complexity here well it turns out that if you have like a link list thing kind of similar to this and the max value is the last item say then then um then basically every node is going to only take out one node and so then this uh range thing is going to make it n Square because you the first time is going to take n operation then n minus one operation n minus 2 dot dot dot all the way to one and then of course that's going to be n Square over two some is and which is n square right so this is going to be n square but you can actually reduce this by using some sort of rmq solution RQ thing stands for R range I guess range Min Curry is the common one but obviously this in this problem you can convert it to Max and and because the the um the list of numbers is uh con or you know it's static um you can pre-process it to to answer queries um you may even be a would do better than that to be honest but I but like with rmq directly but in any case even if you just do that you're able to do this in all of one time and therefore you're able to um you know like instead of having a loop you're able to get the maximum index in all one so that means that every construction of node is going to take all of one so that's going to make it linear time linear space that's pretty much it um I am going to um if you're looking for this video I don't of your um since this is R anyway I will have a different video right after this uh but yeah but that's all I have for this one hopefully it didn't go too fast let me know what you think uh yeah stay good stay healthy to your mental health I'll see you in the next video and I'll see you later | 2024-03-20 14:49:55 | 654 | 654. Maximum Binary Tree (Leetcode Medium) |
|
7hEPPNfj7PM | hey guys today we're going to talk about rico rico 760. 760. you know since i didn't pay the premium you know since i didn't pay the premium and and so i cannot access it but i found a so i cannot access it but i found a tweak tweak they you know they you know sim crush in lincol sim crush in lincol you can if you don't know his website he you can if you don't know his website he use it too you know they give you access use it too you know they give you access to the premium problems in legal to the premium problems in legal and and basically the question is find anagram basically the question is find anagram mappings mappings so what's an anagram so what's an anagram so basic anagram is so basic anagram is a word of face a word of face phrase formed by rearranging the letters phrase formed by rearranging the letters of a different word or face of a different word or face so yeah this is definition and let's look at if i have examples so see like fried or fired listen or slam silent you know so all right so let's go to the link right here and let's look at the approach so we explain what's the anagram and then what's given a two array a and b right here well a and b and then where b is energy of a and what i want to get is return an index array representing what's the position from a to b so look at the example right here so if a have elements 12 28 46 3250 b is this arranged range different index so what i want to return is okay where is 12 and b it's an index one so we'll put one where is 28 in b in x four so we put index four right here and then so on and so on so that's what we're gonna get so how can we approach this problem it's so first so first we create a we create a array p that will return our result okay so a okay okay and and what we need okay we what we can do is what we need okay we what we can do is we can use we can use list list because the list they have a index of because the list they have a index of method which we will need method which we will need for when we get for when we get a index for a particular element a index for a particular element so when you list this so when you list this type image type image we call it we call it list of b all right all right and then and then right now what do we do we right now what do we do we add element in b add element in b to list b all right all right and next we look to the so if we so if we check so basically check so basically so at every index we want to set it to this b dot get the particular element a so basically the particular element a so basically just like that just like that all right so and then return p so yeah it should be there you know yeah accepted all right accept this so run time should time time complexities o n complexities o n but the space is o and two because we but the space is o and two because we play a lisp all right thank you guys for the video if you like this video if it helps you help you um the journey of inner proof prepping like the video subscribe to the channel share to your friends share it to the freshmen in the school study computer science all right i'm gonna call until i get to google facebook | 2024-03-21 15:56:48 | 760 | Leet Code 760 Find Anagram Mappings |
|
Y2F8EGP3OA4 | hey everyone welcome back today we are going to solve problem number 1091 going to solve problem number 1091 shortest path in binary Matrix first we shortest path in binary Matrix first we will see the expansion of the problem will see the expansion of the problem statement then the logic and the code statement then the logic and the code now let's dive into the solution now let's dive into the solution so here I have taken the second example so here I have taken the second example from the lake website from the lake website so here we are given a binary Matrix so here we are given a binary Matrix which consists of 0 1 1 and here 0 which consists of 0 1 1 and here 0 represents a path and one represents a represents a path and one represents a block right one is like an obstacle block right one is like an obstacle right right and we need to find a path from top left and we need to find a path from top left corner to the bottom right corner and we corner to the bottom right corner and we need to check whether we have a clear need to check whether we have a clear path or not path or not so a clear path should be connected by so a clear path should be connected by zeros right so in this case it's all zeros right so in this case it's all connected with zeros connected with zeros so which means there is a path exist so which means there is a path exist and if there is no path exist we need to and if there is no path exist we need to return negative one right return negative one right so we need to start from top left cell so we need to start from top left cell and we can visit the adjacent cells in and we can visit the adjacent cells in eight directions eight directions so the eight directions are something so the eight directions are something like like this right so these are my eight directions and I'm going to solve this problem using BFS approach so initially I will make the first the top left corner cell as 1 which means I have visited that cell right and I will store the row and column of that particular cell in a queue so here 0 and 0 represents the row and column of the top left corner cell right and I will be initializing it with 1. so the one represents there was a path here since there was 0 which means that is one path so now we need to start visiting the address and cells from this particular cell so since these two cells are blocked we don't have to visit them we only visit when there is a 0 exist when there is a path so initially we are going to start from 0 and 0 right that is 0 throw and zeroth column cell and the distance of this particular cell is 1 that we initialized here so from this cell we are going to visit the adjacent cell that is 0 and 1. that is 0 through and First Column is zero since it is 0 we will make this as 1 which means we have visited this cell and I will append that particular cells rho and column and I will add the distance as well I will use the previously seen distance that is 1 and I will increase it by 1 so I am going to get 2 here so far we have covered a distance of 2 right I will append that particular cell row and column indices and the distance covered so far in the queue so I will run this Loop until I finish all my values in my queue so I have seen these values in the queue now I need to see this value so now we are going to start from 0 through and this First Column cell so our I will be 0 and J will be 1 and distance will be 2. so this is nothing but the zeroth row and First Column indices right that we appended in the queue so we will use Q to visit each and every adjacent cell right so in this case we have zero throw and First Column and the distance is 2. so we are going to visit the next adjacent cells from this cell right we need to visit all eight directions so here there are blocks since there are once we don't have to visit them we only care about these two cells right since that are the clear paths here so now I will visit this particular cell right which is nothing but 0 through and second column and the distance is 3. the reason why it is 3 is the previously seen distance is 2 the distance from this particular cell is 2 so we will add one so it becomes 3 right so we will append this one in the queue so there will be 0 2 and 3. then I will make this particular cell as 1. which means I have visited that particular set then from this cell I can visit this particular cell I can visit in eight directions so I can visit this particular cell as well so this particular cells rows 1 and column is 2 and the distance is 3 again from this cell the distance is 2 and I will increase it by 1 which will be 3 then I will append this to my queue so here we will be getting 1 2 and 3 then I will make this cell as 1. so now I have visited all the clear paths from this cell right I cannot visit any more cells from this side so I will return to the queue I will pick the next set of values so I will pick 0 2 and 3. so I will be 0 J will be 2 the distance is 3 right so which is nothing but 0 through second column so we will be here now so from this one I cannot visit any other clear path sorry there are no zeros adjacent to this cell so we don't have to visit any other cell so we will pick the next set of values from the queue which is nothing but 1 2 and distance is 3. so first row and second column which is nothing but this particular cell and from this cell I can visit this particular path that is the bottom right path so the row will be 2 and the column will be 2 so and the distance will be 4. from this cell the distance is 3 and I will increase it by 1 so it will be 4 and I will append this to the queue right so there will be 2 2 and 4. then I will make this cell as 1. since there are no any other paths we don't have to visit any other cells then we return to the queue and pick the rows and columns 2 and 2 and the distance 4 from the queue so whenever I pick values from the queue I will check whether I have reached the bottom right or not I will use this row and column indices to check whether I have reached this particular bottom right corner or not since I have reached now I will just return the distance 4 that is the shortest path in my binary Matrix right that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so here n represents the length of the grid so initially I will check if the top left and bottom right Corners are one or not if it is one which means they are already blocked so there is no path exist so I will just directly return negative 1 right then I will be creating a queue where I will initialize with the row 0 through and 0th column indices and with a distance of 1 and I will make the 0 through the top left corner value as 1 which means I have visited that cell right so here I am writing a for row where I will pick each and every values from the queue so the rows and indices are I and J and the distance of that from that particular cell is D then I am checking whether I reached the bottom right corner or not if I have reached the bottom right corner I will just return the distance d right then I'm creating the eight directions here then I will start visiting all eight directions from the currently picked cell from the queue and if it is 0 I will make that particular cell as 1. then I will append that particular cell to the queue and I will increase the Distance by one for that particular cell right and if there is no clear path is exist I will be returning negative 1 as my answer right that's how the code is now we will run as you guys see it's pretty much as you guys see it's pretty much efficient thank you guys for watching efficient thank you guys for watching this video please like share and this video please like share and subscribe this will motivate me to subscribe this will motivate me to upload more videos in future and also upload more videos in future and also check out my previous videos keep check out my previous videos keep supporting happy learning cheers guys | 2024-03-25 17:10:26 | 1,091 | Shortest Path in Binary Matrix - Leetcode 1091 - Python |
|
h22FJe_iHsk | See in this video we are going to do question let code 930 binary sub ares with some let code 930 binary sub ares with some live now binary are i.e live now binary are i.e one iragi of zero and one and one wait goal will be given to one iragi of zero and one and one wait goal will be given to you d return d number of non empty sub you d return d number of non empty sub is with some goal aisi kitni is with some goal aisi kitni is with some goal aisi kitni whose sum is tu hai sabar i.e. the consecutive numbers are ok so as given here what is the output let's see the expression this is my what is it and see here their sum is two ok and All are two, okay, the sum of this morning All are two, okay, the sum of this morning All are two, okay, the sum of this morning is also two and the sum of this sub error is also is also two and the sum of this sub error is also two, okay, next example, what is two, okay, next example, what is one, it is binary, okay, there is one, it is binary, okay, there is no problem, all are zero, what is round also, if it is no problem, all are zero, what is round also, if it is zero then zero then zero then Hey, you are in the form round zero, ok, they must have made all the combinations, how much is the output, 15 is ok, one, two, three, ok, five, ok, then By doing this, 15 will be made. By doing this, 15 will be made. By doing this, 15 will be made. Okay, any number of combinations can be made. Okay, any number of combinations can be made. Well, how can we approach the Well, how can we approach the problem? Now see, when I was problem? Now see, when I was solving lead code 560 in this playlist, solving lead code 560 in this playlist, I had told you that when the I had told you that when the restrictions become strict then restrictions become strict then How do we solve the questions? Okay, How do we solve the questions? Okay, so we will adopt the same approach in this question also. so we will adopt the same approach in this question also. Okay, let's start, Okay, let's start, take mother, this is my pass, one and the goal is take mother, this is my pass, one and the goal is two, okay, so what do we take out, two, okay, so what do we take out, we take one mother, prefix. we take one mother, prefix. we take one mother, prefix. out our okay 1 1 2 and 3 obviously zero started we have our okay and like lead code 560 we had approached it in exactly similar manner we will approach it what we have to do is to Two Two Two are fine or in other words we have to find are fine or in other words we have to find which sub are and are happening with some, which sub are and are happening with some, as you will see all these are as you will see all these are different and are happening here, similarly different and are happening here, similarly this one is morning and are happening with this one is morning and are happening with some. some. some. some tu and this one savere and ho rahi hai with some tu ok so from this I thought and and ho rahi hai with some tu achha so you can prefix it with sum Now you will see, mother, at this moment I am here, okay, I have to bring out how many beautiful ars are there which are happening on this one, okay, then the crossing prefix is this, okay, so you will see All or whatever is All or whatever is All or whatever is written here, I round three minus, written here, I round three minus, what am I saying, three minus round or what am I saying, three minus round or prefix sum, I round minus, that is, prefix sum, I round minus, that is, one if one has already been prefixed, one if one has already been prefixed, if one has already been prefixed, then we if one has already been prefixed, then we See how many times it has come and how many times it has come here, See how many times it has come and how many times it has come here, like it has come here twice, like it has come here twice, then our result answer will be then our result answer will be implemented twice. Okay, if you implemented twice. Okay, if you pay attention, if you have not understood pay attention, if you have not understood why we are doing this. why we are doing this. why we are doing this. question, look at it. Okay, I have gone into depth in the question. Okay, if I tell you the same thing again and again, I will go crazy. Okay, so this is a similar question. Let's start with lead code 560. Let's take a result, Let's take a result, Let's take a result, wait, okay, which we will make beautiful in the end and wait, okay, which we will make beautiful in the end and return it. Okay, now see return it. Okay, now see what is written here, I told what is written here, I told you that we will check whether we have already you that we will check whether we have already accessed the prefix or not. accessed the prefix or not. If so, tell us what should be done for that, we are the If so, tell us what should be done for that, we are the prefix, we are not going to take it, here we will prefix, we are not going to take it, here we will take a prefix, we will wait, it is only okay, take a prefix, we will wait, it is only okay, and we will store the prefix even in the map, it is and we will store the prefix even in the map, it is okay, map in teacher is equals, you okay, map in teacher is equals, you are okay, we will store in it which one. are okay, we will store in it which one. How many times has the prefix sum 'A' come? How many times has the prefix sum 'A' come? Okay, in the beginning, let's put in the map Okay, in the beginning, let's put in the map that 'Brother, zero' has come once. Okay, then the that 'Brother, zero' has come once. Okay, then the loop goes on and i = 0 i < loop goes on and i = 0 i < i plus plus. Okay, let's i plus plus. Okay, let's take this in a way. take this in a way. take this in a way. days and it will do what is the in the result, like I told you, in the result, like I told you, what will you do with plus plus is equal, what will you do with plus plus is equal, what will you do with map.get and the default will be understood what will you do with map.get and the default will be understood - this is what the volume was saying to you, isn't it? -How many times has the goal come in the map? How many times has the goal come? If I don't come then I will add zero. Okay, obviously I will update you as well. Okay, as it will be seen here, Maa, here I am, then I have Okay, if two comes again, Okay, if two comes again, Okay, if two comes again, then two will have to be updated, now two has then two will have to be updated, now two has come twice. Okay, so I will write this brother, come twice. Okay, so I will write this brother, now get and Audi fault yes com zero plus now get and Audi fault yes com zero plus one. Okay, that's all brother, this is the one. Okay, that's all brother, this is the question from three third. question from three third. question from three third. accepted. After submitting, let's see, everything is done. Talking about space complexity, space complexity is big of N and time complexity is of N. You know that first of all we were Add Add Add more to this playlist We have come to Hashman Pe, more to this playlist We have come to Hashman Pe, we saw that how can the questions be stubborn, how we saw that how can the questions be stubborn, how can they be 2.2 Sliding Window, we can they be 2.2 Sliding Window, we saw that now look at the condition that is there, the saw that now look at the condition that is there, the restriction that is there is very exact, restriction that is there is very exact, okay, so that is why we okay, so that is why we had to do this. had to do this. had to do this. how do we do it, like if something like this happens here, then we do it with the sliding window, it is okay, there is no problem, video, you will get the link of the next video [Music] | 2024-03-25 11:32:03 | 930 | LeetCode 930 Solution in HIndi | LeetCode Binary Subarrays With Sum Solution |
|
1drkaHUY0Zs | hey guys welcome back to my channel and i'm back again with another really i'm back again with another really interesting coding interview question interesting coding interview question video today today guys we are going to video today today guys we are going to solve questionable 1652 solve questionable 1652 diffuse the bomb of lead code before i diffuse the bomb of lead code before i start with the video guys if you have start with the video guys if you have not yet subscribed to my channel then not yet subscribed to my channel then please do subscribe and hit the bell please do subscribe and hit the bell icon for future notifications of more icon for future notifications of more such programming and coding related such programming and coding related videos videos let's get started let's get started so basically guys the problem statement so basically guys the problem statement says that we have a bomb to diffuse and says that we have a bomb to diffuse and our time is running out so we are given our time is running out so we are given a circular array like this okay a circular array like this okay and uh so what we have to do is this and uh so what we have to do is this circular array of code circular array of code to its sort of a code to diffuse the to its sort of a code to diffuse the bomb okay and if you want to decrypt the bomb okay and if you want to decrypt the code we must replace every number of code we must replace every number of this code this code with a certain value okay with a certain value okay all the numbers are replaced all the numbers are replaced simultaneously that means one after the simultaneously that means one after the another another and how to replace that number so and how to replace that number so basically we are given a value called as basically we are given a value called as k k okay so let's say these are our codes okay so let's say these are our codes and this is our k value this is sort of and this is our k value this is sort of our key right our key right so if the key value or the k value is so if the key value or the k value is equal equals to 0 if it's equal equals equal equals to 0 if it's equal equals to 0 so we have to replace the ith to 0 so we have to replace the ith number with 0 or we can say that if k number with 0 or we can say that if k value is 0 then all the code values must value is 0 then all the code values must be replaced to 0. be replaced to 0. if the k value is greater than 0 then we if the k value is greater than 0 then we have to replace the ith number with the have to replace the ith number with the sum of the next k number so for example sum of the next k number so for example 5 has to be replaced with the sum of the 5 has to be replaced with the sum of the next three numbers which is 7 1 and 4. next three numbers which is 7 1 and 4. so you can see that if i just crawl so you can see that if i just crawl below it 5 is replaced by 7 plus 1 plus below it 5 is replaced by 7 plus 1 plus 4 4 then 7 is replaced by the sum of the then 7 is replaced by the sum of the next 3 numbers but because this is a next 3 numbers but because this is a circular array so after 1 and 4 the circular array so after 1 and 4 the third number would be third number would be 5 so that's why the sum is 1 plus 4 plus 5 so that's why the sum is 1 plus 4 plus 5 similarly 1 is replaced by 4 and the 5 similarly 1 is replaced by 4 and the sum of 5 and 7 and 4 is finally replaced sum of 5 and 7 and 4 is finally replaced by the sum of 5 7 and 1 okay by the sum of 5 7 and 1 okay so once we do this then we get this so once we do this then we get this array as a result and we can just return array as a result and we can just return this error this is our decoded code so this error this is our decoded code so once you have decoded the code you can once you have decoded the code you can diffuse the bomb okay diffuse the bomb okay now if the k value is less than 0 then now if the k value is less than 0 then you just have to do the reverse you have you just have to do the reverse you have to replace the ith number with the to replace the ith number with the previous k number so for example in this previous k number so for example in this case 5 will be replaced by the sum of case 5 will be replaced by the sum of 4 1 and 7 because they are the previous 4 1 and 7 because they are the previous k numbers k numbers or i would say 4 will be replaced by 1 7 or i would say 4 will be replaced by 1 7 and 5 because they are the previous k and 5 because they are the previous k numbers okay numbers okay so another example you can see here that so another example you can see here that k value is 0 because k is 0 all the k value is 0 because k is 0 all the values of code are replaced by 0 and values of code are replaced by 0 and finally this example is a negative finally this example is a negative example which i have already explained example which i have already explained you so every number is replaced by the you so every number is replaced by the previous two numbers so for example 3 is previous two numbers so for example 3 is replaced by the sum of 4 plus 9 okay replaced by the sum of 4 plus 9 okay the constraints are pretty the constraints are pretty straightforward guys n is the length of straightforward guys n is the length of the coding area and the n could go from the coding area and the n could go from 1 to 100 so basically there could be 100 1 to 100 so basically there could be 100 values values uh the value of the code could be from 1 uh the value of the code could be from 1 to 100 and the k value can go from minus to 100 and the k value can go from minus n minus 1 to n minus 1 to n minus 1 okay so basically the length n minus 1 okay so basically the length of the array right of the array right so now that we know about the problem so now that we know about the problem statement guys let's go to the solution statement guys let's go to the solution part part so to start off with the solution guys i so to start off with the solution guys i am going to first of all declare our am going to first of all declare our result array result array and to do that first of all i'll create and to do that first of all i'll create an element called as len which is an element called as len which is basically going to hold the length of basically going to hold the length of the code and it's a code dot length now the code and it's a code dot length now i am going to declare the result array i am going to declare the result array which i am going to return so enter is which i am going to return so enter is in bracket rest becomes equal to new in bracket rest becomes equal to new inch inch and pass the length so now that we have and pass the length so now that we have declared the resultant array that we declared the resultant array that we want to return okay want to return okay so the first thing so the first thing if if k is equal equals to zero so let's start k is equal equals to zero so let's start with the base case guys because if we with the base case guys because if we are done with the base case that's the are done with the base case that's the simplest case right so for if k is equal simplest case right so for if k is equal equals to zero so for integer i to zero equals to zero so for integer i to zero so i less than so i less than length length i plus plus you simply have to replace i plus plus you simply have to replace all the elements all the elements with the with the zero so as i becomes equals to 0 zero so as i becomes equals to 0 and and then we will do the else condition else then we will do the else condition else if if k is greater than 0 k is greater than 0 some logic and then else is some logic and then else is then k is then k is less than 0 finally when all the if else less than 0 finally when all the if else conditions are done then we are just conditions are done then we are just going to simply return the going to simply return the resultant array okay resultant array okay so uh the first case is done k is equal so uh the first case is done k is equal equals to zero we equals to zero we take all the result elements and then we take all the result elements and then we simply assign them 0 and we return the simply assign them 0 and we return the resultant array okay resultant array okay so the second case second case is when k so the second case second case is when k is greater than 0 so guys if k is is greater than 0 so guys if k is greater than 0 then we are going to greater than 0 then we are going to iterate from then also we are going to iterate all the elements so 0 to i less than length i plus plus but then for every element we are going to replace that element with the sum of the next key elements so we are going to do another follow for integer j equals to 1 to j less than equals to k j plus plus but instead of making res i becomes equals to 0 here we are going to replace rest i or we are going to assign reside to the sum of the next j element so less i become equal to s i plus add the jth element to it okay or i would say i plus jf element to it so i plus j so let's say if i is 0 so for example i is 0 so the first element which we added is the element at index 1 then the element at index 2 and then the elemental index k like so on and finally all of them will be added to rest i and if you continue this for loop then all the resultant values will be the sum of their next k elements right but obviously guys if you do i plus j and let's say the value goes greater than the length of the array you are going to get an array index out of bound exception so to cater that situation you have to do the mod mod of the i plus jth value with the length of the array if you do the more guys what are you going to do for example if my j is at position 3 so 3 plus 3 becomes equals to 6 if i do 6 mod 4 then i will reach to value 2 which is index i mean i reach to value 2 which is the second index here so eventually i will add i will add one and then i will go behind and i will add all these values okay so basically if you mod it with length you will start iterating from behind instead of or you will start iterating from the cyclic position so that's why we are doing this so that even if our i plus jth value goes greater than length it will not give us the air index out of bound exception instead it will start iterating from the other side of the array okay or from the left hand side of the array now so we know is great k is greater than zero so that part is also sorted now comes the complex part the complex part is when k is less than zero so this part definitely guys we need that means iterating the ith value from 0 to i less than length i plus 1. so this thing we definitely need because we are going to replace all the values of the resultant array but because k is less than 0 this time we have to think about it from a different way so because k is less than 0 instead of iterating from integer j to 1 to less than equals to k we will create j becomes equals to minus 1 to j greater than equal to k and this time instead of doing j plus plus we are doing j minus minus okay because remember this is a negative volume okay so because this is a negative value we cannot iterate it from 0 to k or 1 to k value right we have to go from behind minus 1 to greater than equal to k now so we have got the negative value right and what index do we want to reach let's say i want to iterate the previous element so the previous element will becomes equals to i plus j right because let's say if my ith value let's let's take this example so if my ith value or my index value is 3 and my k value is minus 2 so i want minus 1 that means this one so when j is minus 1 then minus 1 plus the ith l value so for example in this case i is 3 and if you subtract 1 from it you will reach index 2 so index 2 will get added and then when j will be in you know minus minus i would say so when j will become from minus 1 to minus 2 that means this value then i i is still 3 so i 3 minus 2 becomes equal to 1 so eventually we will reach 4 and 9 and we are just going to simply add these two and store them in res value okay so don't get confused why i am doing i plus j because j is negative see even if i am doing i plus j i'm still going on an index which is previous to us okay remember that obviously guys the j value could be something which is greater than the length value okay so i my i plus j could be a something uh something like minus 4 for example in this case the maximum index is 3 right whatever it becomes what is whatever it becomes minus 1 okay or minus 4 something so we don't want that so that's why always do a mod will length so that we uh reach at the value which is always contained inside our array now if our index value let's say my index value is greater than 0 then it's good but what if my index becomes equal for example if my index is 0 right if this is my index if i am at this position and the kth value is minus 2 so my next index if i go by this volume will be minus 1 right 0 so i 0 j is minus 1 0 plus minus 1 is minus 1 correct so if i try to go to a position which is minus 1 i'm not going to find it anywhere right so if you always get an index which is lesser than 0 then it basically means you have to go to a position which is previous to it so for example if i am at minus 1 if i add minus 1 to the length of the array length of the array is 4 add minus 1 to the length of the array so what is going to happen you are going to reach to the last position similarly when you will come to minus 2 for example if i add i 0 first j will be minus 1 second j will be minus 2 so then i will reach minus 2 here if i add minus 2 to my length i will reach the second last guy so that's what you have to do if your index is lesser than 0 then just add the index to the length of the array by this you will actually start iterating the array from the other side okay from the behind finally res i will becomes equals to rest i plus code of index okay then once this else is completed you have covered all the cases so just return rest so let's run this code guys let's see if this works for our example cases uh okay there is some error okay fine i wrote return rest multiple times so you just have to write it once so you can see that the example case is and yes you can see that the solution is and yes you can see that the solution is also accepted now talking about the time also accepted now talking about the time complexity guys so the time complexity complexity guys so the time complexity for this solution is uh going to be n for this solution is uh going to be n into k into k because we know that the length of the because we know that the length of the array is order of n array is order of n and the number of times we are adding and the number of times we are adding the k elements is always the k elements is always k right this is the for loop which which k right this is the for loop which which we are running k times we are running k times so that's why the time complexity is so that's why the time complexity is order of n into k order of n into k the space complexity guys is order of n the space complexity guys is order of n because we are creating another because we are creating another resultant array which is having the same resultant array which is having the same length as that of our original code length as that of our original code array okay array okay but i hope guys that this solution was but i hope guys that this solution was clear to you and it works for you as clear to you and it works for you as well and hopefully it helped you in well and hopefully it helped you in in improving your coding practice if i in improving your coding practice if i did guys then please do not forget to did guys then please do not forget to like this video and share this video like this video and share this video with your friends if you are not yet with your friends if you are not yet subscribed to my channel then please do subscribed to my channel then please do subscribe and hit the bell icon for subscribe and hit the bell icon for future notifications future notifications and uh and uh also guys uh also guys uh thank you so much for watching if you thank you so much for watching if you have any comments write down in the have any comments write down in the comment section below i would be happy comment section below i would be happy to read them and work on them to read them and work on them uh so thank you so much i'll see you uh so thank you so much i'll see you guys in the next video until then take guys in the next video until then take care and bye | 2024-03-19 18:22:10 | 1,652 | Defuse the Bomb | Leetcode 1652 | Amazon Google Facebook interview question |
|
jwnWLqU26Ko | so first thing that what we are doing we are creating first and we are moving K are creating first and we are moving K distance from the from the beginning distance from the from the beginning then we are creating another note that then we are creating another note that also uh points to our head and we are also uh points to our head and we are creating temp that points to our first creating temp that points to our first since um the distance from the beginning since um the distance from the beginning from the head to the to the second our from the head to the to the second our node is the exactly the same distance node is the exactly the same distance from the temp to the end of the note we from the temp to the end of the note we are moving them are moving them simultaneously and once we have the simultaneously and once we have the second node we are just swapping the second node we are just swapping the values of first and second | 2024-03-19 17:45:49 | 24 | 1 minute LeetCode - 24. Swap Nodes in Pairs |
|
jCEmOqL8W80 | Loot Hello Viewers Welcome Welcome Back To My Channel Suggestion Or Their Discussion Of The Problem Channel Suggestion Or Their Discussion Of The Problem With Difficult For Me To Death You Not Laga Do With Difficult For Me To Death You Not Laga Do Video Please Like It Subscribe To My Video Please Like It Subscribe To My Channel Subah You Get Notified When The Channel Subah You Get Notified When The Most Innovative Without Any Positive Let's Most Innovative Without Any Positive Let's Get Started Get Started Problem In Problem In Problem In Problem Jeevan To - Singh Binttu Returns The Amazing I Let Us Take Care Sweet Dreams Take Care That Iyer Dates Posting End Second Singh 832 30 Inch Loongi 10 End Second Will Do Something Like This Switch Boys Atin Sodium Wave New Updates To Wicket 0f Result And Jerry That Is Vansh Hai Main To Yeh Saying This Time Naav Siron A Plus Dushman A Plus B S One Witch Carrier Song Again This Is OnePlus One So And You Will Be Amazed 1500 Plus 9900 Wicket Wicket Wicket 0characters 0characters for for entered unemployed form will get your own entered unemployed form will get your own so that is zero brigade and carry again with so that is zero brigade and carry again with one of which will welcome one plus0 one of which will welcome one plus0 a plus b 0 a plus b 0 bhi hua sorry armaan welcome and 109 rates might even so are bhi hua sorry armaan welcome and 109 rates might even so are some of two in some of two in 0tweet Debit, Debit, Debit, that is a Dnyaneshwar, what are you doing, lying down, the that is a Dnyaneshwar, what are you doing, lying down, the hundred pleasures of hundred hundred pleasures of hundred discharges, the knowledge discharges, the knowledge that this 1010 that this 1010 1010 and 12000 1.11 lage to will get unemployed, career and And [ __ ] And [ __ ] And [ __ ] tomorrow morning get 10101 cigarette 1010 tomorrow morning get 10101 cigarette 1010 ₹3 network problem sleep approach from this what are you doing basically basically a v v v v v v v v we are starting from this is from the lost with you can see from outside the right side 2018 in Value e will be 0 in this app you will come here bhi jio phone par dheli will want oo torch light show with me to in and jin jin viewers ko * and values of not only sharing liquid and drink it is this position for example sentences position for example sentences with with with A Plus Wear Also Adding That The Hai But E Will Se Wear Not Adding Carryover Year To English E Will Take Carrier Rear AC Value Will Give Water You Will Want Ho To Amlon Candidates Need To Get Amlon Candidates Need To Get Value Hello How Old Values Value Hello How Old Values Value Hello How Old Values one bittu bittu models of this tweet 2.0 in order to calculate value with that what will you do sammohan tilak to ki and spirit 253 how to that with spirits of but that will be divided into two will get a to Have Done Wear Have Done Wear Have Done Wear Every Time You Will Be Traveling Like Every Time You Will Be Traveling Like This Is Trick This Is Trick Single Line 150 Start From Decide Anil Arrangement Various Places And Will In Turn Will Always Be Done S Five Plus B Plus B Plus Ap 10 10 10 hai to initially given starting from this hai to initially given starting from this 202 plus dushman plus carriages you will come on 202 plus dushman plus carriages you will come on tourism welcome to my election mintu 910 value value will be the song mode to ab to here the song mode to ab to here 360 maurya vansh models to medium nominated 360 maurya vansh models to medium nominated member value get also ward 34 value member value get also ward 34 value vitori vitori vitori Harvesting Ne Distic This Attack Ka Answer Arranged String In So Gillard Value of Interesting Questions and Answers in Preparation and [ Music] Divide Divide 2012 Listen to 12345 Value Is Vansh Apes Ring in Your Eyes and Still Alive 210 Medium to One Plus One No Value Vikram to Motu Experts Sudhir Will Not After Which One Will It Before You are Calculating the Neither Its Disposal of 1000 Before the Co Tight It Life and Works Career Welcome to Back to Which is My Choice Career Option Will Repeat Also Step Sunflower Do It Now Over What Are We Are You Will Here IS Scheduled For 1000 Results Will Come When Results Will Come When Divided Into Two Parts 120 Hands Divided Into Two Parts 120 Hands Free Web Counters Free Web Counters And No I Will Go On Air And No I Will Go On Air And No I Will Go On Air I am the same a I am the same a 2051 plus b co 501 and carries you listen 2051 plus b co 501 and carries you listen come to come to 200 fund value meaning Vivo before and 200 fund value meaning Vivo before and died to carry mulligan one can carry will died to carry mulligan one can carry will update 251 questions video value and update 251 questions video value and patience is patience is to novel to novel torture camp torture camp torture camp 101 0 0 0 Here Open Understood To Prove What They Are Doing Very Simple Questions Beta Testing Carry We Are Doing Song Called Divya Calculating Value And Is Divya Calculating Alone One Medium Alarms Like 2002 Divide Divide In Verification Video Buy To A Plate Here Know Your Parents Should Approach A The Code Very Simple What Doing Well Travels 30 Viewers Rank Calculating the Length of the Best Ringtone Regulating Length of the Best Thing in the Water Havells Vihar Loud in Which Loud in Which Loud in Which File Taking Its Value Is Valued For The Giver The Length Of The Value Of That And This Boy Doing It Because When A To Get This Last Value This Condition Happened By Accident And Wasting Are Eyes From 087 Been Easier Like and 12th leading Like and 12th leading Like and 12th leading that I love you can say is from Delhi that I love you can say is from Delhi and over what doing Bihar taking lives due to its and over what doing Bihar taking lives due to its ring is dish 101 indic ring is dish 101 indic civilization 0123 so I will here but how to give civilization 0123 so I will here but how to give addition for the right to express will get will get addition for the right to express will get will get a a Minus minus one index Minus minus one index 123 index of this world 123 index of this world torch light handed chatting with us in the next to take torch light handed chatting with us in the next to take wire same thing in the wire same thing in the interests of the value of calculating the volume to in vivo v9 plus to plus to get converted to avoid Answer Answer Is The Meaning Of The Name Of The And Posting Suite With Me Including 10 Maths Chapter 9 That And Time Black Click Here Its Time Black Click Here Its Direct Is Wire Loot Will Run Until All This End Direct Is Wire Loot Will Run Until All This End Essence Of All Na Niend Vidron Its Soil Essence Of All Na Niend Vidron Its Soil Health Problems Health Problems Health Problems Be A Great Help Length And Breath And Give Them A Between Total Yo Yo Honey To Lenses Inspirational Prayer Oil ₹10 Continent Which 110th Bhi To Time And Space Complexes Can Stand Were Not Using Excel Data Structure Viewers Using problem very simple but does so please like does so please like subscribe and | 2024-03-20 11:09:47 | 67 | Add Binary 🔥| Leetcode 67 | Math | Bit Manipulation | String |
|
06oWnxVIAv0 | hey everyone welcome to techquired in this video we are going to solve problem this video we are going to solve problem number 1071 greatest common divisor of number 1071 greatest common divisor of strings strings so here we are given two strings we need so here we are given two strings we need to find the largest string that divides to find the largest string that divides both string 1 and string two both string 1 and string two and now let's see the logic on the and now let's see the logic on the solution for this problem solution for this problem so this is the first example that has so this is the first example that has been given in the Lead Core website been given in the Lead Core website and before solving this problem if you and before solving this problem if you guys haven't subscribed to my Channel guys haven't subscribed to my Channel please like And subscribe this will please like And subscribe this will motivate me to upload more videos in motivate me to upload more videos in future and also check out my previous future and also check out my previous videos and keep supporting videos and keep supporting so here we are given two strings and in so here we are given two strings and in the question it says that one of the the question it says that one of the string is concatenated with other string okay for example here S1 a b c a b c right here S2 is ABC here S2 has been repeated two times in S1 this S2 Plus S2 right so that's how the inputs will be so what I'm going to do here is I'm going to keep S1 as the largest string every time okay I'm going to write a recursive call I'm going to keep S1 as the largest and S2 as the smaller string okay so this will be done by swapping okay if S2 is greater than S1 I am going to swap X1 and S2 so whenever I do the recursive call I'm going to break S1 and keep S2 as it is now I will so initially I'm going to check if S2 is so initially I'm going to check if S2 is greater than S1 if this happens I'm greater than S1 if this happens I'm going to swap okay I will swap S1 going to swap okay I will swap S1 and S2 okay and S2 okay or or I'm going to call a recursive I'm going to call a recursive function okay function okay since I keep S2 as small all base since I keep S2 as small all base I am guaranteed that the first I am guaranteed that the first from 0 to length of S2 from 0 to length of S2 it is going to be the first part of the it is going to be the first part of the S1 S1 so when this condition fails I am going so when this condition fails I am going to return an empty string to return an empty string okay okay or if the condition is satisfied whether or if the condition is satisfied whether I found my substring of S1 the first I found my substring of S1 the first part of S1 part of S1 as S2 as S2 then I'm going to break S1 and I'm going then I'm going to break S1 and I'm going to do the recursive call on this part to do the recursive call on this part after this after this okay now I'll show you the recursive okay now I'll show you the recursive call as well call as well so initially I will check S1 is lesser so initially I will check S1 is lesser than or yes less than S2 than or yes less than S2 in other words whether S2 is greater in other words whether S2 is greater than S1 if S2 is greater than S1 I'm than S1 if S2 is greater than S1 I'm going to swap I am going to keep S1 as going to swap I am going to keep S1 as the largest string always the largest string always okay and if I don't find the first part of S1 as S2 it should be equal okay if it is not equal I am going to return the empty string and if it is equal I am like this lenov S2 okay then I'm going to do the recursive call on this one this part I'm going to Omit this part so my new S1 here will be ABC okay now I will write another condition I'll write another condition when my S1 and S2 are equal then that is the largest common device the greatest common divisor of both strings and I will always keep S2 as it is the so even if S2 is greater than S2 when we so even if S2 is greater than S2 when we call the recursive call call the recursive call okay because the function okay because the function we are writing a condition to swap right we are writing a condition to swap right so every time is S1 will be it's so every time is S1 will be it's guaranteed it's going to be largest guaranteed it's going to be largest string or it's going to be equal to S2 string or it's going to be equal to S2 if it is equal to S2 I am just going to if it is equal to S2 I am just going to return return my S1 my S1 or we can written S2 as well since both or we can written S2 as well since both are going to be same are going to be same I will also show you guys with the I will also show you guys with the another example another example so this is the another example that is so this is the another example that is found in the lead code so here S1 is found in the lead code so here S1 is greater than S2 I'm just going to keep greater than S2 I'm just going to keep as it is as it is now I'm going to check whether my S2 is now I'm going to check whether my S2 is in my the first part in my the first part of my S1 of my S1 yes we can we could see that yes we can we could see that both are equal so my new S1 will be a b okay so this is my new S1 now I call the recursive function since here S2 is greater than S1 I'm going to swap okay I'm going to swap S1 and S2 now S1 will be a b a b and S2 will be a b fine now I'm again going to check whether S2 is in my S1 I mean the first part of S1 should be S2 okay here it is so I'm going to break S1 again okay my new S1 will be a b a b okay so now I will do the recursive call again so in this case S1 is equal to S2 right so this is the greatest common divisor of both strings so I'm going to return a b fine now let's see the code so now let's see the code so initially is greater than my length of the string is greater than my length of the string one one okay if it is greater I am going to swap okay if it is greater I am going to swap string 1 and string 2. string 1 and string 2. I'm always trying to keep the string 1 I'm always trying to keep the string 1 as the largest string as the largest string okay okay I will be swapping here I will be swapping here now I'm going to write a condition if the first part of the string one should be string two okay I'm going to Break String 1 with the length of string two okay if it is not equal to my string 2 else and I'm going to write a condition here if my string string 2 and string 1 or equal then I'm going to return that then then if I found S2 the S2 in my first part of if I found S2 the S2 in my first part of my S1 then I will break S1 my S1 then I will break S1 okay I will be breaking S1 okay I will be breaking S1 so I'm going to call recursively so I'm going to break S1 I'm going to so I'm going to break S1 I'm going to take all of the characters in my S1 after the length of my S2 I'm going to break based on S2 okay and I will keep the lowest S2 as same if S2 is going to be greater here when I call recursively it it is going to swap here okay if you're going to do this swapping here so it will work it's guaranteed that S1 always be greater than S2 okay let's run the code let's run the code as you guys see it's pretty much as you guys see it's pretty much efficient efficient the time complexity for this particular the time complexity for this particular problem is order of N and the space problem is order of N and the space complexities for this problem is order complexities for this problem is order of n as well since we are using of n as well since we are using recursion that that is going to be a recursion that that is going to be a recursive stack right the call stack recursive stack right the call stack so it's going to be order of n space so it's going to be order of n space thank you for watching this video please thank you for watching this video please like And subscribe like And subscribe this will motivate me to upload more this will motivate me to upload more videos in future and also check out my videos in future and also check out my previous videos keep supporting happy previous videos keep supporting happy learning cheers guys | 2024-03-25 16:42:53 | 1,071 | Greatest Common Divisor of Strings | Leetcode - 1071 | Python |
|
7mT--zgxt-A | in this video we're going to go over elite code problem which is convert elite code problem which is convert binary number in a linked list to binary number in a linked list to integer integer so you have a binary number and you want so you have a binary number and you want to make it to make it into an integer a decimal number into an integer a decimal number base 10. so binary is base two that's base 10. so binary is base two that's something you need to know for this something you need to know for this problem it's not terribly job specific thing so hopefully if you're if you get this on an interview and you don't know binary is the interviewer to explain it to you but um this is our example one zero one so um just a number like one zero one which is a binary number and this would convert to 5 and it converts to 5 because we have this is our ones place so 1 times 1 and then start 2's place so 0 times 2 that's our fourth place so 1 times 4 so 1 times 4 is 4 plus 1 times 1 is 5. so that's our first test case we the naive and and the naive and and you know a simple way to do this uh but you know a simple way to do this uh but not the fastest way would be not the fastest way would be to um traverse through this linked list to um traverse through this linked list and maybe add these to a stack or and maybe add these to a stack or something and then as we pop them off something and then as we pop them off the stack we can the stack we can um we'll know like what place they need um we'll know like what place they need to be so to be so ones place two's place four's place um ones place two's place four's place um and then we can multiply each one by and then we can multiply each one by that number that number um maybe we could have a map or um maybe we could have a map or something or some kind of something or some kind of um key value pair to do that but there's um key value pair to do that but there's a way that we can do this in one pass a way that we can do this in one pass and if you think about let's say we have and if you think about let's say we have just this number one zero one just this number one zero one so we're going to have a fourth place a so we're going to have a fourth place a two's place in a one's place two's place in a one's place and let's say we actually have um let's and let's say we actually have um let's say a different say a different test case for this there's a couple test case for this there's a couple let's say we're just gonna do one one let's say we're just gonna do one one zero one just to make it a little more zero one just to make it a little more helpful so we have our fourth place helpful so we have our fourth place two's place ones place in this case we two's place ones place in this case we also have also have an eighth place at the start so an eighth place at the start so another way to look at this is that we another way to look at this is that we have have our our 1 is going to be our our 1 is going to be 2 to the 0 2 to the 0 and we're going to push that out our 2 and we're going to push that out our 2 is going to be 2 to the 1. is going to be 2 to the 1. our 4 is going to be 2 to the 2. our 4 is going to be 2 to the 2. let's give a space here and our eight is let's give a space here and our eight is going to be two to the three going to be two to the three okay so this is going to help us as we okay so this is going to help us as we walk through this problem and this will as we kind of look at this we're gonna figure out how we can do this in one pass so we don't need to do that mapping that i mentioned earlier so here when you look at this you can really see there's like okay this three two one zero so it looks a little more linear and so as we add each number we're really going to be adding one extra thing here and what that turns out to be is we're just going to be multiplying by 2 one more time so how can we loop through these loop through this linked list and multiply by two one more time for each thing so let's look at how we can do that first we're so we get the head here which is the head node which has value at a next next points to another node in the linked list so let's go ahead and store um we want current node and that's going to be initialized as head and then we also want our total here we can just initialize that to zero and then we're gonna be looping through this stuff and so we wanna say while there's current node we're gonna do something and in our constraints we do know that there is um there's always going to be a head at least so we're not going to ever have a an empty linked list and then at the end we want to return our total okay so within here we want to adjust our total amount so our total is going to equal remember i mentioned as we're traversing through we're going to multiply by 2 for each different place so each time our total is going to equal total times 2. and that means the the first place is going to get multiplied by 2 one more than the second place and and so on and so forth so this is going to take care of that for us and then we also because this last number we don't want to multiply by 2 this is just our ones place so our last number is going to be we also just want to add our current node dot val which is the current value that we have so we could condense this into one line but let's just leave it like that for now just so it's a little more clear so we're going to multiply our whole thing by two and then we're going to add the current val so let's get rid of this and add that here okay and then of course we're going to reassign current node equals current node.val excuse me chrono not next and then we're just gonna go through the while loop and um once we get to the end here the current node.next is gonna be null so it's gonna set it to null and then current node is going to be null which is the faulty statement so it's going to continue through execution pass the loop and return the total so this should do the trick for us we could run through test cases manually which is what you should do if you're in an actual interview you should like talk through how it would play out but for now let's just run this first test case see how this runs and it's accepted and our second test case okay it works and then we can go through okay it works and then we can go through the rest of these but this the rest of these but this is um the fastest solution for is um the fastest solution for converting converting converting a binary number in a linked converting a binary number in a linked list to an integer list to an integer and it only takes one pass and it's big and it only takes one pass and it's big o of n o of n time so this is how it's done hopefully time so this is how it's done hopefully this helps you out and we will see you this helps you out and we will see you in the next video | 2024-03-20 10:41:33 | 1,290 | LeetCode Convert Binary Linked List to Integer - JavaScript |
|
j2UK0EcgbN0 | hey hey everybody this is larry this is me going with q2 of the weekly contest me going with q2 of the weekly contest 254 a wave of elements not equal to at 254 a wave of elements not equal to at rich of neighbors hit the like button rich of neighbors hit the like button hit the subscribe button join me on hit the subscribe button join me on discord especially if you like these discord especially if you like these kind of contest forms people talk about kind of contest forms people talk about the problems all the time usually right the problems all the time usually right after the contest so if you're into that after the contest so if you're into that you want to nerd it out with larry come you want to nerd it out with larry come hang out anyway for this one it's kind hang out anyway for this one it's kind of tricky it is what um of tricky it is what um in competitive programming this is what in competitive programming this is what is known as a constructive is known as a constructive uh problem there are a number of uh problem there are a number of arrangements and you can do there are a arrangements and you can do there are a lot of different techniques to kind of lot of different techniques to kind of figure out a different oh sorry maybe figure out a different oh sorry maybe not for this particular problem but not for this particular problem but there can be many different solutions there can be many different solutions and you all you have to do is come up and you all you have to do is come up with one of them um with one of them um and this is a constructive problem and this is a constructive problem because you're trying to figure out a because you're trying to figure out a strategy where this is not true where strategy where this is not true where the two neighbors are not true um so i the two neighbors are not true um so i kind of thought about it and of course n kind of thought about it and of course n is 10 to the fifth so you have to do is 10 to the fifth so you have to do this in a very quick way um in that this in a very quick way um in that you know n square is going to be too you know n square is going to be too slow or and n log n is going to be fast slow or and n log n is going to be fast enough so that's going to be the enough so that's going to be the approach that we take uh and with these approach that we take uh and with these this particular problem you're trying to this particular problem you're trying to rearrange the rearrange the the um the array in any way possible so the um the array in any way possible so the first thing that i do on these the first thing that i do on these things is that i sort not always but for things is that i sort not always but for this one i do because this one i do because sorting sorting what you're doing with sorting is that what you're doing with sorting is that you hope that it gives you a structure you hope that it gives you a structure that you can take advantage of and the that you can take advantage of and the thing that i noticed um actually if you thing that i noticed um actually if you watch me stop the live i actually watch me stop the live i actually um um try to do it another way where where try to do it another way where where because everything is unique because everything is unique so i made one the first observation that so i made one the first observation that i made is that because these are this i made is that because these are this thing and or thing and or one other way that of saying that is one other way that of saying that is that every number is unique because that every number is unique because every number is unique every number is unique let's say we have let's say we have you know a and b in the first two you know a and b in the first two numbers and we're trying to add c numbers and we're trying to add c there's only one possible numbers where there's only one possible numbers where c is c is um you know um you know if c is equal to a plus b over two if c is equal to a plus b over two then this is no good but it could be any then this is no good but it could be any other number and it'll be good so what i other number and it'll be good so what i did and assuming that is unique was that did and assuming that is unique was that i created a i created a a q um and what i did with the q was a q um and what i did with the q was that i i go okay if that i i go okay if if the next number with the top of the if the next number with the top of the stack is equal to this number then we stack is equal to this number then we just just take it and put it at back of the queue take it and put it at back of the queue um and then go again um um and then go again um so i thought about it and i implemented so i thought about it and i implemented this and you can watch me this and you can watch me implement this live next but so i implement this live next but so i implement this and then i was like implement this and then i was like okay there is a case where that might okay there is a case where that might not be good though right because for not be good though right because for example if you just have one two and example if you just have one two and three now you're stuck in an infinite three now you're stuck in an infinite loop because you just keep on popping loop because you just keep on popping three and putting three back in and so three and putting three back in and so forth what you needed to do is put the forth what you needed to do is put the three next to the two and then that's three next to the two and then that's when i hit a second inside of okay when i hit a second inside of okay so so a number cannot be the average of the a number cannot be the average of the two adjacent numbers if it's not in the two adjacent numbers if it's not in the middle of those two numbers right so i middle of those two numbers right so i go okay so let's just look at for in go okay so let's just look at for in this example this example um um in this example in this example we can move the three up for example we can move the three up for example because three is not within because three is not within um because we know that um because we know that three is bigger or three is bigger or yeah because three is not between one yeah because three is not between one and two it cannot be the average no and two it cannot be the average no matter what so then the problem in my matter what so then the problem in my mind reflects to mind reflects to um how do i make this such that um how do i make this such that this is the case and what i did was that this is the case and what i did was that i i i sorted i sorted i sort the problem or i thought the i sort the problem or i thought the input and then i take one from the left input and then i take one from the left and then take one from the right so what and then take one from the right so what i'm doing here now is that i take the i'm doing here now is that i take the smallest number and i take the biggest smallest number and i take the biggest number um let's just say it's one to ten number um let's just say it's one to ten right and then next one i go two nine right and then next one i go two nine three eight four seven and dot dot dot three eight four seven and dot dot dot right um and the reason why there's no right um and the reason why there's no average in between is that because for average in between is that because for every three numbers every three numbers the middle number is not between them so the middle number is not between them so there's no average because it's not even there's no average because it's not even in between um so same thing here same in between um so same thing here same thing here and same thing here so that's thing here and same thing here so that's basically the idea that i have and basically the idea that i have and that's the idea that i implemented um that's the idea that i implemented um you can sort this in you can sort this in uh and yeah of course the complexity uh and yeah of course the complexity here is that so is dominated by the here is that so is dominated by the sorting which is n log n time and then sorting which is n log n time and then here it's going to be linear but it's here it's going to be linear but it's still going to be dominated by n again still going to be dominated by n again um we do have a q and an answer so it's um we do have a q and an answer so it's going to be linear space so n log n time going to be linear space so n log n time of n space uh let me know what you think of n space uh let me know what you think about this one um i think this one is about this one um i think this one is one of those problems where like it's a one of those problems where like it's a constructive problem right so if someone constructive problem right so if someone tells you the answer you're like oh of tells you the answer you're like oh of course that makes sense but i hope that course that makes sense but i hope that if you watch me solve it next you'll see if you watch me solve it next you'll see that i'm actually trying different that i'm actually trying different things trying to figure out different things trying to figure out different ways playing around the numbers to kind ways playing around the numbers to kind of of see how i you know maybe get some see how i you know maybe get some feelings about it um and that's feelings about it um and that's ultimately what i did i didn't i mean ultimately what i did i didn't i mean maybe at least in this case i didn't go maybe at least in this case i didn't go oh this is you know whatever so i don't oh this is you know whatever so i don't know let me know what you think and you know let me know what you think and you could watch me solve it live during the could watch me solve it live during the contest next hmm there's only one so oops um okay uh yeah thanks for watching hit the like button hit the subscribe button join me on discord especially if you like these contest problems we we talk about problems all the time uh of the contest type but you know come come swing by uh let me know what you think i'll see you later to a good weekend to good you know mental health and i'll see you | 2024-03-25 13:22:55 | 1,968 | 1968. Array With Elements Not Equal to Average of Neighbors (Leetcode Medium) |
|
5d6jRwrEehE | uh this question is most frequent subtree sum so you are given a root and subtree sum so you are given a root and then particular return the most frequent then particular return the most frequent subtruism so just keep adding and then subtruism so just keep adding and then for every single frequency you just put for every single frequency you just put into the map or print to the counter and into the map or print to the counter and then you want to keep on track for the then you want to keep on track for the mass the highest frequency mass the highest frequency this is because if you want to return uh this is because if you want to return uh you want to return the highest frequency you want to return the highest frequency number in a list but at the end you want number in a list but at the end you want to return it in Array so to return it in Array so um um so here's it so I'm going to just use a so here's it so I'm going to just use a post order post order so I'm going to Traverse my left and so I'm going to Traverse my left and then Traverse my right and then add my then Traverse my right and then add my current value current value and then this is pretty much the idea so and then this is pretty much the idea so uh let me just go through the entire uh let me just go through the entire solution and once I type it and then solution and once I type it and then you'll be able to know so I need a map you'll be able to know so I need a map and you know integer right and I also and you know integer right and I also need integers need integers so the first the key is going to be so the first the key is going to be represent the sum represent the sum and then the value is going to be and then the value is going to be represent the frequency represent the frequency I also need to keep on some my current I also need to keep on some my current the highest Max frequency right the highest Max frequency right as I'm initialize my map to here as I'm initialize my map to here initialize my mass Max frequency to here initialize my mass Max frequency to here I'm going to Tribute my entire tree I'm going to Tribute my entire tree using a DFS and put in the root using a DFS and put in the root and I'm going to say probably so and I'm going to say probably so sometimes we use the volume right and in sometimes we use the volume right and in this time we need to use in because we this time we need to use in because we need to return the current frequency need to return the current frequency number for the current node right so DFA number for the current node right so DFA is three no no so if the node is already is three no no so if the node is already equal to no equal to no so which means this is nothing so it so which means this is nothing so it just returns 0 else it's going to be sum just returns 0 else it's going to be sum sum is going to be equal to what the sum is going to be equal to what the dfs.noda left Plus dfs.noda left Plus DFS DFS plus another right plus another right Plus Plus no double and so you can you can no double and so you can you can definitely use in the pre-order you know definitely use in the pre-order you know in order in this one I'm using post in order in this one I'm using post order order it doesn't matter the the frequency is it doesn't matter the the frequency is going I mean the frequency is going to going I mean the frequency is going to be the same right and be the same right and yeah this is pretty much it right so uh yeah this is pretty much it right so uh once I have the song for the current once I have the song for the current note I need to put the sum into the map note I need to put the sum into the map but I also need to add a frequency if but I also need to add a frequency if there is a sum inside the map right so there is a sum inside the map right so using the map Target or default using the map Target or default some if if you don't have it then you some if if you don't have it then you initial it to zero and then you plus one initial it to zero and then you plus one for the current you know the current for the current you know the current sound frequency right and I need to keep sound frequency right and I need to keep a keep on track for my Max frequency a keep on track for my Max frequency equal to master Max equal to master Max and then it's either Mass frequency or and then it's either Mass frequency or what method get some right what method get some right and then at the end I need to return the and then at the end I need to return the song because I need to keep traversing song because I need to keep traversing my entire tree based on the the my entire tree based on the the frequency for I mean for the current no frequency for I mean for the current no frequency right so the sum is the frequency right so the sum is the current frequency all right so once I current frequency all right so once I have it have it I need to Traverse my map right so I need to Traverse my map right so ends key ends key and then Mata key set and then Mata key set okay okay and then I need the current frequency and then I need the current frequency right right so on that type get key so this is the so on that type get key so this is the current frequency so if the frequency if current frequency so if the frequency if the current frequency is actually equal the current frequency is actually equal to the max frequency to the max frequency I need to add into the inner array right I need to add into the inner array right but the problem is we don't know the but the problem is we don't know the size of flow in Array so I'm going to size of flow in Array so I'm going to I'm going to just add I'm going to just add I'm going to add another list which is a I'm going to add another list which is a red list I'm going to play Let's Open a red list I'm going to play Let's Open a list of integer right in order this list of integer right in order this all right so if if the curve frequency all right so if if the curve frequency is equal to the max frequency I'm going is equal to the max frequency I'm going to add into the one the release and what to add into the one the release and what when I add it I need to add a current when I add it I need to add a current frequency which is the key right frequency which is the key right right key is a frequency right the sound right key is a frequency right the sound frequency and then the value is a frequency and then the value is a frequency number like how many time it frequency number like how many time it actually reach right actually reach right so uh this is pretty much it right so uh so uh this is pretty much it right so uh when I return I need to return the in when I return I need to return the in Array Array so I have the array list where I can try so I have the array list where I can try I can convert to the inner array based I can convert to the inner array based on this using a string and then map two on this using a string and then map two in in and you can initialize 2x to X so I and you can initialize 2x to X so I don't multiply the value and I need to don't multiply the value and I need to say two array all right so this is pretty much it right so let me run it right so I forgot uh semicolon so let's talk about the timing space for so let's talk about the timing space for the time you shoulders every single node the time you shoulders every single node it's going to be all the fun and this it's going to be all the fun and this space is going to be all open as well space is going to be all open as well right uh you put every single no uh sum right uh you put every single no uh sum into the unit I mean into the arraylist into the unit I mean into the arraylist OR into the map right so it's all a OR into the map right so it's all a frame for both frame for both so let's you know like I'm going to say so let's you know like I'm going to say the breadcrumb right here because when I the breadcrumb right here because when I Traverse my TFS I know my current uh Traverse my TFS I know my current uh the map right and I will just keep the map right and I will just keep okay so I'm using a debug okay so I'm using a debug debug mode and just uh look on the left debug mode and just uh look on the left and you know and you know so for the root is what five two so for the root is what five two negative three right negative three right definitely there is an app you know it definitely there is an app you know it didn't show didn't show and all right so 2 negative 3 4 is actually the answer but uh I don't know why I didn't show uh show the map uh this is pretty much a solution | 2024-03-22 16:08:17 | 508 | LeetCode 508. Most Frequent Subtree Sum | DFS | MAP | Debug | Java |
|
vlPVTqKKdx0 | hey everyone today we'll be looking at longest increasing path in a matrix longest increasing path in a matrix we'll try to solve it in less than 15 we'll try to solve it in less than 15 minutes okay it's a hard problem so minutes okay it's a hard problem so hopefully we can solve it but if not hopefully we can solve it but if not then need code Baba zindabad let's do then need code Baba zindabad let's do this okay given an M N M and N integer this okay given an M N M and N integer mean Matrix return the length of the mean Matrix return the length of the longest increasing path in in Matrix longest increasing path in in Matrix from each cell you can either move in from each cell you can either move in four Direction left right up down you four Direction left right up down you you may not diagonally move or outside you may not diagonally move or outside the boundary that is wrap around is not the boundary that is wrap around is not allow okay allow okay so so yeah the longest increasing path is 1 12 yeah the longest increasing path is 1 12 69 mhm okay uh um mhm the longest increasing path 69 that is wraparound is not six in here 1 2 I don't get it for each cell you can either move okay you may not move diagonally or move outside the boundary that is wrap around is not allowed yeah I get it but duplicates longest increasing path Matrix so for me if I uh look at this 1 Matrix so for me if I uh look at this 1 2 6 9 and I guess the number should not 2 6 9 and I guess the number should not get repeated that is one of the get repeated that is one of the challenge that is there challenge that is there got it so looking at the solution uh got it so looking at the solution uh looking at the looking at the example the number shouldn't get example the number shouldn't get repeated if it gets repeated then yeah repeated if it gets repeated then yeah so that makes things so that makes things easier if you look at at that easier if you look at at that way so if I start at like we I have to way so if I start at like we I have to Traverse Traverse through through um the array and let's say if I Trav through nine first or how should I decide which should be my moving point or how should we think we have to Travers through the think we have to Travers through the entire array entire Matrix and for every entire array entire Matrix and for every cell you need to calculate the cell you need to calculate the distance distance and if the new cell uh if we Traverse and if the new cell uh if we Traverse the cell and if it is the longest one the cell and if it is the longest one then we need to replace the array with then we need to replace the array with the new the new one but other than that I don't think one but other than that I don't think so we need to do anything other than so we need to do anything other than that that [Music] [Music] so okay first of all we need to see if so okay first of all we need to see if it is in increasing order and if it is it is in increasing order and if it is and it is not equal uh equal and it is not equal uh equal to less than or equal to the previous to less than or equal to the previous cell that we visited so we want to make cell that we visited so we want to make sure that it doesn't happen that sure that it doesn't happen that way and we do not revisit uh the cell way and we do not revisit uh the cell that we have already visited so that uh that we have already visited so that uh we need to take care we need to take care of of so that being said okay so what we need to do is every time we Traverse any cell um I believe we need to have an array which um in which we'll store the number of nodes that we have traversed in an increasing order so yeah that's what we should be returning at yeah so how can we do that how can we do yeah so how can we do that how can we do it it um um so let's do this we know for matter of fact that we need to Traverse the entire length of the Matrix right is equal to um before doing that let's take in row is equal to row Len is equal to Matrix do length let call Len is equal to Matrix of Z do length so we got those two and what we need to do is we need to Traverse the row row L Z J is less than column Z J is less than column length j++ I need to Traverse these okay yeah and one more thing that we need to make sure is that let result is equal to an empty array right let new result new result which will be returned by TFS of i n g that will be sending along with the visited okay so along with the visited and here we'll check if new result do length is greater than result total length if it to new to new result okay yeah that's what we'll do result okay yeah that's what we'll do and yeah once we have done that we also and yeah once we have done that we also need to make sure that we return our need to make sure that we return our result in the end result in the end yeah so that's yeah so that's that that um and finally what we need to do um and finally what we need to do is we need to start sending an empty array we need to start sending an empty array and one more thing we need to and one more thing we need to create um create um visited um array visited is equal to new visited um array visited is equal to new array you need to pass the rule in to it array you need to pass the rule in to it and then we need and then we need to need to also it and need to return array call do fill with false and that should exactly give us a 2d false okay so we are here and what we false okay so we are here and what we are going to do here is are going to do here is function we need to Define rdfs function function we need to Define rdfs function right that's where the magic will happen right that's where the magic will happen we ccept R and C then we accept the we ccept R and C then we accept the visited what we also need to send is visited what we also need to send is along before the visited we also need to along before the visited we also need to send the Matrix that is given to send the Matrix that is given to us right so once we have the Matrix access Matrix and also we need to uh result okay yeah once we have this we need to okay yeah once we have this we need to check if we are not going out of pound and and yeah um we are not going out of pH and we need to also check uh with the previous value uh if it is not equal to the previous value we need to also check that mhm mhm so let's do the basic check first if R so let's do the basic check first if R is less than zero or or if R is greater is less than zero or or if R is greater than equal than equal to matrix. to matrix. length or length or or or else for simpl Simplicity sake we or or else for simpl Simplicity sake we just um Define it here so that yeah we can have access L L [Music] [Music] row let's write it row let's write it properly row properly row Len Len and C is sorry my bad C is less than and C is sorry my bad C is less than zero or C is zero or C is greater is greater than equal greater is greater than equal to call to call then yeah if these any of these things then yeah if these any of these things happen we need to go back happen we need to go back and in instead of okay or visited of R and C equals to two equals to equals to true then to two equals to equals to true then also we need to return right return back also we need to return right return back we don't want to do anything here so we don't want to do anything here so return return and just in case if here so what I need to do is I also need here so what I need to do is I also need to uh send back if it is equal to the to uh send back if it is equal to the previous S one so how can we do that I can have it here so how can we do that I can have it here uh Define the previous one um or define null previous and I don't need this Matrix previous and I don't need this Matrix anymore I anymore I also don't need the visited anymore because we are anyways writing it in the the function itself so I have this previous value and the result value okay I need these let's call it rest instead and and if PR is not equal to equal to null and if PR is not equal to equal to null and and and PR is not equal to equal to n and C current value is equal to equal to C current value is equal to equal to previous then we don't do anything we previous then we don't do anything we return we don't want to we don't we return we don't want to we don't we don't want part of this so we return don't want part of this so we return right we don't want to do any any of this and if uh if everything goes well we come here what we do is we have to first set visited of that RNC equals to is yeah and we also need to make sure yeah um instead of equal to equal to prep we need to make sure that if it is less than equal to less than equal to previous then there is no incre increasing order right so we return so if it is increasing then we know for that okay and we we we need that okay and we we we need [Music] to need to also put Matrix here okay so I am n j here and you need to push rest. push push Matrix of R and C or what we can do is we can you can simply so my oh my goodness my laptop is running slow sorry about that let um let current is equal here let get rid of this and let's call here let get rid of this and let's call it it current okay so we push the current current okay so we push the current value into uh onto the Matrix onto the value into uh onto the Matrix onto the result array result array and what we need to do is top left right and what we need to do is top left right bottom right we need to go there so bottom right we need to go there so DFS r + DFS r + one R minus one is top one R minus one is top C uh then previous is now our current C uh then previous is now our current and result is and result is result I need to figure out how I'll be result I need to figure out how I'll be turning my array so this would be + so this would be + one this would be nothing this would be one this would be nothing this would be minus oh minus oh sorry - sorry - one and this would be + one and at the before leaving this we need to make sure that visited of R and C uh we false Okay so the end I I suppose we can just return the result return the rest and that's how we'll get value so what's say guys will that value so what's say guys will that work only way to find out work only way to find out is running this is running this function okay it did not work but uh function okay it did not work but uh let's check let's check what did it send Nan it send out Nan why what did it send Nan it send out Nan why is that why did you send out Nan do you have a good reason for that Matrix if previous is not equal to equal to Matrix yeah this will for the first case Matrix yeah this will for the first case it won't be triggered but for the rest it won't be triggered but for the rest of the cases it will be of the cases it will be triggered triggered so so yeah let me check a what yeah let me check a what console.log if in fact we are uh getting console.log if in fact we are uh getting anything back from the DFS function or anything back from the DFS function or at least like what are we getting exactly so what happened here was 9 99 9 I saw this okay so yeah so let's say I came in here okay so yeah so let's say I came in here I went nine has already added oh yeah oh yeah I added the nine again I added the nine again I shouldn't that that if if prev is I guess if if prev is I guess if I guess to deal with this uh we can if I guess to deal with this uh we can just send a empty just send a empty uh empty thing and it should take care uh empty thing and it should take care of this instead of you know of this instead of you know unnecessarily um doing it here so there unnecessarily um doing it here so there should be just one nine now so 9 comes should be just one nine now so 9 comes in in 9 we s n and 9 we s n and then this this was less then this this was less then this was less then it sent this one then this was less then it sent this one then 4 9 4 489 really current it shouldn't have sent 489 it should have just send 48 uh or oh um guys I'm going on a break I'll be back okay hello hello okay we are connected but why is this not showing anything anyways okay so I won't worry about that but yeah let's see uh if uh okay so 489 I came to 4 [Music] went okay that is a problem right I I went okay that is a problem right I I went to a eat it should be an increasing path [Music] so every path that we take could lead to path okay that's what I understand and path okay that's what I understand and uh what we cannot have for is so see um if we send it to 9ine and8 is so see um if we send it to 9ine and8 at this time four and 9 would be the at this time four and 9 would be the one and okay what the hell man every time so let's go back to the EXA uh let me first of all get rid of everything that is over here okay so I have this guy 9 9 4 8 6 6 21 1 okay I drew this and so what I'm currently doing is if if and so what I'm currently doing is if if I go to I go to four then I can move this direction this four then I can move this direction this direction this direction this this two direction this direction this this two this two this two directions these two directions are not directions these two directions are not of any right because it will return out of any right because it will return out so what we are interested in is uh these so what we are interested in is uh these two two values uh then uh then what we can do is values uh then uh then what we can do is that that uh what we can do is we can we uh what we can do is we can we can so let's see when we Traverse the eight what what do we do with the AR so when we Traverse the array we have four in it then eight is greater then we add eight to it right okay and that's what we do then 8 coming to eight we can all uh we can go here here so everything is less than that then we we end up returning a result uh result back so we have four and8 um eight return returned back so so this guy goes to goes here 4 and at this point of time I believe the result is um 48 okay we are sending the same result to uh this guy right so that's why it is it is it is behaving that way yeah so in instead of instead yeah so in instead of instead of instead of instead of sending everything like this result of sending everything like this result is having the same reference right is having the same reference right [Music] so instead of sending this this way what what if we do this we spread this uh let's keep uh let's keep it so let's say we this guy returns something this guy returns something this guy return something to send the longest of these something to send the longest of these uh these uh these three so I'll just do it for more couple of more minutes let's left oh let top is equal to DFS let uh bottom is equal to DFS let left is equal to let let let let WR is equal to TFS so yeah we know that WR is equal to TFS so yeah we know that yeah we we want we know we want this so yeah we we want we know we want this so whatever is return back so this returns whatever is return back so this returns nothing turns nothing turns an empty an empty AR and this returns an empty AR and this returns an empty aray return an empty AR empty aray so aray return an empty AR empty aray so this guy once okay so let's go back to here so once okay so let's go back to here so this guy will return an empty array this this guy will return an empty array this guy return return an empty array this guy return return an empty array this guy eight guy eight then it goes here it goes here this then it goes here it goes here this returns an empty array to this guy this for rest I guess what we should be doing is we should uh be checking whose length is greater and send that fin so uh out of these four whose length is so uh out of these four whose length is greater we need to send that so how should we find out whose length so how should we find out whose length is greater like top dot length is equal to if it is greater than equal to if it bottom let's say equal bottom let's say equal to let's say greater than equal to to let's say greater than equal to bottom then top is equal bottom then top is equal [Music] [Music] to to and sorry and sorry bottom um and let let's call it AR AR and LR Mar is equal to and LR Mar is equal to to left do length is greater to left do length is greater than equal to right than equal to right dot dot length length then left then left or right and finally what we need and finally we need to check let [Music] to DP array. is greater than equal to lr. length question TV array or array and finally we need to send Max array and finally we need to send Max array is that okay yeah guess so and if array is that okay yeah guess so and if we run this now we shouldn't get OMG okay so SD out so let's see console log what console log to do do Bottom Dollar Bottom then Bottom then left then right right bottom oh sorry for for okay so I guess let's check it now so right returns nothing because yeah so right returns nothing because yeah so sending nine again nothing returns sending nine again nothing returns nothing nothing so top bottom left right returns nothing so top bottom left right returns nothing so bottom returns so bottom returns 48 and left returns so meaning of this is so meaning of this is that how can we send a you um just a value like this is rest right it 48 I don't want to send it anything other than that like rest rest okay okay so how can we do the thinking hello h okay guys after banging my head for okay guys after banging my head for several hours on this like uh we don't several hours on this like uh we don't have that much of have that much of time time um so yeah I guess uh we can see how um so yeah I guess uh we can see how this guy Sol this guy Sol it welcome back and let's write some it welcome back and let's write some more neat code today so today let's more neat code today so today let's solve the problem longest increasing solve the problem longest increasing path in a matrix and while this is a path in a matrix and while this is a hard problem I would definitely say it's hard problem I would definitely say it's one of the more doable hard problems one of the more doable hard problems there's nothing crazy involved but it is there's nothing crazy involved but it is somewhat difficult we're given an M byn somewhat difficult we're given an M byn Matrix that is filled with integers and Matrix that is filled with integers and the integers are going to be I believe the integers are going to be I believe zero or greater than zero so mostly zero or greater than zero so mostly positive integers and we want to return positive integers and we want to return the length of the longest increasing the length of the longest increasing path in this Matrix and we are allowed path in this Matrix and we are allowed to move only in four directions left to move only in four directions left right up or down we're not allowed to right up or down we're not allowed to move diagonally and of course we can't move diagonally and of course we can't go outside of the boundaries so let's go outside of the boundaries so let's just start with some observations first just start with some observations first of all this is an example and you can of all this is an example and you can see that this is the path that is the see that this is the path that is the longest it's of length four and it's in longest it's of length four and it's in increasing order obviously we can start increasing order obviously we can start with pretty much any value right and with pretty much any value right and pretty much starting at any position we pretty much starting at any position we can create a path of at least length one can create a path of at least length one right this is a path of length one this right this is a path of length one this is a path of length one uh but you know is a path of length one uh but you know starting from here then the next starting from here then the next position that we go to is a two it has position that we go to is a two it has to be greater than one which it is and to be greater than one which it is and then the next one is six that's greater then the next one is six that's greater and then nine that's also greater but and then nine that's also greater but from here uh we can't really go anywhere from here uh we can't really go anywhere else we allowed to move here uh but this else we allowed to move here uh but this one is not greater than nine it's just one is not greater than nine it's just exactly nine so that's the longest path exactly nine so that's the longest path now one thing you might be wondering is now one thing you might be wondering is can we you know reuse the same value can we you know reuse the same value multiple times right what if we have a multiple times right what if we have a loop of some kind well just think about loop of some kind well just think about it for a second if this is an increasing it for a second if this is an increasing path of course we can't reuse any values path of course we can't reuse any values because take a look at our path right because take a look at our path right you know the value that we get to is you know the value that we get to is going to be greater than all the going to be greater than all the previous values anyway so how could we previous values anyway so how could we possibly reuse any of the values in our possibly reuse any of the values in our path we're not allowed to now they don't path we're not allowed to now they don't state that in the problem statement but state that in the problem statement but that's an observation that you have to that's an observation that you have to make on your own and in this case you make on your own and in this case you know that's true and another observation know that's true and another observation we can make without even trying to we can make without even trying to understand you know what's the algorithm understand you know what's the algorithm we'd use for this problem just by we'd use for this problem just by looking at this example we can make a looking at this example we can make a very important observation and that is very important observation and that is that if this is the longest increasing that if this is the longest increasing path and it's of length four that means path and it's of length four that means the longest increasing path starting at the longest increasing path starting at this position is going to be of length this position is going to be of length four but what about the longest four but what about the longest increasing path starting at this increasing path starting at this position over here what is it going to position over here what is it going to be in this case we can see that there is be in this case we can see that there is a path right now starting from it uh a path right now starting from it uh that's increasing that's of that's increasing that's of length did you get a path increasing length did you get a path increasing path from path from two uh okay so ret send one on the top bottom okay so ret send one on the top bottom left left right why was 69 how come 69 and why not 69 how come 69 and why not one see I did I did messed up something one see I did I did messed up something um but yeah let's do this going to be um but yeah let's do this going to be larger than three of course not because larger than three of course not because if they're were wouldn't here it's one if they're were wouldn't here it's one because remember the solution to this because remember the solution to this problem and then I bet it will make problem and then I bet it will make sense now let's think about this what's sense now let's think about this what's the most basic Brute Force way that we the most basic Brute Force way that we could find the longest increasing path could find the longest increasing path well we could basically start at every well we could basically start at every single position and say maybe the single position and say maybe the longest increasing path will start here longest increasing path will start here maybe it'll start here maybe it'll start maybe it'll start here maybe it'll start here right who knows they don't tell us here right who knows they don't tell us where we have to start so we pretty much where we have to start so we pretty much have to try every single position that's have to try every single position that's the brute force and let's say we you the brute force and let's say we you know record that in a grid that's the know record that in a grid that's the same size as the grid grid we have here I'm G to call it Li for longest increasing path and once we do that once we filled up every value in here we can just take the maximum of them and then return that that'll be the length of the longest increasing path okay so for any particular position how do we find the longest length well the Brute Force again is just going to be a simple DFS I hope you're familiar with the DFS algorithm a pretty standard graph algorithm and you definitely will need it for hard level problems we're going to run a DFS starting from this uh position going in four directions right up down left right of course if we go out of bounds to the top or to the left or any other direction we're not going to continue There of course okay so we can't go out of bounds uh let's try going right starting from here are we allowed to go here well we have to compare the values right we have to look at this value is it greater than the previous value it's not greater than the previous value so we can't go here right we're not allowed to go there starting from here okay let's try going down that's the only position left that we have it's a six that's also not greater than nine so we can't go there either uh so we're pretty much uh not allowed to go anywhere so what's the length uh from here it's one because remember U one is basically like the default value we can always have a length of one starting at any position okay so we did that now let's go to the next position similarly we're not allowed to go in in any of the four directions because none of them have a greater value so we'll also put a one here okay now let's try the four and this is where things are going to get interesting so pay attention we can't go up we can't go to the right but we can go to the left uh and finally we see a value that's greater than the original 9 is greater than four so we are allowed to go here that's awesome uh but now uh we're doing DFS does that mean recursively we're going to run DFS on this position again well we don't have to because we already ran DFS on this position and we already found the longest increasing path starting from that position the length of it is one so we don't have to repeat that work because we stored the repeated work inside of this Matrix so we know that starting from four we can go to this nine and that's a path of length to that's at least one path that we can create okay we do have one more direction to try though we can from four we can go down to the eight we haven't ran DFS on this position yet so we're going to have to do that now DFS okay let's go to the right that's out of bounds okay let's go up should we even go up well in reality we shouldn't but if our algorithm is programmed to try going up it'll still work for us because of course we came from the four so we know that the value up above is less than eight so if we try going up it's not going to work anyway so it's okay to leave that in the code because it's not going to break anything so that's good for us because it keeps our DFS pretty simple okay now let's try going down we can't go down because one is less than 8 we want it to be greater than eight let's try going to the left okay six is also less than eight we want it to be greater than eight okay so we couldn't go anywhere but we'd still uh of the two paths both of them were the same length so we can put a two here uh starting from this position the longest increasing path is length to but did we do anything else well we started at the a we ran DFS from this position so not only did we determine that the the lip from here is two but we also determined that the lip from 8 is one because we couldn't go anywhere starting from eight are you starting to see how this algorithm itself even the DFS brute force is not inefficient because we're cashing the work we're storing the work in a Matrix so this isn't even a a Brute Force solution as long as you implement it correctly it's actually very efficient as long as we don't repeat the work so now when we we're not we're not quite at the eight yet right because we're going in order in our uh Matrix but once we get to the eight we'll know we already ran DFS on it and we won't have to repeat that work so now that you're probably starting to get the idea I'm going to start fast forwarding through this explanation so uh now let's run uh DFS starting from the six we try going left can't we try going right we can't we try going down we also can't do that we try going up okay we can do that and we know that we already computed the lip from here it's one so we can say the lip from starting at six is going to be two now let's go to the second six we can't go left it's less than six we can't go down it's also that this will be a path of length to we you know one from here so uh that's uh one Poss we have a tie position computed it so we don't repeat up over here it's l the two value that's which will be 1 plus we can't go down greater than 1 + 2 four + one so we're going to put a return four we don't actually have to return solution and it's pretty efficient but how do we know it's efficient what's the time complexity of course the memory complexity is big o n * m those are the dimensions of the Matrix because we're using extra space here but what's the time complexity it's also Big O of n * m just think about the intuition behind it let's say our Matrix was in such a way that when we ran DFS at the first position we you know had a path such like this and then we went here uh and then we went there then here then here then here basically we visit the entire Matrix in one DFS that's going to take Big O of n * m to run that DFS but the good thing about that is going to be after we've done that we're going to have computed every lip from every single position right and then when we visit the remainder uh remaining values of the Matrix each of those is going to be computed in Big O of one time so you know having done the repeated work at the beginning wasn't such a big deal because the remainder is going to be very easy or right let's say each of them was exactly two but we'd see that we can't go in any of the four directions so for each of these in that case as well the time complexity would be Big O of one which means the why this is an efficient solution um and with that being said let's finally jump into the code graph problems U Matrix problems in a very formul like way and I've done it put it in some going to need to know those Dimensions um in this case we're going to have hashmap because it's pretty easy to do that in Python we is basically going toing path now of course you could just use a two-dimensional Matrix if you're doing this in Java or whatever if you want and maybe I honestly should do that as well but I'm really really used to doing it this way because you can kind of just turn your brain off uh and next we're going to use uh DFS uh we have a function inside of a function so so we don't have to pass in every variable such as these three that I defined up above but we are going to pass in the position that we're currently visiting which ising order so we are going to pass in what the previous value ends up being and then with all uh you know graph traversals the first thing you want to check is did we go out of bounds uh is the row less than zero or is the row exactly equal to the number of rows which means it's too big um or same exact thing with the column is column Less Than Zero or is column equal to the number of columns because that means it's too big and the last condition in this case is going to be is the path not increasing how do we know that well the value that we're currently visiting which is the Matrix at the row column position is less than or equal to the previous value that means it's not increasing and if it's not increasing then we are just going to return we can return zero just to say that the increasing path was just zero Okay so so that's one base case and the second base case is a little bit easier that's if we already computed the lip at this position RC and if this and we know that because if this is in our DP hashmap as a key value then we can return whatever the length of it was that we computed cache cache so there we go okay now to actually so there we go okay now to actually compute the length we're just going to compute the length we're just going to call it result and initially set it to call it result and initially set it to one because we know it's at least going one because we know it's at least going to be one that's the minimum it could to be one that's the minimum it could possibly be and now we could use a loop possibly be and now we could use a loop to go through all four of the directions to go through all four of the directions but I don't think it's really necessary but I don't think it's really necessary we can just kind of copy and paste the we can just kind of copy and paste the same line like four times I prefer doing same line like four times I prefer doing that rather than doing a loop but you that rather than doing a loop but you can do what you prefer so one we know can do what you prefer so one we know we're going to uh run DFS right we're we're going to uh run DFS right we're going to run DFS on one of the going to run DFS on one of the neighboring positions one of them could neighboring positions one of them could be r + one uh and then the column is the be r + one uh and then the column is the same and what is going to be the same and what is going to be the previous value that we passed in of previous value that we passed in of course it's going to be the current course it's going to be the current value right now so row column and we value right now so row column and we only want to update the result if this only want to update the result if this is greater than the result so what we is greater than the result so what we want to do is set this equal or actually want to do is set this equal or actually uh this alone is not going to be the uh this alone is not going to be the length because this is going to tell us length because this is going to tell us the longest increasing path starting at the longest increasing path starting at row + one and if that's the case what we row + one and if that's the case what we actually want the length to be is from actually want the length to be is from this position that we're currently at so this position that we're currently at so we're going to take this and add one to we're going to take this and add one to it one plus that similar to how I was it one plus that similar to how I was doing it or I was talking about it in doing it or I was talking about it in the drawing explanation okay so once we the drawing explanation okay so once we have that then we want to take the max have that then we want to take the max of the current uh maximum result maximum of the current uh maximum result maximum length length and take this update the result if this is greater than the result so what we want want to do is set this equal or actually uh this alone is not going to be the length because this is going to tell us the longest increasing path starting at row + one and if that's the case what we actually want the length to be is from this position that we're currently at so we're going to take this and add one to it one plus that similar to how I was doing it or I was talking about it in the drawing explanation okay so once we have that then we want to take the max of the current uh maximum result maximum length and the max of this and then you know update it accordingly and this is where we copy and paste uh four times because we want to go in all four of the directions so r + one R minus one uh also column plus1 and column minus one okay and when we're done with that the last thing we have to do is now that we've actually computed the lip starting at this position we want to make sure to actually throw it into our DP cache so let's do that before before we end up returning so let's store that and then once we've stored it we can go ahead and return it so then the next time if we ever called DFS starting from the same position we'll end up returning it from our cach rather than redoing the DFS so that's where we're saving our time now that we've defined our DFS all that's left is to actually call it and remember we want to run DFS starting from pretty much every single position in the grid so we can do a nested for Loop to do that so go through every row go through every single column when we do that we also want to run DFS on every uh coordinate and what's the previous value that we're going to pass in for that well we know that every value in The Matrix is going to be uh Z or greater than zero so a default value we can pass in for the previous value uh is -1 because we never want this to return if we're looking at like the first value right and so if we pass in negative one Oh I thought we have to return an Oh I thought we have to return an AR AR okay okay got it got it comparison will never evaluate to True right none of these values is ever going to be less than negative one that's good so that's why we're doing it like this uh so once we've done that uh we're good to go the last thing we have to do is just return whatever the maximum was so we can just take our DP values which will return a list of all the values and just take the maximum of that now we probably don't need to do it like this like we could have just maintained another variable over here maybe have just called it lip longest increasing path and then just continuously updated it based on on the maximum that was returned uh you can do it however you want the time complexity is the same even though we're iterating over the entire you know Matrix again pretty much by doing this that's the idea let's just run this to make sure that it works and as you can see on the left yes it does work and it's about as efficient as you can get for this problem so I really hope that this was helpful if it was please like And supports okay so yeah uh let's try to solve this problem on our own and let's goes okay guys | 2024-03-24 10:39:00 | 329 | 329. Longest Increasing Path in a Matrix | Leetcode | Google |
|
Nfu-ubvJaZ0 | hey guys welcome back to another video and today we're going to be solving the leakout question kate missing positive number alright so this question is an easy question but i think it is a little bit more complicated than that so let's actually see how we can solve this question okay so before that so in this question we're given an array of positive integers sorted in a strictly increasing order so this over here is pretty important and we're also going to be given an integer k so our task over here is to find the k positive integer that is missing from the from this area so what exactly does this question mean let's just go over that real quickly and then we'll try to understand how we can exactly solve this question okay so over here this is going to be our array and we're also going to be given a k value and in this case uh let's see what they so they gave us a k value of five so this is the same as example one so what exactly is this question asking us for so in simple words the question is asking us for what is the fifth missing number which is not inside of our area so to actually understand what numbers that actually uh makes up of we'll try to have an array where there is no missing number so there's no missing number for uh we start off at the number one then we're gonna go to two three four five six seven eight nine ten and eleven so actually what would happen is that this would go all the way up to positive infinity okay so this over here is going to be all of the missing numbers now as it is it does not consist all the missing numbers because for example the number 2 does exist in our area so let's just clean up our area over here so one thing we could do for cleaning up our area is so we have the number two so we're gonna get rid of two where you have three get rid of three and four is also there so get rid of that as well and then seven and eleven so let's get rid of both of those as well seven and 11. okay so now these numbers over here 1 5 6 8 9 10 and from 10 every number to up to infinity is part of our missing numbers now in our question they're asking for the fifth missing numbers of numbers sorry so in that case that's gonna be so this is the first missing number second missing number third missing number fourth missing number and the nine over here is going to be our fifth missing number and this is what we're going to end up outputting which is the number nine so we'll try to see how we can actually solve this but hopefully you understood what the question is asking for and one more thing i do want to point out is this question over here the example two has the area one two three and four and we have a k value of 2. so if you look at this area as it is so we have the numbers one two three and four now as it is there is no missing number right so after one we have two after two there's three and after three there's four so there's really no missing number so in this case since there is no missing number before four then in that case the missing number is going to be everything after four so like i showed you earlier it's going to be so for example in this case we have 10 and everything all the way up to infinity so keeping that in mind the second missing number is going to be uh from 5 6 7 8 9 10 11 12 all the way to infinity so in this case they ask for the second one so that's gonna be five six the second one which is going to be the number six and we end up outputting that all right so hopefully you understood what the question is asking for but now let's see how exactly we could solve this question one way we could do this is going to be the same way that i kind of discussed the question as so what that means is basically we would kind of have a missing numbers array and using that we're going to find out what the missing number is so that's one way to do it but another way is we actually want to find some a solution with the best time complexity so in simple words we just want something which can we can get an answer through one pass and we also want something which does not take up extra space so how exactly could we do this so to do that one thing we can notice is that we're searching for the uh k positive integer right uh that is missing from this area so we are searching for something over here and another thing to notice is that we are our area is in a strictly a strictly increasing order so keeping that in mind both of those conditions mean that we could use a binary search to find our answer but now the question is what exactly are we searching for well we know we're finding the kth positive integer that is missing from the area but how exactly do we perform a binary search using these values over here right so using just the array how do we do a binary search so to kind of talk through or understand how we can do that i'm gonna go over here and show you how exactly we could do that so let's just get rid of this okay so to start off uh we have this area same area right so 2 3 4 7 and 11. now one thing i do want to kind of uh talk about is what is this area going to look like so how big is our area here the area has a length of one two three four and five so how is the area going to look like if we don't have any missing numbers okay so let me just write that down real quickly so if we have no missing numbers how is our area going to look like well that's going to be pretty simple the first number is going to be 1. the second number is going to be 2 and then 3 and then 4 and finally five so those are going to be our numbers if nothing is missing now technically uh this will go all the way up to infinity but just for the sake of simplicity simplicity i'm just gonna close it over here okay so this is how our area is going to look like when there are zero missing numbers okay okay so now that we have this let's talk about what we actually want to do using this information now our main goal is at a certain number so at a certain number we want to find out how many numbers are missing to the left of it so what does that mean a simple example is if you look at the number two to the left of the number two if everything was normal we would expect to see the number one but it's not there so in this case the number of numbers missing to the left of two is going to be one so at a certain number uh how many numbers are missing to the left of it okay and also one more thing i'm sorry my handwriting is pretty bad but anyway so let's just uh so kind of using this okay so this is what we want to calculate so at a certain number how many numbers are missing to the left of it so this is how we're actually going to end up calculating it and one more thing i'm going to do real quickly is i'm just going to write the index values of each of these numbers okay so now that we have this let's start off with the number two so at the number two how many numbers are missing to the left of it so in simple words uh if you just want to look at this and kind of think about it the answer is just going to be one because uh currently so at the number two so if you have a number two we would expect the number one to be on the left of it but it's not so in that case there would be one missing number over here now just talking so just thinking about it that like that won't be that easy especially for bigger numbers so is there any sort of way that we can find this out using math and the answer to that is yes so a simple way to do this is we have the number two and the number that is supposed to be in this position if there are no missing numbers is the number one so in this case to get the number of numbers missing to the left of two we can just do two minus one and two minus one gives us a value of one okay so let's just go on and you'll kind of understand how this works now we're gonna go over here and this over here is going to be our second number so the number over here is actually three but if there were no missing numbers the number that is supposed to be here is going to be the number two so using that we're going to do three minus two giving us a value of one so that's telling us that one number is missing to the left of three and that makes sense because to the left of three we would expect the numbers one and two and two already exists so the only other number is one so hopefully you can understand how this works i think it's pretty simple because over here we're supposed to have number two but we have a number which is greater than two by one so that is going to be the difference of the number of numbers missing to the left of it so now let's say we don't actually have this list over here how do we calculate the values then and that's pretty simple so the number that is supposed to be here is the same as its index plus one because so for example at four so the number which is actually there is four and this is the third number and how do we know that well it's pretty simple the index is at two so that means it's going to be two plus one which equals to three so it's going to be the third number and in other words the number that is supposed to be there if there's nothing missing is the value three so that's just going to be four minus three giving us one again so i'll just go through this real quickly and hopefully you didn't understand why why this actually ends up working now over here we will do seven minus four giving us three so that means there's three numbers missing to the left of seven and just to be really clear that's going to be the number one five and six those are the missing numbers and finally at five uh how many numbers are missing to the left of five well in this case is going to be 11 and this is the fifth number so 11 minus five which is nothing else but well six so that is going to be uh six perfect okay so now we found out how many numbers are missing to the left of a certain number now what exactly can we do with this so here is how we actually end up finding the answer so what's going to basically happen is we want to look for a number which is just greater than k so okay so just to make this a bit a little bit easier i'm going to just have a variable called x now what is x going to stand for so the x over here stands for the number of missing numbers okay so i have a variable x and x is going to represent the number of missing numbers to the left of a certain number so in this case the x value for 4 would be 3 the x value for sorry the x value for 7 would be 3 the x value for 11 would be 6 and so on and so forth okay so i'll just call this the variable x so it's easier to kind of talk about it but what exactly are we going to be doing here so our main goal is now going to become to find out the minimum value which is just greater than k okay i'll just repeat that one more time our goal is to find out the minimum value which is just greater than k so that could become the number six seven or whatever it is so how exactly are we doing that and more specifically why are we doing that so to understand that it's pretty simple so what does k represent here k is telling us that we want to find the fifth missing number so let's look at a simple example so let's say we go to one so sorry to the number four so to the left of 4 there's only one number missing and that doesn't really mean anything because we want to look for the fifth missing number we don't really care about the first missing number we just need the fifth missing number but now when you go to the number 11 there are six numbers missing to the left of it so that means that six numbers are missing to the left of it and out of the six numbers the fifth number is going to exist right we have six numbers and we just want the fifth one so that is actually important to us and we're going to use that information to kind of get our answer okay so this is basically our goal okay so in this case what is this x what is this going to be so the number that we're actually going to be searching for is going to be this over here so the number 11. so the minimum value which is just greater than 6. sorry than the k value right which is 5. so we got that as 11. okay so to get our answer now that we've got this in value 11 and we know it's at the fourth index so all we are going to be doing is we're going to do 4 plus k which is equal to our up which is going to be equal to our answer so in other words it's going to be 4 plus 5 which equals to 9 and that is the correct answer so uh to explain why exactly we're doing 4 plus k to get the final answer i'm just going to go through how this is going to look like in a binary search and one more thing i just want to mention is that we're doing a binary search to find the minimum value which is just greater than k okay so for our binary search we're going to have a left pointer and a right pointer and the middle uh to find the middle value we're just going to do the right pointer plus the left pointer divided by 2. so 4 plus 0 divided by 2 gives us a value of 2. so we're currently at the number 4 and to find the x value and again x is the number of numbers to the left of 4 which are missing so to do that is just going to be 4 minus 3 so that gives us a value of one and one is less than k so in that case we're going to move our pointers okay so uh where exactly are we gonna move them our left pointer is now gonna move to the right side and we're gonna move it to the middle value plus one so to do that we're going to do middle value which was here plus one so third index okay so now that we have this uh what we're gonna do is the same thing the middle value is gonna be four minus three so sorry four plus three which is seven and seven divided by 2 would be 3.5 but we're going to round down so we're going to go to the third index so we're going to go over here and this is the middle value that we're looking for so over here um we're going to do the same thing how many num what is the x value at 7 so the x value at seven is going to be seven minus four which is three and again three is less than five so we're going to move our left pointer to the right of the mid so that would be three plus one so our left pointer would be over here so we're gonna do the same thing and the middle pointer is gonna be over here at the same place so over here we're going to have a value of 11. so over here the x value at 11 is going to be 11 minus 5 which is going to be equal to 6. so since 6 over here is greater than 5 or the k value then in that case we're going to move our right pointer to the left so that means we're going to go one to the left of our middle pointer so four minus one so right is now going to be at the third index and uh left is going to stay as it is so at this point the left pointer has a value which is greater than the right pointer by value i mean uh index bytes right so this has a value of four this has a value of three so at this point we're going to end up stopping our binary search and we're going to be left out with these two values now the value that we're concerned with is going to be whatever is at the left pointer so in this case it's going to be the number 11 and one more thing i just want to write is that the x value at 11 is six so there's six numbers missing to the left of 11. so now to find our answer what we would be doing is we would be doing l plus k which in this case again would just be a four so l has a value of four not eleven it has a value of four okay so four plus 5 which equals 2 9. okay now how exactly did we come up with this formula over here okay so to kind of derive the simple formula of l plus k what we're basically doing over here is um we want to first find out how many values are to the left of of 11 in this case right and to do that what exactly did we do so in simple words what we did is we went to the value 11 itself so let me just write that so we went to array and i'll so the index is going to be the l index and we subtracted that by l plus one right so we first add up l plus one because that's the number that is supposed to be there and we subtracted it with that so in other words another way to write this the same thing we're distributing the negative sign around so it's going to be negative so minus l minus one okay so this is how we got the value six okay so let's just write that down and now what we want to find out is how many steps backwards do we need to take in order to get our fifth value over here and to do that what we're going to be doing is we have this over here and we're going to subtract this with our k value and we're going to add it by one so in this way of this value over here is six and the k value is five plus one so that means that we're taking two steps backwards to get to the value that we are looking for okay so this is what we have as it is and we can actually simply make a small simplification which is basically we have negative one year and plus one year which ends up getting cancelled okay so now this is what we have so we have area of l minus l plus k perfect now the question is we want to find out what that value exactly is and to get what that value actually is equal to what we're going to do is we're going to go to area l so in this case is the value 11. and the reason what we're basically doing over here so area l and we're going to subtract it with this value and the reason this actually works is because we know that whatever our value is is going to be less than 11. since we know the missing number is to the left of 11. so since we know it's gonna be less than 11 we're going to take this as the bigger value and we're going to subtract this and this basically what this is standing for is the number of steps we take backwards okay so this is the number of steps we take backwards and we're subtracting this with this okay so if you want to simplify this okay so one thing i do want to make a small correction so sorry about this so while i was copying the values this is actually supposed to be minus k you can just rewind a bit and look at it so this is actually supposed to be minus k okay so now keeping that in mind uh let's take this negative sign and spread it around so this is now going to become minus area l plus l plus k so in this case these two end up getting cancelled and all we're ended up with is l plus k which is nothing else but our final answer over here now let's see how we can code out the question which is pretty simple but hopefully you did understand this entire explanation i try to break it down into smaller parts and try to explain what is happening behind each step okay so now let's look at the code which is pretty simple okay so over here for our solution uh the first thing that we're just gonna have a quick check which is we're going to check if our k value is less than whatever is at the zero index and if that is the case we can just directly end up returning k so this is pretty simple and the basic idea is let's say our k value is so whatever sorry uh if whatever is at the zeroth index for our area has a value of 10. so that means everything to the left of it is not there it's missing right so the numbers one all the way through nine are missing so if our k value is with any of those numbers anything between one two nine in this case we can just directly return that k value so that is one thing that we could do and if that's not the case then well we're going to end up doing the bad research so for our binary search we're going to have a left pointer and a right pointer and the left pointer is going to start off at zero and the right pointer is going to start off at the length of our array minus one which is nothing else with the last index okay so now that we have this what we're going to do is we're going to go in our while loop and we're going to we're going to keep going while left is less than or equal to right so now we want to find out what the mid value is equal to so mid is going to be equal to l plus r divided by two and notice we're doing integer division so other than this um another way you could find out what the mid value is it's exactly the same thing but all it is is you're doing left plus right minus left so you're finding the difference between those two subtracted by two sorry divided by two and then you're going to add that to the left value okay so we have that for getting our mid value so now we want to do what we want to do is find out what the x value is and in other words the x value was nothing else but the number of missing numbers to the left of our certain whatever we currently are so to do that the formula was pretty simple which was our we go to whatever value is in the mid place so area mid and we're going to subtract that with our mid value plus one now the brackets over here is pretty important so we have our mid value plus one and that is basically nothing else but the value that is actually supposed to be there so another way to think about it is the index plus one so uh you could write it like this or if it's easier for you to understand you can remove the brackets and this would end up end up becoming negative but i think this is just a little bit easier because this is the example that i kind of talked about in the explanation so if sorry um okay so if this value over here is less than the k value then in that case we want to be looking for bigger values since that we want to look for bigger values we're going to move our left pointer to the right so that's just going to be mid plus 1. now if that is not the case what we're going to do is we're going to move our right pointer to the left so that's going to be r is equal to mid minus 1. so that should be it and at the very ending we're going to end up returning our l plus k okay so if you submit this it should get accepted okay so that should be it for our solution hopefully it did make sense and do let me know if you have any questions i'll try to answer them alright so thanks a lot for watching [Music] | 2024-03-21 11:40:07 | 1,539 | Kth Missing Positive Number | Leet code 1539 | Theory explained + Python code |
|
GI2N3mohm04 | hello everyone today we're going to be looking at three sum closest which is looking at three sum closest which is lead code problem number 16 this is a lead code problem number 16 this is a medium problem and it states given an medium problem and it states given an integer array nums of length n in an integer array nums of length n in an integer Target find three integers in integer Target find three integers in gnomes such that the sum is closest to gnomes such that the sum is closest to Target so return the sum of the three Target so return the sum of the three integers we don't need to return the integers we don't need to return the integers themselves just the integers themselves just the sum and the key word here is closest it sum and the key word here is closest it doesn't have to equal the Target it just doesn't have to equal the Target it just needs to be the closest to the Target needs to be the closest to the Target and we can assume that each input has and we can assume that each input has exactly one exactly one solution so if we look at the first solution so if we look at the first example here we see that nums isga 1 2 example here we see that nums isga 1 2 1g4 and the target is one so the output 1g4 and the target is one so the output is going to be two because according to is going to be two because according to the explanation here we have -1 + 2 + 1 the explanation here we have -1 + 2 + 1 = 2 so that's the closest we can get to = 2 so that's the closest we can get to the Target in the second example we have the Target in the second example we have three zeros so the closest we're going three zeros so the closest we're going to get there is just zero to get there is just zero so let's take a look at how we're going so let's take a look at how we're going to do this we're basically going to go to do this we're basically going to go through the entire array nums we're through the entire array nums we're going to start at position zero and going to start at position zero and we're going to have two pointers we're we're going to have two pointers we're going have a low pointer and a high going have a low pointer and a high pointer so we'll sign the low pointer pointer so we'll sign the low pointer equal to the next number in the sequence equal to the next number in the sequence next to the uh initial number and then next to the uh initial number and then we'll sign the high pointer equal to the we'll sign the high pointer equal to the last number in the last number in the array and then we'll just add those array and then we'll just add those three together so we got 6 -6 -3 + 5 is three together so we got 6 -6 -3 + 5 is equal to4 so4 will be our result current equal to4 so4 will be our result current result and the target we're trying to result and the target we're trying to get to is get to is zero when now4 is less than the target zero when now4 is less than the target so we're going to increment the so we're going to increment the low so now we've got -7 + 5 -2 so now low so now we've got -7 + 5 -2 so now we'll make the result or the difference we'll make the result or the difference equal -2 which is closer than -4 however equal -2 which is closer than -4 however that's still less than the target so that's still less than the target so we're going to increment the low again we're going to increment the low again and so now we've got -6 + 2 + 5 equal 1 and so now we've got -6 + 2 + 5 equal 1 so now one is greater than the target so so now one is greater than the target so we're going to we're going to decrease the high value of the high decrease the high value of the high pointer so now we have -6 was negative pointer so now we have -6 was negative 1 and the low and the high are now 1 and the low and the high are now adjacent to each other so we need to adjacent to each other so we need to basically increment the initial basically increment the initial pointer so now we're atg3 we'll sign the pointer so now we're atg3 we'll sign the low and high just like we did low and high just like we did before and then we got4 + 5 is 1 so B before and then we got4 + 5 is 1 so B remember we're just looking for the remember we're just looking for the smallest difference we don't care about smallest difference we don't care about the actual numbers that add up to that the actual numbers that add up to that difference so this doesn't change difference so this doesn't change because it's the same as it always was because it's the same as it always was even though one is also closest to the even though one is also closest to the Target and we're going to increase the Target and we're going to increase the low because the last result low because the last result was1 so now we have -3 + 2 negative 1 was1 so now we have -3 + 2 negative 1 plus so we have four so now we' have two plus so we have four so now we' have two high so we got four over here so we're high so we got four over here so we're going to decrement going to decrement the high and now we've got plus two the high and now we've got plus two which is still but because they're which is still but because they're adjacent we're just going to go on to adjacent we're just going to go on to the next one so initial pointer is going the next one so initial pointer is going to be at negative one you're starting to to be at negative one you're starting to get the idea here we got low and a high get the idea here we got low and a high and we'll see that is equal to six which and we'll see that is equal to six which is so now we got to decrement the is so now we got to decrement the high and we've got four high and we've got four and low and high are next to each other and low and high are next to each other so we can so we can increment one here so basically we've increment one here so basically we've we've come to the end we've come to the end because we've the initial poins at two because we've the initial poins at two and the low and the high are going to be and the low and the high are going to be three and five which are adjacent to three and five which are adjacent to each other so it doesn't there's there's each other so it doesn't there's there's no need to continue on that on that path no need to continue on that on that path so let's see how to code this so the so let's see how to code this so the first thing we need to do is create a first thing we need to do is create a variable to pass back so I'm going to variable to pass back so I'm going to create an create an int I'm going call it result and I'm int I'm going call it result and I'm going to make it equal to we're going to going to make it equal to we're going to start at pointer start at pointer zero so nums zero then we need to add zero so nums zero then we need to add the next number in the array which would the next number in the array which would be nums be nums one and then we're going to add the last one and then we're going to add the last number which is number which is nums nums length minus one those arrays are zero based and so that will be our initial result now we need to do a sort of that nums that we up here that we passed in and now we just need to start looping through like we did in the example so we'll do for in I equal z i is less than num's length now we're going to do minus two in this case because we've already taken care of length minus one so we don't want to um grab that number again so we do i++ all right now in here we need a few i++ all right now in here we need a few variables so now we're going to have our variables so now we're going to have our pointers so I'm make an an in start pointers so I'm make an an in start equals equals I + I + one then we can also do the n value here one then we can also do the n value here so n is going to be equal to do nums so n is going to be equal to do nums length minus one and these are the two length minus one and these are the two pointers that we're going to move um up pointers that we're going to move um up and down the array the low and the high all right so while start is less than the end we're going to do some stuff what are we going to do so first we need to add we need to create a variable called sum so this is going to keep track of the addition of the three numbers so we'll have nums I which is a pointer and then we're going to just add in nums start oops and nums end all right so now if that sum is end all right so now if that sum is greater than the greater than the target target then we need to decrement the N which then we need to decrement the N which moves the high pointer to the right moves the high pointer to the right which we saw in the example else we're which we saw in the example else we're going to increment the start by one going to increment the start by one start start Plus+ all right Plus+ all right now now we need to now now we need to compare the sum to the result so if compare the sum to the result so if we're going to do the math we're going to do the math absolute which will get the positive absolute which will get the positive values so sum values so sum minus minus Target okay if that is less than meaning Target okay if that is less than meaning it's closer to the Target math ABS it's closer to the Target math ABS result minus Target yeah okay then the result is just going to be equal to the sum assign some value to the result all right so now that we get out of this at the end we're just going to result and that is pretty much the result and that is pretty much the entire program so let's debug this real entire program so let's debug this real quick to see it an action okay I use quick to see it an action okay I use the first example 1 2 1 and -4 and a the first example 1 2 1 and -4 and a target of target of one so we'll start here okay result is3 one so we'll start here okay result is3 three we're going to sort the nums value three we're going to sort the nums value of the nums array and now we're just of the nums array and now we're just going to Loop through going to Loop through here so start will be equal to one and here so start will be equal to one and end will be equal to end will be equal to three all right so while start is less three all right so while start is less than end which is true in our case the than end which is true in our case the sum is equal nums of I which is going to sum is equal nums of I which is going to be the be the -4 plus the -1 plus the -4 plus the -1 plus the 2 so if sum is greater than Target which 2 so if sum is greater than Target which it it isn't so now we need to increment start isn't so now we need to increment start by by one now if if the sum minus Target is one now if if the sum minus Target is less than the result minus Target which less than the result minus Target which it isn't then we will it isn't then we will assign uh result equal the sum all right assign uh result equal the sum all right so so now we're going we moved the start now we're going we moved the start pointer so now we're just going to check pointer so now we're just going to check the numbers again and we see here what do we have start in so sum is NE 1 so we're going to increment the start and in this case the sum minus Target is greater than result minus Target which is one which is yeah result negative one okay so now result is ne1 and start is not less than n so basically the start and the end pointers right next to each other so we're going to break out of that while loop and now we're going to go uh in increment the initial pointer so now the initial pointer becomes one and start becomes two and end becomes three so this one will Loop through add those together the sum is two the sum is greater than the target which is one so we're going to decrement the end pointer in math ABS sum minus Target is less than result minus all right and now we've got a we're done all right and now we've got a we're done with that one because the start and end with that one because the start and end pointer are next to each other and that is it because we hit the yeah we would have put start up here and yeah there would have been too much overlapping or overlap so the result here is two so if we pass that back and that is our answer so let's hope I coded this right we'll run that it was accepted and then we'll submit it and better than 13 and 18 let's try it one more time sometimes I don't always trust well we're getting better 30 and uh memory usage is less than 36 so we'll run with that not the quickest self-explanatory all right now let's self-explanatory all right now let's look at the space and time complexity look at the space and time complexity for time complexity for time complexity assort of an array is n log of n but assort of an array is n log of n but because we're doing an nested for Loop because we're doing an nested for Loop we've got n squ so this actually we've got n squ so this actually trumps the N log in so the time trumps the N log in so the time complexity for this solution is uh Big O complexity for this solution is uh Big O n^2 and the space complexity is O of n n^2 and the space complexity is O of n so as you increase the input parameter so as you increase the input parameter the logic inside the solution will use the logic inside the solution will use more space and that is it so thank you more space and that is it so thank you for watching hope you learned something for watching hope you learned something and we'll see you next time | 2024-03-19 15:42:19 | 16 | [SOLVED!] 3Sum Closest - LeetCode 16 - Java |
|
boklNAqDe50 | [Music] hello everyone welcome to day 12 of hello everyone welcome to day 12 of march lead code challenge and i hope all march lead code challenge and i hope all of you are having a great time of you are having a great time even before jumping onto the details of even before jumping onto the details of today's question i would like to inform today's question i would like to inform all of you out there that today i am all of you out there that today i am going live it's gonna be the first the going live it's gonna be the first the second doubt clearing session along with second doubt clearing session along with this i'll be giving away a surprise this i'll be giving away a surprise amadron gift card to all those amadron gift card to all those developers who have been coding along developers who have been coding along with me on coding decoded repo with me on coding decoded repo it's gonna be a great surprise for all it's gonna be a great surprise for all of them so i want you to join me and of them so i want you to join me and encourage me be my support system this encourage me be my support system this time during this live session time during this live session now let's get back to the question now let's get back to the question today's question is copy list with today's question is copy list with random pointer here in this question we random pointer here in this question we are given a linked list that has two are given a linked list that has two nodes instead of one the next node and a nodes instead of one the next node and a random node random node what we need to do we need to create a what we need to do we need to create a deep copy deep copy of this linked list and return the head of this linked list and return the head of the newly created linked list of the newly created linked list to your surprise for all those who have to your surprise for all those who have been associated with the channel from a been associated with the channel from a long time must know that i have already long time must know that i have already solved this question in the month of solved this question in the month of february 10 2021 i'm attaching the link february 10 2021 i'm attaching the link in the description below do check this in the description below do check this video out and i hope you have a great video out and i hope you have a great time watching it up time watching it up also if you're interested in the linked also if you're interested in the linked list problems that we have sold so far list problems that we have sold so far these are 28 in number these are 28 in number and i'm attaching its link as well in and i'm attaching its link as well in the description below do give it a shot the description below do give it a shot i hope to see you soon in the evening i hope to see you soon in the evening take care good bye | 2024-03-21 12:20:19 | 138 | Copy List with Random Pointer | Leetcode 138 | Easy Linked List | Live coding session 🔥🔥 |
|
LdCf8bO7Mw8 | hi guys hope you're fine and doing well so today we will be discussing this so today we will be discussing this problem from the lead code which is problem from the lead code which is count number of teams count number of teams so this is the 19th problem of the so this is the 19th problem of the dynamic programming series dynamic programming series so if you haven't watched the previous so if you haven't watched the previous videos you can consider watching them videos you can consider watching them since it will be really helpful for you since it will be really helpful for you to understand the concepts in the to understand the concepts in the upcoming videos and in case you are new upcoming videos and in case you are new to this channel you can consider to this channel you can consider subscribing it and pressing the bell subscribing it and pressing the bell icon so that you don't miss any of the icon so that you don't miss any of the upcoming updates upcoming updates so let's start with this question so let's start with this question so the question states that there are n so the question states that there are n soldiers which are standing in a line soldiers which are standing in a line and each soldier is assigned a unique and each soldier is assigned a unique rating value rating value so we have to form a team of three so we have to form a team of three soldiers amongst any of them that are soldiers amongst any of them that are standing in the line standing in the line and the condition is and the condition is that for example we choose the ayat that for example we choose the ayat jaith and kf soldiers jaith and kf soldiers basically these are the indices of that basically these are the indices of that soldiers which are standing in a line soldiers which are standing in a line and the condition is that either and the condition is that either this i j k this i j k rating should be in increasing order rating should be in increasing order or in decreasing order or in decreasing order so these are the two conditions so these are the two conditions by which we can form a team and then we by which we can form a team and then we have to return the number of teams that have to return the number of teams that can be formed with the given condition can be formed with the given condition so let's have a look at this test case so let's have a look at this test case so the test case is so the test case is two two five five three three four four and one and one yes yes so if we clearly look that if we choose so if we clearly look that if we choose this two this two three three and four and four so they are in increasing order so this so they are in increasing order so this contributes to contributes to one one of the of the teams that can be formed teams that can be formed so the next can be so the next can be like like 5 4 and 1 because they are in decreasing order 5 4 and 1 and similarly the other can be this five three and one five three and one so if we clearly see that only these three are the possibilities that can be formed and these are the total teams that can be counted and as an answer so the answer for this test case is three so let's see like what can be the naive approach to approach this problem so just let me write it again 2 5 3 4 and 1. so the first thing that may come up to your mind is that since there are i j k so since there are only three members in the team so what we can do is we can simply apply three for loops nested three nested for loops these are the three nested for loops these are the three nested for loops and in these nested for loops what we and in these nested for loops what we can do is this is for the i starting can do is this is for the i starting from 0 from 0 and going up till n and going up till n and incrementing i this is j is equal to and incrementing i this is j is equal to i plus 1 i plus 1 and and what we are doing here is what we are doing here is that that j should be less than n j should be less than n and again j and again j plus plus plus plus and here also k is equal to j plus 1 and here also k is equal to j plus 1 j plus 1 yes j plus 1 yes and k is also less than n and k plus and k is also less than n and k plus plus plus so now here we can simply put this if so now here we can simply put this if condition we can also create a count condition we can also create a count variable outside it variable outside it count variable is equal to 0 count variable is equal to 0 and we can just simply put this and we can just simply put this condition that rating of i should be condition that rating of i should be less than rating of j less than rating of j should be less than rating of should be less than rating of k so in case this is the condition then k so in case this is the condition then also count plus plus otherwise that rating of otherwise that rating of i should be greater than rating of i should be greater than rating of j should be greater than rating of j should be greater than rating of k k so basically it is not i j k but yes so basically it is not i j k but yes rating of rating of let it be our array let it be our array so that is how so that is how this will be done on all these so this this will be done on all these so this is one of the things that that can be is one of the things that that can be done and we can simply return and simply return so so if we do this approach if we do this approach so let's see what is the problem with so let's see what is the problem with this approach so let's have a look at this approach so let's have a look at the constraints of this problem the constraints of this problem so if we clearly see that the value of so if we clearly see that the value of and basically the length of this and basically the length of this array which is the rating value array which is the rating value is of the form is of the form 10 to the power 10 to the power 3 in the worst case 3 in the worst case and if we clearly say here and if we clearly say here that the time complexity for this that the time complexity for this algorithm is algorithm is of the form of the form n cube n cube so if we apply this to here it comes out so if we apply this to here it comes out to be 10 to the power 9 operations to be 10 to the power 9 operations since we know that we can only do since we know that we can only do approximately 10 to the power eight approximately 10 to the power eight operations approximately operations approximately in one second in one second so this is definitely gonna give time so this is definitely gonna give time limit excuse me to us limit excuse me to us so this approach should not be opted for so this approach should not be opted for but in case the constraints would have but in case the constraints would have been low like of the form 10 to the been low like of the form 10 to the power 2 power 2 then this could have been done then this could have been done with this algorithm so now let's see with this algorithm so now let's see like how can we optimize our approach like how can we optimize our approach so before moving to the optimal approach so before moving to the optimal approach let's see let's see what part of the algorithm what part of the algorithm is just creating time limit exceeded and is just creating time limit exceeded and how can we how can we just eliminate that just eliminate that so firstly let's consider we are given so firstly let's consider we are given this array let me just create it like like seven seven and and five five so here we are given so here we are given six 8 six 8 3 3 1 1 and again 7 yes and again 7 yes so so according to that algorithm let's say i according to that algorithm let's say i is this is this j is this yes which is this and this k will obviously range from this index to this index right so let's take out the total number of teams that are possible with this i and j firstly if this is the k then is it possible to form the team no so if this is the k then also it is not possible if this is the k yes it is possible because 7 is greatest 5 is lower than 7 and three is again lower than five so yes this is possible so first possibility is seven five and three so the next possibility is if we move to 1 so yes this is also possible 7 5 and 1 and if we move on to this 7 like is it possible let me just write it again yes let me just write it again yes so this is also not possible so with i so this is also not possible so with i referring to the seventh value and j referring to the seventh value and j referring to this five value referring to this five value so the total number of teams that can be so the total number of teams that can be formed with formed with k k varying from this range to this ranges varying from this range to this ranges basically basically only only two values two values so if we clearly see that so if we clearly see that what it is actually indicating is what it is actually indicating is that the total number of values here that the total number of values here in this range which are basically less in this range which are basically less than five than five so so why do we need to iterate over it again why do we need to iterate over it again and again and again what i am trying to say is what i am trying to say is let's see it in another way let's see it in another way like we have been iterating over all the like we have been iterating over all the indices for this particular i and j indices for this particular i and j if rather i would had a value like 2 if rather i would had a value like 2 which depicts the total number of which depicts the total number of values to the right of this j values to the right of this j which are basically less than this value which are basically less than this value of the jth index of the jth index if i got that i would have just if i got that i would have just received my answer for this j received my answer for this j but if my now j is changed to but if my now j is changed to let's say yes now my j is changed to this now what will i do is according to the algorithm what i have been doing is i would have again iterated over this range and found out whether this value is less than j or or not so in this case if we see that the answer for this should be if we can simply calculate the total number of values to the right of this value six which are less than six it should be basically three not three two again two three and one so this would have also contributed to only two answers so my aim should be not to just iterate over all this range again and again with that k which creates an extra for loop but my focus should be on like how to get that the total number of indices whose value is less than this jth value in just o of one time so if i can do that my algorithm will be reduced to o of n square because the last and that we were applying for k will now just give me answer in o of 1 so this is how we can reduce our algorithm so now let's have a look at a test case and understand that how can this be so let let me just write the test case so let let me just write the test case and which is 25341 two five three four and one so what will i do is i'll create an array which will tell me the total number of values which are less than a particular index let's see how can we create that yes so if i am standing at this index the total number of values that are less than this index to the right of it are none basically so no use of it it will simply be zero and if i am standing at this index the total number of values to the right of this index which are strictly less than this four value is only one so the total count is one and now if i move to three third index then total number of values to the right of this will be i will be iterating over all these values like whether 4 is less than 3 no whether 1 is less than 3 yes it is so i'll just put value and if i move to 5 now i'll again and if i move to 5 now i'll again iterate over all these indices and find iterate over all these indices and find out whether this value is less than 5 or out whether this value is less than 5 or not since this value is less than 5 it not since this value is less than 5 it will become 2 1 now this is also less will become 2 1 now this is also less than 5 this is also less than 5 so total than 5 this is also less than 5 so total is is 3 and if i move to this two total number of values i'll again move to five then to three then to four and then to one so out of all these values i find out that the total number of values that are less than two is only one so let's write down one here and it should be three so to make this array let's call this array uh dp array yes let's call this a dpis so after creating this array we realize that the total number of time total time it takes is was just n square how often square like if we stand i will be this index and we will be iterating over j to find out the total number of indices which are less than this value so this is how it will take just o of n square time and similarly what we'll do is let's call this at dp1 and the next thing that we will do is two five three four one we'll create another array and what does this mean is and what does this mean is now now we were just seeing to the right like we were just seeing to the right like what our values are less than to the what our values are less than to the right of it now for each index we will right of it now for each index we will also see the total number of values like also see the total number of values like if we are at 4 if we are at 4 then we will see the total number of then we will see the total number of values that are less than 4 and left values that are less than 4 and left left side left side right so let's start iterating over it right so let's start iterating over it so if we are standing at this 2 the so if we are standing at this 2 the total number of values that are left total number of values that are left less than 2 less than 2 to the left of it is only 0 because to the left of it is only 0 because there are no values to the left of it there are no values to the left of it and if we are standing at this 5 and if we are standing at this 5 so total number of values less than 5 is so total number of values less than 5 is only 1 only 1 which is which is this this this 2 yes so for 3 it will come out to be 1 for 4 it will come out to be these two values so for four it is two one it is again zero so we have got two arrays basically dp1 and dp2 so dp1 says that total number of values to the right of that particular element which are less than particular index that we are standing on and the dp2 says that the total number of indices whose value is less than the particular index that we are standing on to the left side so this is what the both of them mean now what we need to do is since we are given this 2 5 3 4 1 as our original array now we simply need to apply two for loops which is from i is equal to zero to i less than n to i plus plus and the for loop is for i not i yes j is equal to i plus 1 and j is less than n and j plus plus so this is the second for loop and the if condition that will be put here is if basically r of i is less than r of j so we know that i is less than j then we should also find the total number of maximum value values that are greater than r of j to the right of the array and for the right of the error it is the dp1 array so we will for this case we will simply d p one of d p one of j j dp one off dp one off let me just yes dp one of j let me just yes dp one of j so dp1 of j just suggests that total so dp1 of j just suggests that total number of values that are greater than number of values that are greater than r of j to the right of it r of j to the right of it so if this is the j so if this is the j and let this be and let this be i i this is i this is j the total number of this is i this is j the total number of values to the right of this j is only values to the right of this j is only one this is this one one this is this one so this is what so this is what we will increment our count to we will we will increment our count to we will simply create a count variable before simply create a count variable before this for loops this for loops and and initialize it with zero so similarly we will create another for loop for the descending part which is this was the ascending order which is r of i is less than r of j is less than r of k this these two for loops are for this ascending order similarly we will apply another two for loops for the descending order which is r of i is greater than r of j is greater than r of k so if we clearly see that for one part which is ascending order it just takes two for loops so the time complexity here is o of n square and for this part also it will be o of n square for creating this dp1 array it is of n square and for dp2 is also of n square so in total the time complexity of this algorithm is o of n square so which can be done in one second so since the total number of not total number of the maximum value of n can be 10 to the power 3 so in the worst case this algorithm will be of 10 to the power 6 operations which can be done in one second and after applying these two for loops the count so now let's have a look at how can we code this problem so firstly let me just create this let me just change this name of the arrow to r and now what will i do is i'll simply create dp1 array of size n and dp to array of size n let me initialize this n as r dot length and now i'll create a count variable which is equal to zero and now for i is equal to zero i is less and now similarly for the and now similarly for the j j one j is equal to one j is equal to i plus i plus one one and j is less than n and j is less than n and j plus plus and j plus plus what will i do is what will i do is so i will simply put if r of i so i will simply put if r of i is greater than r of j is greater than r of j then then dp1 of dp1 of i i plus plus and what will i do in another for loop is i'll start from i equal to 0 as less than n and i plus plus now from end j equal to 0 and j is less than i and j plus plus so here i will do the same if r of i is greater than r of j so again i will just write dp2 of i plus plus and now for this particular dp1 i'll repeat this for loop and i'll simply increment count plus equal to dp of dp1 of j and just repeat count of count plus equal to dp 2 of and i will simply return and i will simply return count count so let's see if this is running so let's see if this is running you see it is running correctly you see it is running correctly so now let's try to submit this question yes it is getting accepted so i hope you understood solution in this video and if you have any doubts you can comment down below i'll be more than happy to answer them and if you appreciate my work you can consider subscribing to my channel and giving thumbs up to this video so let's meet in the next video till | 2024-03-21 01:04:33 | 1,395 | 19. Count Number of Teams | Dynamic Programming Series | LeetCode Medium 1395 |