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
|
---|---|---|---|---|---|
rlx9WrDxMSY | alright guys welcome back to make challenge challenge 2022 the default so max number of k sub pairs we are giving an integer array numbers and an integer k in one operation you can pick two numbers from the array whose sum equals k and remove them from the array return the maximum number of operation you can perform on array so for example one we have one two three four k equal to five we have here one plus four is equal to five so we remove one and four from the array and now we have just this array two plus three is also equal to five so we have two numbers one plus four and two plus three so the output is two okay for the example two we have three one three four three and k equal to six three plus three is equal to six so we have one operation and here we have this number one four and three we cannot make any sum any true sum with this numbers equal to six so the output is just one okay to solve this problem let's do it with a let's make our lives equal to zero and let's make our lives equal to zero and writes equal to the length of writes equal to the length of numbers minus one numbers minus one and we use also a counter now while our and we use also a counter now while our left is smaller than the right left is smaller than the right let's make let's make mid equal to just the numbers mid equal to just the numbers of of numbers numbers of of l l plus numbers of error plus numbers of error and let's check if our midi equal and let's check if our midi equal to okay to okay if it is if it is so so let's let's make one's required to let's let's make one's required to counter plus one counter plus one and let's update the left by one okay let's supply plus one okay okay l if l if our mid is bigger than k our mid is bigger than k in this case let's update the writer in this case let's update the writer and else let's update the left okay let's make our code so beautiful finally let's return our counter yep let's run the code i hope it work the time complexity is analog to n because we are we are sourced at the right and it's some bits yeah it's work so i hope this video was useful for you i'll see you soon | 2024-03-20 11:13:58 | 1,679 | 1679. Max Number of K-Sum Pairs | LeetCode Mai Challenge Day 4/31 |
|
cqZ_z3cwvkE | hey hey everybody this is Larry this is 2/5 tear to chew in the coach and let's 2/5 tear to chew in the coach and let's get started hit the like button hit the get started hit the like button hit the subscribe button let me know what you subscribe button let me know what you think random pick with weight giving it think random pick with weight giving it a way of a weight W a positive integers a way of a weight W a positive integers where weight W sub I is the rate of where weight W sub I is the rate of index I write a function pick index index I write a function pick index which random effects an index in which random effects an index in proportion to its way okay I guess proportion to its way okay I guess that's what it's kind of hard to ought that's what it's kind of hard to ought to check that's the home is just a to check that's the home is just a random character but so the first thing random character but so the first thing I would say is given that women Python I would say is given that women Python there is actual Python my library that there is actual Python my library that does this not gonna get into it because does this not gonna get into it because you know you're probably watching this you know you're probably watching this video not so that if we're like Larry video not so that if we're like Larry tell me which library of in Python to tell me which library of in Python to use for this very specific form right use for this very specific form right but yeah let's kind of think about it I but yeah let's kind of think about it I think that's a couple of clever ways to think that's a couple of clever ways to do this there's actually something call do this there's actually something call so core best of all sampling that you so core best of all sampling that you can play around with so then actually can play around with so then actually you could get it done or one space I you could get it done or one space I would have to put to be honest I would would have to put to be honest I would have to prove fair from scratch I have have to prove fair from scratch I have vague ideas of it but I'm not gonna do vague ideas of it but I'm not gonna do that now definitely you know leave a that now definitely you know leave a link below do your Google research link below do your Google research Wikipedia learn about that and play Wikipedia learn about that and play around that idea I think it's a very around that idea I think it's a very cool idea and you could prove it on your cool idea and you could prove it on your spare time - it's actually not that spare time - it's actually not that difficult per se in theory but that's it difficult per se in theory but that's it I'm just going to do it probably one of I'm just going to do it probably one of the ways that I would do it and the idea the ways that I would do it and the idea is just well forget wait let's calculate is just well forget wait let's calculate the prefix sum and then roll a number the prefix sum and then roll a number between 0 to the some maybe some minus 1 between 0 to the some maybe some minus 1 but and then just kind of you could do a but and then just kind of you could do a binary search to see which a rate that binary search to see which a rate that you get into because if you look at the you get into because if you look at the prefix um it's gonna be monotonically prefix um it's gonna be monotonically increasing and then we have a number you increasing and then we have a number you have to find the root the bucket in have to find the root the bucket in which which that that number is on that number is that that number is on that number is the first bucket that is there's some the first bucket that is there's some the prefix sum is smaller than just the prefix sum is smaller than just random number right okay let's go like random number right okay let's go like that does that kind of make sense that does that kind of make sense because but idea behind this is that because but idea behind this is that okay the idea is that I set you up some okay the idea is that I set you up some weight okay well just boy is useless but weight okay well just boy is useless but let's just say random numbers or not let's just say random numbers or not random numbers but like random - Larry random numbers but like random - Larry generated numbers something like this generated numbers something like this right not given that random enough but right not given that random enough but then now you do the prefix um do you then now you do the prefix um do you want now you pick a random number I mean want now you pick a random number I mean I guess technically does it say well I guess technically does it say well prefix some between zero and dirty one prefix some between zero and dirty one and I doubt that will allow you to kind and I doubt that will allow you to kind of figure it out where which bucket to of figure it out where which bucket to fall into so in this case this actually fall into so in this case this actually matches up with this because fum and the matches up with this because fum and the 31 is kind of implicit you don't need to 31 is kind of implicit you don't need to actually create that prefix some that actually create that prefix some that way but the idea is that okay how many way but the idea is that okay how many numbers are between two adjacent numbers numbers are between two adjacent numbers right well the numbers between two right well the numbers between two adjacent numbers by default because adjacent numbers by default because we're prefix sum is the rate that we're we're prefix sum is the rate that we're giving and then out so then in that case giving and then out so then in that case and then now you take the sum of the and then now you take the sum of the entire away which is actually just the entire away which is actually just the last number because it is a prefix um last number because it is a prefix um that's the definition of prefix um so that's the definition of prefix um so then that means that one or the first then that means that one or the first away will give you one over the sum we away will give you one over the sum we just went over 31 the Delta here would just went over 31 the Delta here would be 5 over 31 10 over 31 and so forth be 5 over 31 10 over 31 and so forth right so that's kind of the idea of how right so that's kind of the idea of how you do it and as you can tell because it you do it and as you can tell because it is a prefix um with positive numbers is a prefix um with positive numbers it's going to be monotonically it's going to be monotonically increasing which means we can binary increasing which means we can binary search so let's do that search so let's do that so let's initialize this weightless so so let's initialize this weightless so yeah so that's just to our self that yeah so that's just to our self that prefix that you call W so we name this prefix that you call W so we name this W in great soft are prefixed our W in great soft are prefixed our apparent rate plus self dot prefix the apparent rate plus self dot prefix the last element so did they say what this last element so did they say what this is doing is just just takes last element is doing is just just takes last element and then adds it to the current element and then adds it to the current element just a way of writing prefix I'm not a just a way of writing prefix I'm not a big to you and then pick index so is it big to you and then pick index so is it just like pick a random one okay just like pick a random one okay and then uh oh that's also good I guess and then uh oh that's also good I guess the sum is you go to yeah we good the sum is you go to yeah we good I just want this to be a little bit more I just want this to be a little bit more explicit though again this is a very explicit though again this is a very obvious thing in that word and prefix um obvious thing in that word and prefix um sometimes the entire way just last sometimes the entire way just last element right now let's pick a random element right now let's pick a random number from zero to self that song no number from zero to self that song no don't remember how to do random in don't remember how to do random in Python so let me look it up anthem very Python so let me look it up anthem very quickly I think it just random dog ran quickly I think it just random dog ran or something random dog ran didn't [Music] all right then take a cup of random okay yeah I think this is good I could okay yeah I think this is good I could be wall and all five one okay I'm just be wall and all five one okay I'm just leaving the syntax right now for random leaving the syntax right now for random random here's what I'm reading in cage random here's what I'm reading in cage what we did with me and again this is what we did with me and again this is what I was talking about you can do what I was talking about you can do random that choice of random touch random that choice of random touch without literally the answer with two of without literally the answer with two of to rate the cumulative rates are again to rate the cumulative rates are again prefix sums but I mean you know that prefix sums but I mean you know that gives the point of no but if you do it gives the point of no but if you do it this way but I me a little bit I mean this way but I me a little bit I mean you should especially for an interview you should especially for an interview you should do this but of course on a you should do this but of course on a competitive programming then maybe you competitive programming then maybe you just use two random that choice and just use two random that choice and that's fine but yeah so I'm I think when that's fine but yeah so I'm I think when a brain should be okay so let's just say a brain should be okay so let's just say number is you maybe okay and then now number is you maybe okay and then now let's binary search so that's just how I let's binary search so that's just how I write it but feel free to you know why write it but feel free to you know why did your own way so to and if so did your own way so to and if so basically what do we one what this is basically what do we one what this is the prefix some let's say we find eight the prefix some let's say we find eight well we want it to be six so basically well we want it to be six so basically if we're in the middle and we want to if we're in the middle and we want to find eight then this actually just means find eight then this actually just means that if this is it just a smaller then that if this is it just a smaller then what does this mean that means that yeah what does this mean that means that yeah all the numbers before are smaller so we all the numbers before are smaller so we actually just want this side given that actually just want this side given that this is smaller so that means that head this is smaller so that means that head has to would move to the middle so okay has to would move to the middle so okay so if self dot prefix MIT is greater so if self dot prefix MIT is greater than or equal to number than or equal to number then we move head to me else now let's then we move head to me else now let's not say given another one that's right not say given another one that's right here and this is bigger well then we here and this is bigger well then we know that cannot be 16 and we wanted to know that cannot be 16 and we wanted to the left so now we want to tell to be the left so now we want to tell to be men hmm it's me double-checking that men hmm it's me double-checking that this is correct this is correct it's a little bit off because this will it's a little bit off because this will never converge what we want because the never converge what we want because the tail is just saying this but then tail is just saying this but then because we never moved to here so if because we never moved to here so if head and tail is equal to one so then we head and tail is equal to one so then we have to add one here so that we double have to add one here so that we double check okay and then now we should be check okay and then now we should be okay with returning head as doing index okay with returning head as doing index once that's happens once that's happens that's let's put in some test cases No that's right I mean I still I don't way we have to fix it but oh I guess this could actually let's see if this is this maybe I mean it's quite it not ok let's maybe I mean it's quite it not ok let's debug this real quick because it goes from wall and to that this would never terminate right yeah binary search off by once a tricky so we have to make sure that uh that were okay that's what may give us a time limit but that means that it's just well it's but that means that it's just well it's just that if this is the case ten that doesn't seem very random there now this is returning the biggest thing in either case what is that what is what am i printing with number well what am i grand amine with number you presume oh hmm I guess this never goes to zero hmm I guess this never goes to zero because of the past one but two dozen because of the past one but two dozen mackenz inside so we test one of two it's not meant to be inclusive that's what I'm trying to think well that's why we do tell us a because they definitely should not be because they definitely should not be worried elements in the second input I know it should because it's they were I know it should because it's they were okay but the civil number doesn't there okay but the civil number doesn't there should be just minus 1 but it's toshin it's now reducing one no that's not true oh I'm doing something funky so now again you get to see Larry debug binary search which is always one of my weaknesses because I get these rid off by one cases as I'm oh so okay so now he's trying to find a number between 0 to 4 not inclusive it finds there's the that's on test lips really need to label that's on test lips really need to label my debugging is less confusing okay so for four it was a one so it should be just gives me a see well assume it is to improve isn't prefix of two should be yeah the number is 3 or the prefix this yeah the number is 3 or the prefix this is bigger did I get the signs well is bigger did I get the signs well probably put it back saying yeah it's probably put it back saying yeah it's okay okay so if this prefix know that say we wrote so if this prefix know that say we wrote a 17 then we want to move then we want a 17 then we want to move then we want to move to set here right now that's why to move to set here right now that's why it should be right anyway let's say we it should be right anyway let's say we rewrote it three and we see it too we rewrote it three and we see it too we should move ahead to - except for that should move ahead to - except for that this is not true because if this is a 2 this is not true because if this is a 2 then this should be true which means then this should be true which means tail should be too and yet somehow we tail should be too and yet somehow we return now how can we never pick a tail then am I missing something but two is the last element right so if but two is the last element right so if two prefixes today did I really actually two prefixes today did I really actually just get to sign one yeah I did cuz I just get to sign one yeah I did cuz I but I keep on saying is that is just me but I keep on saying is that is just me being silly then and somehow for these being silly then and somehow for these kind of problems you really have to kind of problems you really have to think about what you're asking and I you think about what you're asking and I you know I said it a few times out loud and know I said it a few times out loud and you're watching the video you might be you're watching the video you might be like Larry what are you they were and like Larry what are you they were and you said the explanation cuz I remember you said the explanation cuz I remember saying like if it's 18 10 this is bigger saying like if it's 18 10 this is bigger than this number which is this number is than this number which is this number is bigger than this number okay bigger than this number okay I don't know what that's okay as far as I don't know what that's okay as far as we eventually right okay this looks we eventually right okay this looks excuse me excuse me this has recorded live so we might have might not head it out that out but uh excuse me but yeah okay so the thing with this form is that it is a little bit random so we don't you can't really tell how how this is gonna be true even though we did you know get it you find you but it does look like it has you know distributions in a good way and that and you know in that like you get a mix of both which is not good enough for randomness and this one for mmm it's hard to say right mmm it's hard to say right I mean expected answers just whatever we okay so I'm gonna submit this but but the poem is that so the problem with these things is that it is hard to test for random things that gives you randomness and for that reason it because it's very easy to get buyers so definitely use a random library to do the things that you want to do during sampling and shuffling and all that stuff because you're very likely to get it wrong in a library at least you're in the same bar everyone else so because it's very hard to get it exactly why there might be some viruses like you know off by ones or something like that we would mean that's our numbers just never get picked I wonder and I to be honest I'm not super confident this one but it seems like at these four this one or the numbers to get picked or able to get picked I mean it takes a little bit of luck cuz but 0 2 & 3 so you know that goes from zero and it and it could pick a four so it knows that you could do the entire range so that's how it gets me a little bit more confidence I know for example maybe we could do something like this and then you it should be all fours I mean you might still again get unlucky obviously but you know probabilistically way so anyway so yeah that's all I have for this problem for interviewing the first thing I would mention maybe just like hey this was in the real world I would definitely use a library because randomness is hard in on an in or a on a competitive program in contest I would just do it way specifically like I'll just use this library without really thinking about it and be like a next problem but yeah that's what I have with this one hope you enjoy me watching debugging turns out so yeah so just be careful my my lesson here is just be careful with the signs but I hope that binary search is hard right for me especially and even at this point actually wasn't a binary search for is just me sing out loud I'm even saying out loud I was saying the right things out loud but my I converted to the wrong code right but but I think the thing that I would say is that I actually got order order plus one and stuff correctly and the reason how I do it I would like to focus on that because as I mentioned before there's a lot of focus is up for binary search with memorizing these patterns and like look if this is this do this and there's this pattern for it right and it's so cool and then you have to memorize every and for me it's just I don't have enough brain cells anymore I'm getting old I don't I can remember all this stuff so for me is about first point to Boeing a binary search and being like okay let's say head and tail let's say middle of this right and for me I don't do invariant and figure it out we're like okay let's take it let's say we vote a number and it's 10 if its 10th we want decide on this side or this side inclusive or exclusive and everything right and for me I wanted to keep their invariant that the tail is exclusive and from that it leads to this where you know the tail is exclusive right so we move it to mail when it's not possible to be here so we want this side for example and then that means that here will never converge because that's just already let's go so the middle has to be a plus 1 so that in theory both head and tail can move you know freely the entire range and then from that also because in that case head would never be go to tail so then we do this head plus 1 as you go to tear and then at the way n I did head in theory sometimes they could be head plus 1 depending on what you do it but again it all goes by the question of asking yourself okay you know I have this visualization I'm checking the number in the middle or whatever it is in the middle is it on the left sound in the right side and you bind every search and you do it divide and conquer and you do recursively quite equal and that's how you do a binary search anyway it's it's it's an okay problem it's a known problem so it's okay Fred I hope you enjoyed I hope you liked it hope you enjoyed watching me struggle and the like button to subscribe boy now see ya | 2024-03-22 16:49:11 | 528 | 528. Random Pick with Weight (python) - Day 5/30 Leetcode June Challenge |
|
xVnmzIqndd0 | through the code SQL questions just in preparation for interviews I thought I'd preparation for interviews I thought I'd upload them in case it helps anyone else upload them in case it helps anyone else out in their kind of preparation for out in their kind of preparation for similar things so we're doing one 1683 similar things so we're doing one 1683 invalid tweets invalid tweets so we have a table tweets we have column so we have a table tweets we have column ID tweet ID and content ID tweet ID and content as our column headers as our column headers and let's see and let's see one is end far char so we have tweet IDs the primary key and they want us to write a solution to find the IDS of the invalid tweets the Tweet is invalid if the number of characters used in the content of the Tweet is strictly greater than 15. return the result table in any order the result format uh okay so uh okay so we're just looking for length we don't we're just looking for length we don't even care about what it says or anything even care about what it says or anything like that we're looking for returning to because it's longer is greater than 15 and we know strictly greater so we're not not equal either and we're outputting the Tweet ID all right so it's pretty straightforward I need another easy one so we're going tweet ID from the table tweets tweets all right and then where we want the value and the content column okay so we need the length we need to get the length of the varchar content and we want it where it's greater than 15. and there you go correct result this text is greater than 15. so we put it as the Tweet ID or we output it under tweet ID so same column name okay I'll get a lot quicker at these but I'm going to keep going through them if you're interested in just following all the SQL problems for | 2024-03-20 12:10:07 | 1,683 | LEETCODE #1683 SQL |
|
bCn1CTteTbo | back to helgi karina and today we are back with another very interesting back with another very interesting problem on lead code which is the number problem on lead code which is the number complement complement now if you see that this this problem now if you see that this this problem has been tagged as an easy problem and i has been tagged as an easy problem and i do agree with it because it has a very do agree with it because it has a very easy and a very simple kind of a easy and a very simple kind of a solution along with it so why i want to solution along with it so why i want to touch this problem is because it kind of touch this problem is because it kind of this problem kind of covers a very basic this problem kind of covers a very basic and very important uh you know few of and very important uh you know few of the concepts related to bitwise the concepts related to bitwise operations which would be very very operations which would be very very useful when you go on and touch some of useful when you go on and touch some of the very very hard problems uh related the very very hard problems uh related to bitwise operations to bitwise operations so so let's let's start going through this let's let's start going through this problem so uh it says that the problem so uh it says that the complement of an integer is an integer complement of an integer is an integer which you get when you flip all the which you get when you flip all the zeros to ones and all the ones to zeros zeros to ones and all the ones to zeros and its binary representation so and its binary representation so here it gives an example where you know here it gives an example where you know the binary representation of 5 is 101 the binary representation of 5 is 101 and and the complement that you get after the complement that you get after converting once to zeros and zeros to converting once to zeros and zeros to one is basically zero one zero which is one is basically zero one zero which is basically the binary representation of basically the binary representation of two so uh you know the decimal number two so uh you know the decimal number which was input is five and the which was input is five and the complement binary representation is you complement binary representation is you know uh one zero which is like the know uh one zero which is like the binary representation of the decimal binary representation of the decimal number two number two so you have been given a basically a so you have been given a basically a decimal number you have to find its decimal number you have to find its number complement so let's see how we number complement so let's see how we can do it so we are going to discuss two possible solution uh for this problem uh let's so in the first solution like we are so in the first solution like we are going to do exactly what the problem going to do exactly what the problem statements say that is first we are statements say that is first we are going to convert the number to its uh going to convert the number to its uh you know binary representation then we you know binary representation then we will replace all the ones with zeros and will replace all the ones with zeros and zeros with ones in this binary zeros with ones in this binary representation representation and then we are going to convert back and then we are going to convert back the binary representation to uh decimal the binary representation to uh decimal representation that is if we take the representation that is if we take the prior example we will first convert 5 prior example we will first convert 5 into into 1 0 1 1 0 1 and in the next step you know we are and in the next step you know we are going to replace its zeros with once and going to replace its zeros with once and once zeros that's when we are going to once zeros that's when we are going to get 0 1 0 get 0 1 0 and then you know we are going to and then you know we are going to convert back that 0 1 0 into a decimal convert back that 0 1 0 into a decimal representation which is 2 representation which is 2 so so let's see how let's take some examples let's see how let's take some examples and let's see how we can do this so let's take a few of the examples and see how first of all we can convert a decimal number into its binary representation so let's start with 5 so how we do it is basically you know we will continuously keep on dividing it by 2 and you know keep on saving its remainder so we divide 5 by 2 we get 2 remainder is 1 then we again divide two by two uh you know remainder is uh zero and you know again we divide one by two uh you know remainder is one so we see over here the you know binary representation is uh one zero and 1 so 1 0 1 let's try another number let's say 9 ah so 9 again we divide by 2 we get 4 over here remainder is 1 then again we divide 4 by 2 we get 2 over here remainder is 0 then again you know this and yeah so we get like 1 0 0 1 over here right so you know we we just keep the remainders in reverse order and we put it over here one goes here zero goes here again zero goes here and one goes here so yeah this is how we convert the numbers into their you know binary representation now the next ask was that we can we do uh like you see the step two it was basically replacing all the zeros with ones and ones with zeros so let's do it one by one so for five uh we had we we got like one zero one so when we convert once to zeros and zeros to one we get zero one zero and similarly for nine uh you know we got one zero zero one and we convert once to zeros and zeros to one we get like 0 1 1 0 right so so basically this is kind of the what we have got till now is basically a binary representation of complement of these numbers right which were originally given to us so we move to the third step which is basically converting the binary representations back to the decimal representations so how do we do the you know reverse thing that is conversion of binary to decimal we kind of maintain the indexes of the of the individual binary digits like this is two this is one this is zero and then similarly this is three two one zero so then we kind of multiply by the powers of the two so uh 2 raised to the power 2 multiplied by 0 that is you know 2 raised to the power index of 2 and then multiplied by you know the digit present over here plus you know 2 raised to the power 1 multiplied by the digit present over here and then similarly you know 2 raised to power 0 multiplied by the digit present over here which is 0 so this takes us to you know 0 plus 2 plus 0 which is again equivalent to 2 so what we get from this is like the complement of 5 is 2 basically for what we did was first we tried to find the binary representation of 5 which was 101 then we you know just uh you know converted once to 0 0's to 1 which is like you know uh 0 1 0 and then what we did was we just converted back 0 1 0 back to its decimal format by multiplying by the index powers of 2 so 2 raised to power 2 into 0 plus 2 raised to the power 1 into 1 plus 2 raised to the power 0 into 0 which takes us to 2 now similarly let's try it for 9 in the similar way we are going to do is 2 raised to the power 3 multiplied by 0 plus 2 raised to the power 2 multiplied by 1 plus 2 raised to power 1 multiplied by 1 plus 2 raised to the power 0 multiplied by 0 which takes us to 0 plus 4 plus 2 plus 0 which is like 6 and like basically 6 will be our answer for 9's complement so it's exactly the same way we can you know we did it for uh you know five we can do it for nine and similarly we can do it for any other number so basically this is one uh possible solution we can opt for we can easily code the solution all we need to you know we just need to follow this simple algorithm to you know solve this problem but before we jump into the you know coding the solution uh i would like to discuss another possible solution another one tricky solution but which is much easier to quote now uh before we jump into this solution uh let's discuss about another very important uh you know concept and bitwise operation which is zor so uh what zor says is that let's say we want to find the zor of two numbers which is let's say five and nine uh how we find the zor is basically uh you know we represent it by their uh uh you know binary representation like we already saw that the binary representation of five is one zero one and we saw that the binary representation of 9 is basically uh 1 0 0 1 so how we find the zoro of it is basically uh whenever the two digits that we see you know over and above each other uh which are same we put 0 over there and whenever we see 2 digits which are like different we put 1 over there so if we see like 1 and 1 they are same so we put 0 over here 0 and 0 these are also same we put 0 over here and 0 and 1 these are different so we put 1 over here right so so this is how we calculate the zor and then again like we did before we can easily convert right so what we are going to do is 2 right so what we are going to do is 2 raise to the power 3 multiplied by 1 raise to the power 3 multiplied by 1 plus 2 raised to power 2 multiplied by 1 plus 2 raised to power 2 multiplied by 1 plus 2 raised to the power 1 multiplied plus 2 raised to the power 1 multiplied by 0 plus 2 raised to the power 0 by 0 plus 2 raised to the power 0 multiplied by 0 which takes us to 8 plus multiplied by 0 which takes us to 8 plus 4 plus 0 plus 0 which is like 4 plus 0 plus 0 which is like 8 plus 4 is equal to 12 so basically 0 8 plus 4 is equal to 12 so basically 0 of 5 and 9 becomes 12 of 5 and 9 becomes 12 so this is how so this is how we uh we find zoro of two numbers now we uh we find zoro of two numbers now there is one very interesting property there is one very interesting property about zoro is that whenever we take the about zoro is that whenever we take the zor of any of the digits with one right zor of any of the digits with one right the the it automatically you know that the the it automatically you know that reverses the digit like if we take 0 of reverses the digit like if we take 0 of 1 with 1 1 with 1 we are going to get 0 but and if we take we are going to get 0 but and if we take 0 of 1 with 0 we are going to get 0 of 1 with 0 we are going to get 1 over here so if you see 1 over here so if you see it maps it maps 1 to 0 and it maps 1 to 0 and it maps 0 to 1 so 0 to 1 so if we have a binary representation of a if we have a binary representation of a number number right and we take right and we take 0 of it with all the ones right so what 0 of it with all the ones right so what it should it should do is basically reverse all those digits do is basically reverse all those digits like uh we take zoro one with one it it like uh we take zoro one with one it it gives us one gives us one zero with one it gives us uh basically zero with one it gives us uh basically uh one and we take one with one it will uh one and we take one with one it will give us uh you know zero so basically give us uh you know zero so basically what it is doing is that if if if we do what it is doing is that if if if we do a zor of a number with all the ones we a zor of a number with all the ones we are going to get our desired complement are going to get our desired complement of that number basically because one has of that number basically because one has the property that whenever you take a the property that whenever you take a saw of one with any other digit it will saw of one with any other digit it will always give you the reverse of that always give you the reverse of that digit so basically we can utilize this digit so basically we can utilize this property to find the zoro of the number property to find the zoro of the number so let's look at this algorithm so let's look at this algorithm how we can do this is basically find the how we can do this is basically find the number of digits in the given number number of digits in the given number find the number s is equal to 2 raised find the number s is equal to 2 raised to the power x minus 1 now why we talk to the power x minus 1 now why we talk about 2 raise to power x minus 1 about 2 raise to power x minus 1 uh let's say you know 5 has had like uh let's say you know 5 has had like three digits in three digits in three binary digits with it so 2 raised three binary digits with it so 2 raised to the power 3 minus 1 to the power 3 minus 1 uh which takes us to uh uh which takes us to uh you know 2 raised to the power 3 is 8 you know 2 raised to the power 3 is 8 minus 1 which is 7 so so we get 7 over minus 1 which is 7 so so we get 7 over here right and what is 7 what is the here right and what is 7 what is the binary representation of 7 binary representation of 7 it is it is one one and again one so so basically it is one one one which is the which is basically the the the combination of ones we need for uh you know finding the complement in case of a three digit number three digit binary number basically so that's why what we are going to do is that we are going to find find a number which is 2 raised to power x minus 1. uh then what we are going to do is basically find s or n where s is the number 2 raised to power x minus 1 and you know and basically n was the original number given to you so basically what we need to do is find 5s or 7 which will gives give us 2 which is the you know intended answer for us now let's take a look at the code for so in the solution over here we are just so in the solution over here we are just going to represent the three steps that going to represent the three steps that we just discussed in the form of a code we just discussed in the form of a code so uh the first step was basically so uh the first step was basically counting the number of binary digits counting the number of binary digits that are there in the number so we that are there in the number so we already saw like when we were converting already saw like when we were converting uh you know 5 and 9 into the uh you know 5 and 9 into the corresponding binary representation we corresponding binary representation we continuously kept on dividing them by continuously kept on dividing them by two and you know two and you know maintaining the remainder so what we maintaining the remainder so what we need to do over here we will just we need to do over here we will just we don't need the remainders for us what we don't need the remainders for us what we just need is basically the digit count just need is basically the digit count so uh we'll keep on dividing the number so uh we'll keep on dividing the number by two and you know incrementing the by two and you know incrementing the digit count by uh one digit count by uh one and till the point the number doesn't and till the point the number doesn't reach zero so uh yeah we'll keep on reach zero so uh yeah we'll keep on doing that and at the end of the day uh doing that and at the end of the day uh you know the ditch variable is going to you know the ditch variable is going to have the number of binary digits that have the number of binary digits that are there in the number are there in the number so so in case of five after you know running in case of five after you know running till uh this point we are going to have till uh this point we are going to have you know this value equivalent to uh you know this value equivalent to uh three three so so now the next step was finding 2 so so now the next step was finding 2 raised to the power x raised to the power x minus 1 minus 1 so so uh for that what we are going to do is uh for that what we are going to do is that basically you know we are going to that basically you know we are going to do a math dot power of 2 comma digit do a math dot power of 2 comma digit minus 1 minus 1 uh which is going to give us the you uh which is going to give us the you know the required know the required required number with which we should required number with which we should take the zor of take the zor of the given number so in case of uh you the given number so in case of uh you know 5 what we what will happen is that know 5 what we what will happen is that digit count is 3 so 2 raised to the digit count is 3 so 2 raised to the power 3 which gives us 8 8 minus 1 is 7 power 3 which gives us 8 8 minus 1 is 7 so you know uh so you know uh math dot power minus 1 over here is math dot power minus 1 over here is going to give us 7 and then we are going going to give us 7 and then we are going to take our number to take our number with this number with this number so so 5 0 7 so this will return us you know 5 0 7 so this will return us you know two as the answer which is uh which we two as the answer which is uh which we can see over here so basically yeah this can see over here so basically yeah this is basically an accepted solution on is basically an accepted solution on lead code for this problem and thanks lead code for this problem and thanks for watching this video for watching this video thank you | 2024-03-22 15:24:38 | 476 | Leetcode 476 | Number Complement | BitWise | XOR |
|
3vtaXg17kfY | okay so let's solve another lead code problem uh this is one one nine nine problem uh this is one one nine nine four uh tournament winners so we are four uh tournament winners so we are given two tables one is the Players given two tables one is the Players another is the matches okay in the another is the matches okay in the player uh player ID and uh which group player uh player ID and uh which group that particular player belongs to so that particular player belongs to so player ID is uh primarily in this uh player ID is uh primarily in this uh table and another table matches where table and another table matches where the match ID is given and first player the match ID is given and first player and second player and their respective and second player and their respective scores are given in that uh paper so scores are given in that uh paper so let's see the table structures so here let's see the table structures so here you can see it's already straightforward you can see it's already straightforward all the player IDs and the properties all the player IDs and the properties are given here in the match ID tape the are given here in the match ID tape the matches table the match ad is there the matches table the match ad is there the first player and second player and their first player and second player and their respective scores okay so what we have respective scores okay so what we have to find that for each group which is the to find that for each group which is the highest scoring player and if both two highest scoring player and if both two of the players have same score then we of the players have same score then we have to show the player whose player ID have to show the player whose player ID is lower okay so that's the problem is lower okay so that's the problem statement let's now find out how it is statement let's now find out how it is working so player ID 15 it's given in working so player ID 15 it's given in group id1 so in group id1 we have group id1 so in group id1 we have four players right 15 25 30 45 so for 15 four players right 15 25 30 45 so for 15 the score is 3 the score is 3 and also 15 appeared as a second player and also 15 appeared as a second player here the score is zero so total score of here the score is zero so total score of player 15 is 3. for 25 let's give us the player 15 is 3. for 25 let's give us the score it is 2 and there is no other so score it is 2 and there is no other so the total score is two so still 15 is the total score is two so still 15 is highest so for 30 what is the score one highest so for 30 what is the score one and also two the total is three so 30 and also two the total is three so 30 also has total score 3 but 15 has the also has total score 3 but 15 has the lower ID that's why 15 is still uh will lower ID that's why 15 is still uh will be number one and for 45 uh we don't be number one and for 45 uh we don't have 45 here it is 0 so that's why from have 45 here it is 0 so that's why from group ID 1 group ID 1 clear ID 15 is coming so similarly uh we clear ID 15 is coming so similarly uh we can calculate for the other side we can can calculate for the other side we can say it here okay so let's go to the say it here okay so let's go to the coding and see how we can so here uh let me uh first here uh create all the tables and insert the records and then you will go to the the first thing what we have to find out the first thing what we have to find out is that this is that this place first plane and second player we place first plane and second player we have to combine their value right so we have to combine their value right so we need we'll create one temporary table need we'll create one temporary table with the first pair another with the with the first pair another with the second player and we will sum up their second player and we will sum up their scores scores so that would be our first step so that would be our first step so let's do that so this is what we are getting this is pretty straightforward right so after we have that we will sum up the value and so what do you mean by this you're summing up the first score you're summing up the first score now we are doing a group by so we are getting 15 20 in this one right now we have to find out the rank of each and every player so how can we your chest your chest it's the rank so we are using the group it's the rank so we are using the group ID uh so group ID will use from another ID uh so group ID will use from another table so let's table so let's use the cable to join so here with this particular people okay our inner table which uh we just see we will join with the players table based on the player ID we are joining with the player ID okay and once you have that we'll have the group ID player total score and then based on rank we are based on the group by ID and partitioning with the group by ID and we are ordering it with the total score and the player ID as well so let's see how it will look like so now we have this value so for group id1 we have layer 15 and total is called S3 and rank is 1 right so for 30 the rank is 2 because it is also ordered by the player ID as well now all you have to do is to find out and the rank one from this table select and we need the players let's give it an alias as all right so one is here in 235 and 3 is 14. so this is what the expected result so thanks for watching this I'll catch | 2024-03-25 18:07:45 | 1,194 | LeetCode 1194 |
|
zIEdV_jQcZY | hi guys welcome back to the channel eat cod and sleep and today's Le code cod and sleep and today's Le code problem will be Implement Q using stack problem will be Implement Q using stack so so let us see what are the companies so so let us see what are the companies ask this question here and we can see ask this question here and we can see all the Fang companies have asked this all the Fang companies have asked this question so this is a very important question so this is a very important question we need to solve here and we question we need to solve here and we need to understand it okay so let us need to understand it okay so let us quickly dive into the problem here so so quickly dive into the problem here so so uh as we can see here the problem uh as we can see here the problem statement is statement is so Implement a first in first out fif Q so Implement a first in first out fif Q using only two stacks the implemented Q using only two stacks the implemented Q should support all the functions of a should support all the functions of a normal Q okay so we need to implement a normal Q okay so we need to implement a que using two stacks here okay so it que using two stacks here okay so it should also support all the should also support all the functionalities of Q here okay so now functionalities of Q here okay so now what so what are all the functionalities what so what are all the functionalities we need to implement here we need to we need to implement here we need to implement the push functionality pop implement the push functionality pop functionality Peak functionality and the functionality Peak functionality and the empty functionality here so these are empty functionality here so these are the functions and we need to implement the functions and we need to implement here so let us quickly check how we can here so let us quickly check how we can Implement uh Q using two stacks here Implement uh Q using two stacks here okay so uh as a question says we need we okay so uh as a question says we need we require two stacks here so I will init I require two stacks here so I will init I will initially initialize my stacks in will initially initialize my stacks in the here and in the Constructor so the the here and in the Constructor so the class attributes have two stacks here class attributes have two stacks here right so the class attributes are two right so the class attributes are two stacks here so and the Constructor has stacks here so and the Constructor has the initialization of the attributes the initialization of the attributes here right so I will be initializing the here right so I will be initializing the two stacks here in this the Constructor two stacks here in this the Constructor in this Constructor so coming to the in this Constructor so coming to the push functionality so the two stacks are push functionality so the two stacks are now let us see let now let us see let us why we why so what is the first stack us why we why so what is the first stack and second stack here the first stack and second stack here the first stack will be the main stack here okay that will be the main stack here okay that will be the main stack and the second will be the main stack and the second stack will be the auxiliary stack okay stack will be the auxiliary stack okay that will be using that will be using for that will be using for many purposes for that will be using for many purposes okay and this is a S1 is a main stack okay and this is a S1 is a main stack and S2 is a auxiliary stack okay so let and S2 is a auxiliary stack okay so let us us quickly quickly implement the push quickly quickly implement the push function here function here so before so before pushing uh so before pushing so let us pushing uh so before pushing so let us visualize what is a q here okay A Q is a visualize what is a q here okay A Q is a data structure which stores data structure which stores the which stores a different types of the which stores a different types of data right so uh so so we can add data right so uh so so we can add elements from so in a q data structure elements from so in a q data structure it has two openings okay first uh from it has two openings okay first uh from the first from the from the first and the first from the from the first and from the last okay so whatever the from the last okay so whatever the element we need to push we we will be element we need to push we we will be pushing it from the last year and pushing it from the last year and whatever the element we will be uh so if whatever the element we will be uh so if we consider this as starting starting we consider this as starting starting starting and this as an ending so starting and this as an ending so whatever the element we need to push we whatever the element we need to push we need to push it from the last year okay need to push it from the last year okay so if at all we need to push six year we so if at all we need to push six year we need to push it from the uh last here so need to push it from the uh last here so this is the functionality of Q here okay so this is the functionality of q q data structure and whatever the uh element we need to pop it out so we need whenever we need to remove one element from Q we will be removing from the starting here so from starting we will be removing and from last we will be pushing it so this is the functionalities of Stack here okay functionalities of Q here so let us visualize what is stack here what are the functionalities of Stack so whatever the so it will in stack there will be only one opening here okay it will be from the last okay so whatever the element we need to push we'll be pushing it from the last only and whatever the element we need to remove we'll be removing it from last only okay so whatever the element we need to remove and whatever the element we need to push it will be removed from last only right so there is as as there is only one opening so we need to implement these Q function using two stacks here okay so we need to implement Q data structure using two data stres that are Stacks here okay so now let us quickly uh see how we can Implement push function here so what is push function in what is push function in Q here uh push function is pushing the element from the last so uh in the Q also we are we will be pushing the element from the last and in the stack also you'll be pushing it from the last one right so the push functionality will be same for stack and Q here so I'll be pushing my elements into my main stack here okay that will be S1 so I will directly push into my S1 main stack here so now let us quickly understand what is how we can Implement pop function here so now to implement pop function so in q in Q data sector what is pop we can what is pop the remove function right so in at what from where we can remove the element from the starting right but in Q where we can remove from the last right so as so for removing the first element in the Q data structure we'll be uh removing directly uh this ring right so but removing one element in the stack data structure we need to remove 6 5 4 3 2 1 right so we need to remove all the elements from the stack right to remove the first element of the stack right so but in the queue uh we can only we can directly remove it from the remove it from the first opening right so uh by using Stacks how we can implement the pop function here so here what I will do is I'll be transferring my all the elements to my auxilary stack here okay so uh so uh I'll be transferring my all the elements from uh from my main function to main stack to auxilary stack so my auxilary stack looks like in this way right so now from my auxiliary stat whatever the element I pop it out it will be the first element of the main stack right right so now we can pop it out right so now we can pop it out the first element so in this way I'll be implementing my pop function right so now let us quickly observe the code here so what am I doing I'm I'm first of all transferring all the elements from main function to auxilary function right auxilary stack so this is the fun this is the while loop for transferring the transferring all elements from Main to auxilary here and whatever the last element will be the last element in the auxilary stack that will be the first element right so I'll be popping out and I'll be storing it in a variable right now after after doing this operation what I need to do I need to again transfer my all elements from my auxilary stack to main stack here so now I'll be transferring all the auxilary elements to the main stack so I'll be again transferring my so this is a while loop for transferring all the elements from auxilary to main stack here so this is and at last I'll will be returning a here which is the starting element right so in this way I'll be applying the pop operation so and Peak operation is also same as Pop operation but here we will be removing it from the data structure but we will be just getting the uh getting the last element right getting the last element here so in the pop also what we are doing we are we we were transferring so in Q what will be the peak here that will be the starting element right so for getting St for getting the starting element in stack what we need to do we need to transfer it to auxilary and whatever the last element of auxiliary that will be the starting element of main right so in this way we can get the starting element of starting element of Stack right so the same same functionality of Po we'll be transferring all the main elements to main elements to auxilary and from auxilary we need to find the peak here so in STI in stack what will be the peak that will be the last element right so it will be the last element which will be the first element of Q here right and after after finding the peak we need to transfer all the auxilary elements to main main stack so I'll be transferring all the auxilary elements to main stack here so so this is how I'll be performing the peak operation here and the last thing is empty operation empty functional so what is empty whether we need to check our Q is empty or not in Q in Q data what is empty whether it is empty whether it has elements or it has no elements so in stack also we have same kind of data s like that is main stack right so we'll check whether our main stack is empty or not right so same functional so whether it is empty then it will return true if it is empty whether it is not empty then it will return false right same and coming to the time complexities of these functionalities so it will so for stack it will be obviously uh big of one constant constant space right constant time complexity right big of one only for pushing the element into stack so well so for pushing the element into the tack it will be like from last we will be pushing it right so it will be big of only right and for popping it out we need to transfer all the elements from M to auxilary right so this this while loop uh this while loop takes big of and operation right so the pop functionality time complexity will be big of n here okay and for Peak also it will be big of n only right as we are transferring all the elements to from Main to auxilary right so this is also will be big of n operation only and at last for checking m stack uh that will be uh constant time complexity only right so for checking whether our Q is empty or not uh we need we we need only big off one operation right so and the space complexity of this problem is and as we are using two stacks here so it will be 2 into big of N and so we can we can take it to Big offen only right so the space complexity will be big offen and overall space time complexity will be big often here okay so this is how we'll be solving this problem here uh like implementing Q data structure using two stacks here and thank you for watching this video And you | 2024-03-22 11:19:40 | 232 | 232. Implement Queue using Stacks | STACKS & QUEUE | POTD | DAILY LeetCode Problem | EASY | |
|
oOYrmlGYoKw | hey guys welcome to a new video in today's video we're going to look at a today's video we're going to look at a lead code problem and the problem's name lead code problem and the problem's name is largest substring between two equal is largest substring between two equal characters so in this question we given characters so in this question we given a string s we have to return the length a string s we have to return the length of the longest substring between two of the longest substring between two equal characters excluding the two equal characters excluding the two characters if there is no such substring characters if there is no such substring we have to return return minus one as we have to return return minus one as output and by definition a substring is output and by definition a substring is a continuous sequence of characters a continuous sequence of characters within a string now let's take these within a string now let's take these three examples and see how we can solve three examples and see how we can solve this question so in this example there this question so in this example there are two characters a and a this is at are two characters a and a this is at zero and this is at one and there is no zero and this is at one and there is no substring between them so Zer is the substring between them so Zer is the output here in this case you can see a output here in this case you can see a is appearing here and a is appearing at is appearing here and a is appearing at the last index so first index is at zero the last index so first index is at zero second index is at three and there are second index is at three and there are two characters in between so you return two characters in between so you return two as the output so how are you getting two as the output so how are you getting two is Right index three minus left two is Right index three minus left index 0 - 1 is equal to 2 so answer is 2 index 0 - 1 is equal to 2 so answer is 2 and in this case there is no common and in this case there is no common characters so we return minus one as the characters so we return minus one as the output according to the conditions now output according to the conditions now let's take this example and see how we let's take this example and see how we are getting the output so if You observe are getting the output so if You observe these three examples you finding for the these three examples you finding for the leftmost index and the rightmost index leftmost index and the rightmost index of a common character so we need to keep of a common character so we need to keep track of the left and right index and track of the left and right index and then find the characters between them so then find the characters between them so to keep track of the characters between to keep track of the characters between them I'm using a hashmap to fill the them I'm using a hashmap to fill the hash map I'm iterating through the input hash map I'm iterating through the input string from left to right and let me string from left to right and let me create the hashmap so I is initially create the hashmap so I is initially pointing at the zero index we check if pointing at the zero index we check if that character is present inside the map that character is present inside the map or not no it's not present so add it as or not no it's not present so add it as the character and add its index index is the character and add its index index is zero Now we move I further so inside the zero Now we move I further so inside the values we're going to keep adding the values we're going to keep adding the leftmost index of the character and as leftmost index of the character and as you as you find a match so I will be the you as you find a match so I will be the rightmost index and you have the rightmost index and you have the leftmost index in the map and then leftmost index in the map and then you'll find the difference between them you'll find the difference between them I also create a variable Max and set it I also create a variable Max and set it to minus one which will be our output to minus one which will be our output because there might be multiple because there might be multiple occurrences of leftmost and rightmost occurrences of leftmost and rightmost indexes we have to find the longest indexes we have to find the longest distance because we need to return the distance because we need to return the maximum length of the substring between maximum length of the substring between the two matching characters we check if the two matching characters we check if B is present inside the map no so add B B is present inside the map no so add B and add its index index is one now we and add its index index is one now we move I further I is equal to 2 we check move I further I is equal to 2 we check if it is present inside the map yes so if it is present inside the map yes so get its leftmost index and calculate the get its leftmost index and calculate the length length is equal to like I said length length is equal to like I said right minus left minus 1 so right is 2 I right minus left minus 1 so right is 2 I is 2 left is 0 minus 1 so you get one as is 2 left is 0 minus 1 so you get one as the output the output and update it with Max Max is minus one and update it with Max Max is minus one and update the current max out of them and update the current max out of them one is Max so this is the max subring one is Max so this is the max subring now move I further now I is here I is now move I further now I is here I is equal to 3 check if the character is equal to 3 check if the character is present inside the map yes it is present present inside the map yes it is present and this is the leftmost index so and this is the leftmost index so calculate the distance between them calculate the distance between them right is equal to I 3 and left is equal right is equal to I 3 and left is equal to the value present inside the map to the value present inside the map which is 0o and minus one so you get two which is 0o and minus one so you get two and update it with Max Max is current and update it with Max Max is current Max comma length so you compare it with Max comma length so you compare it with two current Max is two now move I two current Max is two now move I further I is pointing at further I is pointing at 4 check if it is present inside the map 4 check if it is present inside the map yes it is present so calculate the yes it is present so calculate the distance right is equal to 4 and left is distance right is equal to 4 and left is the value in the map so 1 - 1 = 2 and the value in the map so 1 - 1 = 2 and update the max 2A 2 max is 2 now move I update the max 2A 2 max is 2 now move I further I is equal to 5 check if the further I is equal to 5 check if the value at I which is B is present inside value at I which is B is present inside the map yes it's present get its value the map yes it's present get its value and calculate the distance so right is and calculate the distance so right is five and left is 1 and 1 so 5 - 2 is 3 five and left is 1 and 1 so 5 - 2 is 3 and update the current Max 3 and two and update the current Max 3 and two will be compared and Max is three now I will be compared and Max is three now I is at six check if the character at I is is at six check if the character at I is present inside the map yes it is present present inside the map yes it is present so get its left index and calculate the so get its left index and calculate the distance right is 6 - 0 - 1 is equal to distance right is 6 - 0 - 1 is equal to 5 so length is equal to 5 and update it 5 so length is equal to 5 and update it with current Max current Max is 3A 5 with current Max current Max is 3A 5 which is 5 and move I further and I is 7 which is 5 and move I further and I is 7 which is greater than the length of the which is greater than the length of the strings so we end the iteration as it strings so we end the iteration as it goes out of bounds and whatever is goes out of bounds and whatever is present inside the max variable which is present inside the max variable which is five will be returned as output so these five will be returned as output so these are the five characters and this is the are the five characters and this is the left index and this is the right and the left index and this is the right and the substring length is five so that is the substring length is five so that is the output now let's Implement these steps output now let's Implement these steps in a Java program so this is the input in a Java program so this is the input given to us let's take the second given to us let's take the second example so s is equal to a b c a and we example so s is equal to a b c a and we have to return a integer as the output have to return a integer as the output so first I start with creating the map so first I start with creating the map and then I create a variable Max which and then I create a variable Max which is equal to minus1 and then we iterate is equal to minus1 and then we iterate through the string from starting index through the string from starting index till the end so we start from so right till the end so we start from so right pointer is pointing here we extract that pointer is pointing here we extract that character CH is equal to a we check if character CH is equal to a we check if it is present inside the map no it's not it is present inside the map no it's not present so this will be skipped and this present so this will be skipped and this will be executed we're putting that will be executed we're putting that character at right character at right is character at right character at right is a so add it as key a so add it as key and add its index which is right to zero and add its index which is right to zero as its value now move right to the next as its value now move right to the next index we extract the character at right index we extract the character at right CH is equal to B we check if it is CH is equal to B we check if it is present inside the map no so this will present inside the map no so this will be executed add that character B and set be executed add that character B and set its index as the value now move with the its index as the value now move with the right pointer extract the character at right pointer extract the character at right character at right is C so CS C right character at right is C so CS C check if it is present inside the map no check if it is present inside the map no it's not present so El block will be it's not present so El block will be executed again add the character at executed again add the character at right character at right is C and set right character at right is C and set its value as right right is pointing at its value as right right is pointing at two which is the leftmost index of C two which is the leftmost index of C until now which is the first occurrence until now which is the first occurrence that is the leftmost index of C now move that is the leftmost index of C now move right further character at right is a so right further character at right is a so CH is a check if it is present inside CH is a check if it is present inside the map yes a is present inside the map the map yes a is present inside the map get its left pointer from the value so get its left pointer from the value so map. get of character at right character map. get of character at right character right at CH so get its left most so this right at CH so get its left most so this is this is left now we calculate the is this is left now we calculate the distance that is right - left - 1 right distance that is right - left - 1 right is equal to 3 left is equal to 0 and - 1 is equal to 3 left is equal to 0 and - 1 so 3 - 1 is 2 and current max value is so 3 - 1 is 2 and current max value is so max of -1a 2 so max will be updated so max of -1a 2 so max will be updated to two and in the next iteration right to two and in the next iteration right is out of bounds so we end the iteration is out of bounds so we end the iteration because right is equal to four so right because right is equal to four so right is four and length is four this is four and length is four this condition will fail and we come out of condition will fail and we come out of the for Loop and whatever is present the for Loop and whatever is present inside Max Max contains two as the inside Max Max contains two as the answer so two will be returned as the answer so two will be returned as the answer which is expected here so the answer which is expected here so the time complexity of this approach is O of time complexity of this approach is O of n where n is the length of the input n where n is the length of the input string has given to us and the space string has given to us and the space complexity is also of n because we're complexity is also of n because we're using a hashmap to solve this question using a hashmap to solve this question that's it guys thank you for watching that's it guys thank you for watching and I'll see you in the next and I'll see you in the next [Music] | 2024-03-15 18:48:56 | 1,624 | Leetcode | 1624. Largest Substring Between Two Equal Characters | Easy | Java Solution |
|
Xl0mO-Nrp_E | hey guys so welcome back to another video video in this video we are going to see a in this video we are going to see a problem called longest problem called longest nice substring given that a string nice substring given that a string s is nice if for every letter of the s is nice if for every letter of the alphabet that contains alphabet that contains that s contains it appears both in upper that s contains it appears both in upper and lower case and lower case so for example a b a b so for example a b a b b is nice because capital a and small b is nice because capital a and small a appear and capital b and small b a appear and capital b and small b appear appear so however a b and capital a is not so however a b and capital a is not because because the letter b appears and there's no the the letter b appears and there's no the capital capital letter in the string yes letter in the string yes so so for example so so for example in this given string a b a b b in this given string a b a b b they need not the alphabets a they need not the alphabets a and b are unique and uh and b are unique and uh as per the given condition we need to as per the given condition we need to have both of their have both of their uppercase letters in the given string uppercase letters in the given string and they need not be and they need not be in the consecutive order for example a in the consecutive order for example a and capital a need not be and capital a need not be in the consecutive order so which makes in the consecutive order so which makes this problem this problem kind of a little bit more complicated kind of a little bit more complicated so in this problem we are going to so in this problem we are going to use recursion to solve it use recursion to solve it let's see how we can do it let's see how we can do it so this is the given string and so this is the given string and our logic is going to be something like our logic is going to be something like so first let's mark the indices so first let's mark the indices 0 one two three four five and six 0 one two three four five and six so our logic is going to be something so our logic is going to be something like like so whenever we see an so whenever we see an invalid alphabet we are going to divide invalid alphabet we are going to divide the string the string into two into two into two into two and we are going to check if the and we are going to check if the to the left of the string and the right to the left of the string and the right of the strings of the strings if we can find any valid formations and if we can find any valid formations and we are going to return the maximum of we are going to return the maximum of them so for example in this string we them so for example in this string we can see that so we create can see that so we create a set for each and every letter a set for each and every letter in the given string so that that set is in the given string so that that set is going to be going to be looking like this and we have looking like this and we have all the characters we put all the all the characters we put all the characters into the set characters into the set and we check if they're valid and we check if they're valid a character is valid if we have both its a character is valid if we have both its upper and lower case letters for example upper and lower case letters for example in y we have in y we have both of its upper and lower case letters both of its upper and lower case letters in the set so in the set so the string so the character the string so the character y is valid so we kind of going to run a y is valid so we kind of going to run a for loop for loop on the string first so y as you can see on the string first so y as you can see y is valid and then we move to y is valid and then we move to a and a we have both the upper and lower a and a we have both the upper and lower case a's case a's uh so it's kind of also valid and then uh so it's kind of also valid and then now we move to is it now we move to is it but the thing with is it is that we only but the thing with is it is that we only have its lowercase letter and we do not have its lowercase letter and we do not have its uppercase letter in the set have its uppercase letter in the set so it's not valid so we are going to so it's not valid so we are going to divide this string into two parts divide this string into two parts and it's gonna look something like this and it's gonna look something like this so for example so for example the string has a y the string has a y a y a y a is it a cavalry a and y a is it a cavalry a and y and and we're going to divide this string at is it and we're going to divide it into two the the string the substring to the left off is it and the substring to the right of is it and we are going to do this recursively again and again so the substring to the left of z is going to be capital y and substring s1 is going to be capital y and small a and the set we're going to create another set for this again so the set is going to contain y and a so again the sub the substring to the right opposite is going to have small s2 is going to be having solid a capital a a and y small one and the set for this is going to be small a capital a and small y so and then we are going to run for loop on both of these we're going to do that process recursively and our base case is going to be if the string goes less than two strings then we are going to return an empty string so it doesn't make sense so if it goes less than two strings they cannot be a it cannot be a nice string so we're gonna run a for loop on this string y a and y we have we do not have both uppercase and lowercase letter wise in the set so we're gonna divide the string into two and the string towards the left of y it's gonna contain just an empty string and swing towards the the uh right of why it's gonna contain only a so again it's less than uh the length of the string is less than two so it's we're just gonna return uh an empty string these blue strings are just gonna be returning t in empty strings and uh here we check for we again run the for loop in the string and for example in a we have both lower and uppercase letters ea and again capital a we have both upper and lowercase letters and again for the small a we have both upper and lower case letters so these are valid characters so we then move to y and for y we do not have the upper and lower case letter y so we are going to divide the string into two sub strings again the the string to the left of substring to the left of y which is this and substituting to the right of y which is an empty string gain so it's going to be string s one is going to be equals to equal to uh a capital a and a and the set for this is going to be equal to small a and capital a and string to the right of s2 is going to be containing just an empty string so we don't need to do anything for that and yeah this string aaa we're going to recursively run the loop and all these cases this this and this are just going to return empty strings to the recursion above it and and this special string which is actually a valid string it's going to run the for loop on this again and a we have both capital a and small a for that and again for this a we have capital and small a and again for the same we have both the capital and small letters so it's a valid string so once we find this valid string we're going to return the string if the forward loop completes we're just going to return the string or if we have another valid if we had another valid string here for example small b and capital b here we're just going to compare both of them and return the length of the maximum string so in this case we're going to return a a and a to its recursion above it and this is again going to return aaa to the recursion above it and so we finally get the answer which is molly capital a and small a just answer so this is the idea behind it so let's see how we can code this up so first i'm going to be creating the recursive call function it's going to be called dfs and it's going to be taking one parameter and it's called string and we but we're going to be creating our hash set it's going to be the set of our current string and we're going to be creating our base case if the length of our string is less than two then it makes no sense to further proceed so we're just going to be returning an empty string and now we are going to be looking to our string for ein range oops if not of if not of string of i dot if string of i dot if this is going to be checking if our this is going to be checking if our current alphabet is valid and string of and string of i dot upper i dot upper in hash set then or we are going to be dividing the string into two parts string one is going to be the dfs call recursive call to the left of our invalid character to the left of our invalid character and string 2 is going to be the and string 2 is going to be the recursive call recursive call of the current string but to the of the current string but to the right of our in our character and we are going to be returning the string with the maximum length uh we're going to be returning string to lenovo two lenovo two is greater than one off string one is greater than one off string one [Music] [Music] else you can defeat else you can defeat any string one and if our string is any string one and if our string is entirely valid you're just going to be entirely valid you're just going to be returning the string returning the string and this return the dfs call and this return the dfs call of s so this must work so this works so thank you for watching so this works so thank you for watching this video this video make sure to subscribe and check the make sure to subscribe and check the links in the description links in the description thank you for watching | 2024-03-22 12:40:09 | 1,763 | Leetcode 1763. Longest Nice Substring | Recursion Visualized | Code Explanation |
|
PGH3Yc79WRk | hello guys welcome back today we are going to understand to delete your going to understand to delete your question okay so let's see the today question okay so let's see the today question so today we have given 1802 uh question so today we have given 1802 uh maximum value at a given index we have maximum value at a given index we have given in a bounded array right so let's given in a bounded array right so let's continue to understand this question continue to understand this question right so this is a lead code 1802 right so this is a lead code 1802 question so it is saying that you have question so it is saying that you have given three positive integers that is n given three positive integers that is n uh index and maximum okay and you want uh index and maximum okay and you want to construct an array that is called to construct an array that is called nums right and it is a zero index array nums right and it is a zero index array means one day array that satisfies the means one day array that satisfies the following conditions right the first it following conditions right the first it is saying that nums dot length is equal is saying that nums dot length is equal equal to n another it is saying that equal to n another it is saying that nums at I is a positive inches where I nums at I is a positive inches where I is greater than or equal to 0 to n is greater than or equal to 0 to n and absolute value of num num at I minus and absolute value of num num at I minus naught I plus 1 is less than equal to 1. naught I plus 1 is less than equal to 1. now it is saying that I should be now it is saying that I should be greater than equal to 0 answer to less greater than equal to 0 answer to less than equal to n minus 1. than equal to n minus 1. next sum of all the elements of nums next sum of all the elements of nums does not exceed maximum does not exceed maximum and finally it is saying that Mouse at and finally it is saying that Mouse at index is maximized okay these things we index is maximized okay these things we have given have given so what we have what we have to do we so what we have what we have to do we have to return the nums at index of the have to return the nums at index of the Constructor array right and note that we Constructor array right and note that we have to Absolute x equals to equal x if have to Absolute x equals to equal x if x is greater than what 0 and x is greater than what 0 and -1 minus X okay -1 minus X okay so let's suppose we have given a n equal so let's suppose we have given a n equal to 4 right and another we have given to 4 right and another we have given index equal to index equal to 2 and Maxum we have given is 6 Okay so 2 and Maxum we have given is 6 Okay so now we have to reconstruct an array now we have to reconstruct an array right and right and so how will construct the array right so how will construct the array right depends on this value right so if let's depends on this value right so if let's suppose we have ah suppose we have ah ah n equal to 4 right means 4 is a ah n equal to 4 right means 4 is a length light what is a length as you can length light what is a length as you can see here see here n dot announced dot length is equal n dot announced dot length is equal equal to N means length of array equal to N means length of array we have given we have given in where in where in here right n equal to 4 means when we in here right n equal to 4 means when we are going to construct an array so there are going to construct an array so there should be should be index 0 comma index 1 comma index 0 comma index 1 comma index 2 comma index 3 right so these index 2 comma index 3 right so these elements we have to fill in the nums and elements we have to fill in the nums and this is nothing but our nums right this is nothing but our nums right now what we have to do now we have to now what we have to do now we have to construct in such a way that the maximum construct in such a way that the maximum should be 6 right should be 6 right so nums at I is a positive integers so nums at I is a positive integers right right and we have to take absolute value num and we have to take absolute value num minus none plus one should be less than minus none plus one should be less than equal to 1 right equal to 1 right now it is also saying that the sum of now it is also saying that the sum of all the elements of the num does not all the elements of the num does not exceed maximum right so from the maximum exceed maximum right so from the maximum it should not be maximum value it should not be maximum value so to do that if we construct a value so to do that if we construct a value let's suppose I'll start with let's suppose I'll start with 1 okay then we can take 2 1 okay then we can take 2 then we can take 2 and then we get 1. so then we can take 2 and then we get 1. so if if it an index 2 has a two value index 2 it an index 2 has a two value index 2 has a two value right we have given has a two value right we have given this is given right index index index 2 this is given right index index index 2 right index equal to 2 we have given right index equal to 2 we have given right so if you consider that nums at 2 right so if you consider that nums at 2 now is what now is what look if you go if you do the sum it will look if you go if you do the sum it will become what there is no array that become what there is no array that satisfy the condition right right that satisfy the condition right right that satisfies the condition and so satisfies the condition and so we have to construct the error like this we have to construct the error like this one two two one right because this is one two two one right because this is the only one array the only one array that satisfies our all the conditions that satisfies our all the conditions right right so if n equal to 4 if we'll take index 2 so if n equal to 4 if we'll take index 2 index 2 is there right if you do the index 2 is there right if you do the maximum of this one so it will come 6 maximum of this one so it will come 6 right so this all conditions can be right so this all conditions can be satisfied right satisfied right so here if we'll take nums at what to so here if we'll take nums at what to so this will become what three why so this will become what three why because we have to take the sum right we because we have to take the sum right we have to take the sum okay and 2 is the have to take the sum okay and 2 is the maximums at 2 is the maximum nums at maximums at 2 is the maximum nums at here right you can say maximum value we here right you can say maximum value we can say okay can say okay and that's why this is uh the value we and that's why this is uh the value we have given right so 0 1 2 is equal to it have given right so 0 1 2 is equal to it is a 3 value it is coming right but is a 3 value it is coming right but if we talk about 2 what is this 2 2 is if we talk about 2 what is this 2 2 is the maximums at 2 right this is the the maximums at 2 right this is the Max num Max num at 2. at 2. right that we we can see that's why we right that we we can see that's why we have to return these two okay so this is have to return these two okay so this is the output the output okay so in this way you can try this okay so in this way you can try this example too right and you can make it example too right and you can make it okay okay so actually it is saying that num at 3 so actually it is saying that num at 3 and num n equal to three six Behavior and num n equal to three six Behavior index equal to one game a maximum is 10 index equal to one game a maximum is 10 right so you have to construct in that right so you have to construct in that way only let's suppose we have given n way only let's suppose we have given n equal to 6 index we have given equal to 6 index we have given is 1 and maximum we have given is is 1 and maximum we have given is or 10 okay so if we will write uh sorry or 10 okay so if we will write uh sorry array so arrays would be have length array so arrays would be have length what six what six zero zero one one to to 2 3 2 3 4 and the last element is fifth add 4 and the last element is fifth add index fifth zero to fifth now you have index fifth zero to fifth now you have to fill this nums array nums right so to fill this nums array nums right so you have to fill in such a way let's you have to fill in such a way let's suppose I'll start with one just for suppose I'll start with one just for understanding one then we'll take uh one understanding one then we'll take uh one again okay and two so one one two is again okay and two so one one two is four four we'll take two right one one four four we'll take two right one one two two and four or we can say four and three and four or we can say four and three that suppose I am taking three okay one that suppose I am taking three okay one one two one two and three is seven and three is seven and will take what and will take what if I'll take four it will become what if I'll take four it will become what seven for eleven okay so I'll take uh um three and take three zero let's suppose just just for zero let's suppose just just for understanding you can take any other understanding you can take any other value okay and then at index value okay and then at index here 1 here 1 we have to take what value right so it we have to take what value right so it is coming 3 okay so you have to take is coming 3 okay so you have to take initially three value and then you have initially three value and then you have to construct like this okay so you at to construct like this okay so you at that time you will get three just for that time you will get three just for understanding leave it so understanding leave it so take time and uh take time and uh so do the solution of example two okay so do the solution of example two okay so this question has been asked in uh so this question has been asked in uh Oracle and Microsoft okay Oracle and Microsoft okay let's understand the solution what let's understand the solution what solution is saying and how we will going solution is saying and how we will going to implement this right to implement this right so so As We Know As We Know ah this conditions we have given ok so ah this conditions we have given ok so let us start with the example that we let us start with the example that we have given in the problem statement that have given in the problem statement that we are going to refer through this we are going to refer through this figure okay so there are several ways to figure okay so there are several ways to make nums at two okay the maximum as we make nums at two okay the maximum as we are going to see first two example we are going to see first two example we are going to see is let's suppose once are going to see is let's suppose once we want uh larger nums at 2 we want uh larger nums at 2 that we are talking about here and it that we are talking about here and it will become what is 3 right will become what is 3 right and the sum of the array will certainly and the sum of the array will certainly be the greater than the maximum right be the greater than the maximum right because 1 2 and 2 is what 5 right and because 1 2 and 2 is what 5 right and this one becomes 6 okay so two to four this one becomes 6 okay so two to four one will take what one and one so this one will take what one and one so this total sum become six total sum become six right right so when we take this value 1 1 2 and 1 so when we take this value 1 1 2 and 1 right so in this case what will happen right so in this case what will happen maximum 1 1 2 and 2 4 and this is one maximum 1 1 2 and 2 4 and this is one and this will be one five so this is and this will be one five so this is also also true right and here what we are getting true right and here what we are getting we are getting 4 okay value we are getting 4 okay value now let's suppose we are taking here 3 now let's suppose we are taking here 3 at this Index right one two three we at this Index right one two three we will take here right and we come to so will take here right and we come to so that time that time 3 and 3 is 6 now we have two so this 3 and 3 is 6 now we have two so this will become what eight right and it is will become what eight right and it is more than max value right more than max more than max value right more than max value is eight right and that is not value is eight right and that is not good right because here what we are good right because here what we are getting getting uh three three six we will get here uh three three six we will get here right but the total sum will convert right but the total sum will convert total sum will come 8 and that is more total sum will come 8 and that is more than the max value right so this way we than the max value right so this way we have to understand and then we will have to understand and then we will implement the uh function right implement the uh function right let's suppose uh we are going to use let's suppose uh we are going to use greedy or binary uh search right so the greedy or binary uh search right so the first our ins intuition should be like first our ins intuition should be like our objective is to maximize the nums at our objective is to maximize the nums at the the given Index right the the given Index right so nums to maximize the nums at index so nums to maximize the nums at index the nums at the given index while uh the nums at the given index while uh ensuring that the sum the array does not ensuring that the sum the array does not exceed maximum so we can try using exceed maximum so we can try using greedy algorithm right and in order to greedy algorithm right and in order to maximum the maximize the numbers at maximum the maximize the numbers at index we need to ensure all the other index we need to ensure all the other values as small as possible Right values as small as possible Right so however we cannot take the other so however we cannot take the other values to be uh you can say smaller values to be uh you can say smaller right and we will refer the two given right and we will refer the two given rules in this problem that the rules in this problem that the difference between the adjacent number difference between the adjacent number cannot be greater than one right and cannot be greater than one right and nums at I must be nums at I must be positive okay means that we are talking positive okay means that we are talking out here this will not work because if out here this will not work because if we'll make the difference between these we'll make the difference between these numbers so this will not work right so numbers so this will not work right so you have to take like this only like if you have to take like this only like if you will talk about one two difference you will talk about one two difference is one two two right difference is 0 2 1 is one two two right difference is 0 2 1 right difference is one means it should right difference is one means it should not be greater than what one so it is not be greater than what one so it is saying that if I'll take a ah let's saying that if I'll take a ah let's suppose nums at suppose nums at I is let's suppose 2 so it is saying I is let's suppose 2 so it is saying that nums at that nums at uh uh I plus 1 I plus 1 should be either 3 or should be either 3 or or one okay or one okay either three or we should take one okay either three or we should take one okay it should not be other than value it should not be other than value because if the difference is coming it because if the difference is coming it will take will take this minus this or this minus this it this minus this or this minus this it should not be greater than one okay should not be greater than one okay next rule is saying that next rule is saying that if nums at value if nums at value num let's say nums at num let's say nums at I should be must be greater than 0 right I should be must be greater than 0 right positive value so these two conditions positive value so these two conditions we have to follow we have to follow so the last two example that we have so the last two example that we have seen right seen right here here these two right this were working these two right this were working and as you see the difference between and as you see the difference between the adjacent numbers are coming what right but uh in the example of the right side this one this one okay what happening here if we are taking difference between nums at 3 and nums at 4 that is greater than 1 right but in this example if the first number is coming equals right the first number is coming equals and which is not allowed okay here those two example is coming equals right so that is not correct so in this way this is also not allowed this example is also not allowed but we are referring this one and this is also not allowed right so only this type of example will work cut it because both adjacent value is coming what 1 difference would be what it should not be cannot be greater than one right it cannot be greater than one this should be take care of and the difference the next two values should not be equal right if it is equal means what ah this is also not right this is also not allowed got it okay so hence we need to ensure that okay so hence we need to ensure that nums at I satisfy these conditions as nums at I satisfy these conditions as well means this will not work and this well means this will not work and this will not work okay this will not work will not work okay this will not work this will not work this will not work this will work right this will work right based on these two condition right if based on these two condition right if the difference if the difference is the difference if the difference is not greater than this one one right and not greater than this one one right and another another nums at I should not be greater than nums at I should not be greater than zero I should not be 0 right it should zero I should not be 0 right it should be be must be positive number right so it must must be positive number right so it must be positive not zero be positive not zero yeah must be positive as you write right yeah must be positive as you write right like this so therefore the straightforward approach is uh after setting the value of the nums at index here are the numbers to its left decrease one by one from the right to the left until they reach one similarly the numbers to the Its Right decreases one by one from the left to right until they reach one rich one right see the so this way means it is saying this these are number given right these numbers are these numbers are given okay so the very straightforward approach after you set these values right let the numbers to its left decrease one by one so from here we are going to decrease one by one okay it is saying like this similarly the numbers to its right decrease one by one from the left to right from right decrease one by one from the from right decrease one by one from the left to right until we are going until left to right until we are going until there is one okay so these two approach there is one okay so these two approach we can follow either this way or this we can follow either this way or this way right until we reach way right until we reach so left side it will number should be so left side it will number should be decreased right decreased right this way we can ensure that the total this way we can ensure that the total sum of the array is minimized without sum of the array is minimized without validating the rule because if will validating the rule because if will decrease we will decrease by 1 right if decrease we will decrease by 1 right if we'll increase will increase by one we'll increase will increase by one right right so we need to calculate the sum of the so we need to calculate the sum of the array which is purely mathematical array which is purely mathematical problem problem right right so let's uh take the number of left of so let's uh take the number of left of nums at index nums of as an example right there will be an as an example right there will be an arithmetic sequence to its left right arithmetic sequence to its left right and possibly our consecutive numbers of and possibly our consecutive numbers of ones s is numps at the given index is ones s is numps at the given index is less than the number of element to the less than the number of element to the left right so we need to determine the left right so we need to determine the length of the arithmetic sequence based length of the arithmetic sequence based on the relative size of the index and on the relative size of the index and value right so the next value that its value right so the next value that its relative consecutive value will come relative consecutive value will come from what from what index index plus 1 right and if we'll do the minus plus 1 right and if we'll do the minus it should be it should be 1. right absolute value of 1 you can say 1. right absolute value of 1 you can say this will always compose positive this will always compose positive so once we have determined the length of so once we have determined the length of the arithmetic sequence we can calculate the arithmetic sequence we can calculate the sum of the sequence using the the sum of the sequence using the automatic formula right and this sum automatic formula right and this sum will come Y how like a of 1 plus a of will come Y how like a of 1 plus a of n Dot n Dot Dot N by 2. Dot N by 2. okay so this arithmetic sequence formula okay so this arithmetic sequence formula we will use we are af1 we will use we are af1 and a of n and a of n is the first and the last term of the is the first and the last term of the sequence where n is the sequence where n is the sequence class sequence right sequence class sequence right so let's suppose we are going to take so let's suppose we are going to take here okay so what I told the formula so here okay so what I told the formula so I am taking the sum as uh a of 1 I am taking the sum as uh a of 1 Plus Plus a of a of n n and we will multiply with what n by 2. and we will multiply with what n by 2. here a A1 A1 and a n are the first and here a A1 A1 and a n are the first and the last term of the sequence the last term of the sequence and N is the and N is the length of the sequence right length of the sequence right let's suppose we are started from here let's suppose we are started from here to to here okay here okay so it is saying that so it is saying that if the value if the value if the value here if the value here is less than equal to index is less than equal to index right right it means in addition to the arithmetic it means in addition to the arithmetic sequence from value to 1 sequence from value to 1 there will be a continuous sequence of there will be a continuous sequence of One S One S with the index minus Value Plus 1. right with the index minus Value Plus 1. right the sum the sum we are talking about like ah there will we are talking about like ah there will be index side be index side minus value minus value and plus 1. and plus 1. if this will if this will come right it means what come right it means what means means where value is less than equal to where value is less than equal to index and that's why here it is come index and that's why here it is come value and there it is coming Index this value and there it is coming Index this way you are talking about because we are way you are talking about because we are we are just adding one value we are just adding one value here right so one value is here one here right so one value is here one value is here like this we are setting value is here like this we are setting for all these values right so the sum of all the elements right on the index of the left including uh nums index is made by two parts the first part is you can say 0 1 2 3 right and then it will convert it will sorry it will go continuously like this and then it will start with what this part value minus 1 value minus 2 value and then value right like this and which is Value Plus 1 into value like if you implement this one though this part so this part will be convert Value Plus 1 into value by 2. right like this it will be gone so the sum of the sequence will become what if we'll do the sum if you going to find the sum it will be convert index minus value Plus 1. and which is it is consists of all the now now this index minus Value Plus 1 is the sum this index minus Value Plus 1 is the sum of your values of your values right right otherwise it means there there is only otherwise it means there there is only one automatic sequence on the left side one automatic sequence on the left side of the index with the first item of the index with the first item Wing value and the last item value minus Wing value and the last item value minus Index right so first item will become Index right so first item will become what value what value and another will become what value minus and another will become what value minus index index so this is your first value and the zero so this is your first value and the zero second value second value so this time the sum of arithmetic value so this time the sum of arithmetic value will become what will become what this is your value this is your value minus this year you can say value minus minus this year you can say value minus index and then we can take what value index and then we can take what value and then we'll take value minus 1 like and then we'll take value minus 1 like this right this right so this all depends on your things right so this all depends on your things right either will take value minus index value either will take value minus index value minus index that we can see down then minus index that we can see down then then value minus 1 and third we can take then value minus 1 and third we can take what what value value three things we can take in first we'll three things we can take in first we'll take minus then we'll take What minus 1 take minus then we'll take What minus 1 and then we'll take value and then if and then we'll take value and then if we'll do the sum right and this will we'll do the sum right and this will become what become what Value Plus value Value Plus value minus index minus index this value and then we will multiply this value and then we will multiply index plus 1 index plus 1 by 2. right based on this formula means by 2. right based on this formula means I can if I go into right here so first I can if I go into right here so first is what what we have we have value then is what what we have we have value then what we have will do plus what we have will do plus value minus index value minus index right and now n is and we know that what right and now n is and we know that what we have n is we have n is index plus 1 by 2. index plus 1 by 2. that we are talking about here that we are talking about here hey so these are the approach that we will follow in this ah part in this ah part similarly let's suppose we have ah in similarly let's suppose we have ah in the right side we have the right side we have nums at index is actually exactly the nums at index is actually exactly the same we need to determine the length of same we need to determine the length of the elementary sequence and the length the elementary sequence and the length of the continuous array with the one of the continuous array with the one right as you can see here right as you can see here one based on the relative size n minus one based on the relative size n minus index and value index and value right right so this is your n minus 1 and this your so this is your n minus 1 and this your value right similarly if the value is less than or equal to n minus Index right n minus index that we are talking about right it means that um the sub array of the length will become what n minus index minus value this will become sub errorism right because it consists of all the value of one one is addition to the arithmetic sequence value to 1. we have taken value and we'll take till what one so from here to here if you if you are taking means this all is consist of 1 s okay the sum of all the element of the index right including nums at index is made of the two part the first arithmetic sequence that we can say is starting with the value then value minus 1 and it will come similarly to like this okay so here if we'll do the calculation right this calculation is nothing but what it is saying that ah if you do the sum right it will do the sum right this will become what this will become Value Plus 1 we can take Value Plus One Value Plus One into value by 2. right because this is the thing we have if we'll do the sum of the length this will be convert we have taken Index this one then we will take what minus value Plus 1. this is your okay okay and this was a sum of arithmetic as some and this was a sum of arithmetic as some of the arithmetic sequence of the arithmetic sequence okay okay and this order connected with 1s and this order connected with 1s and this is this is actually and this is this is actually less than what less than what n minus n minus n minus index n minus index minus value minus value it is less than it is less than okay just that the sum value is coming so in the otherwise there is only one arithmetic sequence on the right side of the index right with the first item being value and the last item being value minus n minus value minus n plus 1 plus Index right as you can see here value minus n plus 1 and so this is going to be index n minus and so this is going to be index n minus 1 right 1 right so if we'll do the sum right the sum so if we'll do the sum right the sum should be what Value Plus should be what Value Plus Value Plus Value Plus value minus n value minus n plus one plus one Plus Plus index index this will become the sum this will become the sum and you have to Define divided by 2. and you have to Define divided by 2. right because right because if we are going to divide means we have if we are going to divide means we have to multiply what to multiply what we can take n minus we can take n minus n minus index n minus index n minus index n minus index right n minus index C right n minus index C that part we have to multiply here now you have seen everything this detail thinks rise so we don't need to forget that we have added the actual value at the given index twice so we need to subtract the final value by Sum right now we have seen that we how to calculate the array sum at a given a specific value right so the question is how do we maximize our value so we can use binary search to find the maximum value that meets the criteria first we Define a search range from left to right and that we are going to ensure that the maximum value that falls within this range next we will perform binary search within the range like for each boundary value mid that divides a current search space in the half and we try whether the nums at the given index is mid right if it is Miss that is feasible value that ensure the sum of the array does not exceed maximum right so if it is valid we continue the search for the larger mid in the right side right half of the interval so if it is not feasible it means that mid is too large so we need to search for a small value in the left half of the interval and if this if this way we can means we can say in this way we can have we can have the search interval at each step and we will find the maximum mid that emit the criteria in the logarithmic time it means there are many uh problems right there are many problems you can say ah that you can perform the binary search and you can find the Optimal Solutions right you can check out the split array uh Lots on maximum distance to gas station Coco eating banana capacity to ship package within the days and divide chocolate type many problems and you can you can go through that okay now we are going to see the algorithm right and we will try to implement this one so first we need to define the a function that will take you can say index and value and we will calculate the maximum sum of the given value that is called num right we will initialize Left Right space and we'll set a left is equal to one is the max minimum a possible set right equal to Max for its maximum possible value now we'll check left is left should be less than right till that we will get the middle index of the search space and we'll find our mid so left plus right plus 1 by 2 that is you can already have the knowledge of magnetic search we'll check if the get sum is less than the maximum right if so it means num at index is mid is a valid num and we can go for the right half by setting left equal to Mid it means the mid is too large and we have the nums right so we shall go for the left half and we'll search the space and we'll set the right equal to Mid minus ones and we will return once the binary search ends so what we have to do actually here right uh that we will talk about later we will take left right and we'll in the while loop we'll take while is less than right you know the binary search right so we'll make a while loop and we will find our mid and we'll check the get sum is less than the maximum will ah assign left equal to Mid and otherwise write equal to Mid and will return left right so this is the binary search things that you can go through and you'll check coming back to the get sum we have index we have been value we have been and we have given right we will take account right and we'll check value is greater than index we'll find our count how we'll find the count Value Plus value minus index into index plus 1 by 2. count will find how Value Plus 1 into value by 2 or plus ah index minus Value Plus 1 right similarly this is the ah from left to ah right to left right now we'll go with the value is greater than n minus Index right so we'll take Value Plus value minus n Value Plus value minus n plus 1 plus index and we'll take n minus index that we have seen previously right and similarly for this one will take Value Plus 1 into value by 2 value by 2 and we'll do plus n minus index minus value and will return value minus this one because we have already added value is time right so we'll return our value so finally it will return the max value right maximum sum it will return so that's all for today and if you like this video please hit subscribe this channel so you will get more understanding more videos like this this little let's little lengthy videos so don't worry for this take some time pause this video and watch multiple times okay coming back to the time complexity we have given a log of Max sum and uh because uh we know that searching a space will take o log Max sum and this step is coming from what binary search right and we know that each calculation will take off one time so that's why we will take log log of the sum but the space will take off one because uh binary search get function will take o of n space we are not taking any stress basis and that's for all today so thank you for watching this video guys if you hit if you like this video please hit subscribe this channel so we will go | 2024-03-22 16:03:13 | 1,802 | Leetcode 1802. Maximum Value at a Given Index in a Bounded Array |
|
Lsc4mj2Wd-E | Hello guys welcome back devotion in this video will see the editor for combination video will see the editor for combination problem system August challenge and problem system August challenge and incredible third node to solve this problem solve incredible third node to solve this problem solve latest video problem statement latest video problem statement in this problem Thursday in this problem Thursday subscribe this Video not here in this subscribe this Video not here in this Video give the giver function Video give the giver function Video give the giver function Length Function Is The Next 9 Combinations From News Room Latest Example In Order To Get Better Understanding Well In This Case First Wear Given Constructor Which Will All Set For Treating Acidity This Combination Length Know The Function Is The Next The Next The Next Generation In Lexicographical Length Generation In Lexicographical Length Combination Subscribe In The Northern Combination Subscribe In The Northern Porn Picture Verification Combination The Porn Picture Verification Combination The Question Is Giving Combination But I Will Be Question Is Giving Combination But I Will Be Solving Using Hubras For Example Subscribe Channel Subscribe How To Find The Springs Having Combination Length Of Only Give In This They Can Have They Can Have They Can Have Combination ABCD ABCD Will Be The Three Combination ABCD ABCD Will Be The Three Combination Subha Possible From Distic Combination Subha Possible From Distic President Graphically Subscribe To Dr. Reddy Labs' President Graphically Subscribe To Dr. Reddy Labs' Combination Lexicography Indian They Are Not Against Any Thing Will Start From This Point Widening This Point To Point To Tweet Day you will see the Day you will see the Day you will see the point at a point into a string point at a point into a string and have detected at this point into a and have detected at this point into a string then will be going through in this string then will be going through in this non veg dish function Kaulav 1.21 BSE The non veg dish function Kaulav 1.21 BSE The Video then subscribe to The Amazing Video then subscribe to The Amazing Pointed to be written and they will update this Pointed to be written and they will update this Point to the point for this point to the Point to the point for this point to the return of the problem examples return of the problem examples tu latest new look at how to solve this problem we tu latest new look at how to solve this problem we love e request to generate love e request to generate combination soir giver string abc length combination soir giver string abc length equal in the total combination you must for equal in the total combination you must for every character will have two options subscribe possible combinations of strength from this subscribe possible combinations of strength from this abc watering allegation length of the abc watering allegation length of the combination length combination randhir wa ko subscribe zur acids pe ki aditya ne cd vanity van abc of this will be possible combinations from this will speak all the Of length to presence to read somewhere in order to Of length to presence to read somewhere in order to Of length to presence to read somewhere in order to process and process and next nonviolent no matter how to solve watching this next nonviolent no matter how to solve watching this green line will win the character green line will win the character of birth subscribe The Amazing Green Color subscribe se this se this 220 will go to also know what we 220 will go to also know what we 220 will go to also know what we 10 20 or exclude this be let us swim proof Buddy 8V Can include desi and one foreign improved desi ghee in the distinctive which will be amazed to see some decisions of the three and receive notifications combination of all will not be the best option will be Simply Subscribe Indian Simply Subscribe Indian Simply Subscribe Indian Length Will Be Back To Back To The Best Option Length Will Be Back To Back To The Best Option A Day Will Not See The Hidden The Channel And A Day Will Not See The Hidden The Channel And subscribe The One That String subscribe The One That String Quest Only For Recording Studio Quest Only For Recording Studio But Acted SBNS2 DC But Acted SBNS2 DC Sources Of Your Interests Of Land Sources Of Your Interests Of Land Sources Of Your Interests Of Land back from this is back from this question for this is not including a e don't know the character we can do subscribe will be there will be no the best option for not doing so will only be not been looted 9 9 Will Not Be Seen From This 9 9 Will Not Be Seen From This 9 9 Will Not Be Seen From This End Subscribe Toe Hue End Subscribe Toe Hue Land Is From All Possible Combinations Land Is From All Possible Combinations Soft Dough Possible Combination Switch Is He Is Soft Dough Possible Combination Switch Is He Is Totke Strings Idea Of Interest Does Totke Strings Idea Of Interest Does So The Interested Springs Raw Length So The Interested Springs Raw Length Combination Land Which Was Requested To Know Combination Land Which Was Requested To Know The Thing Which They Should The Thing Which They Should The Thing Which They Should lexicographical Dr. Hind is the trick so you can servi provide all the string in see watering director subscribe like this is this what is this production will be in order to combination veer veer veer question how to victimized solution in this Which can see that they are just Which can see that they are just Which can see that they are just interested in the combination length length of the string interested in the combination length length of the string ok so in this is pair including this and including this ok so in this is pair including this and including this also din also din they can stop here and lotus in her but no what is they can stop here and lotus in her but no what is placid in this a win again they want placid in this a win again they want to to to Is Not As Well Shree They Are Not Tree To Its Length Is Required In The Top And They Can Not Give This Will Be The Mystery Solved This Very Good Which Will Give You Time Complexity While even Time Complexity While even Time Complexity While even after you upload voltage change the voice after you upload voltage change the voice kids time complexity can go to and raw kids time complexity can go to and raw to the point and because the length of the string to the point and because the length of the string and the combination can land both also and the combination can land both also in this world will be equated with and a in this world will be equated with and a butterfly positive vibration they can butterfly positive vibration they can Improve the time will be running in a better Improve the time will be running in a better time compare to they don't reply 2 time compare to they don't reply 2 optimization ok no latest look at the optimization ok no latest look at the next technique which by using waste masking before going to next technique which by using waste masking before going to bed masking bed masking approach latest weekly revised it's who approach latest weekly revised it's who 737's latest from where given string it 737's latest from where given string it b b b string values for example Will be having only those who believe values from plant B C D Will have all is well because of the corresponding values of this A B C D Will not have anything because all Well wishes will give you know how to improve the way they can take off Well wishes will give you know how to improve the way they can take off Well wishes will give you know how to improve the way they can take off but are to be valued for but are to be valued for the latest Thursday morning no one will just subscribe to the Page if you liked The Video then subscribe to the Apne CD Sanseri Understand How They Can Use This Witmarsh on this given string in order to get new subsequent spring so how many true combinations are possible if you have endless stream death will have total number of bitcoin combination apps and display 100 this is very simple to understand what we can give subscription subscription subscription be two to two two to two 9 from this length subscribe combination string from total length of subscribe combination string from total length of total strings Bluetooth total strings Bluetooth 382 huge crystal clear 382 huge crystal clear ludhianvi three subsequent springs which will be ludhianvi three subsequent springs which will be having length equal to fennel having length equal to fennel having length equal to fennel ABCD Water This Mask Range Value Pure Mask Will Be Ranges From All 0.2 All One Side Open 10th december Combination Request You Too So Will Take All Two Spring Combination Morning Is That 210 210 Do Or 21 2013 Near And Dear Ones Who Were COMBINATION 2ND YEAR IN COMBINATION 2ND YEAR IN COMBINATION 2ND YEAR IN JUST MORE THAN 120 SUBSCRIBE LIKE SUBSCRIBE AND WAVE COMBINATION WILL FIND THE ENGLISH HOW 2010 WILL CHECK THE LENGTH OF THE STRING WITH AND COMBINATION LANDSORE LUTYENS ZONE PRESIDENT WILL NOT MATCH NOMINAL FEE FOR LIPS DISTRICT WILL GIVE YOU WILL NOT Will Not Distract Subscribe Know What Is The Story In Hindi Stories With Values Path But As You Can See The Question Is That We Need Not Guarantee Key Elements In Water In Delhi Yet Kept In Short Doctor Saw In The Previous Cases Will Be Easy CM BC When all the elements in set and you 100 inspiration in map and set is people is maintaining all elements in half basically a balance total number of the nation and everyone can we take time to time complexity and see the question is that we can withdraw all This Creation Combination Veer Vikram Channel And Not Storing These Values Will Not Complete Process Will Not Present In All Possible Springs Advisor Deposit From Your Length Of The String And G To 250 No You Know That You Next Function Will Only Be Generate All Generate All Generate All Possible Strings Within Time For This Will Possible Strings Within Time For This Will Be To The Point And Wish You Very-Very Be To The Point And Wish You Very-Very Happy Know Your Next Functions Only For All Happy Know Your Next Functions Only For All Times You Are Interested In The Top Ten Times You Are Interested In The Top Ten Lexicographical To Spend Some Lexicographical To Spend Some Time To Generate Just Give Answers For Doing What Time To Generate Just Give Answers For Doing What We can do it is the function to generate We can do it is the function to generate new song Video Subscribe Very Fast new song Video Subscribe Very Fast Solution Adhura Solution Adhura Clement And Latest New Look At The Code Clement And Latest New Look At The Code Of Baroda Process Which Have Explained You Of Baroda Process Which Have Explained You Dice Code For Tracking Where Given String Dice Code For Tracking Where Given String In The Name Of Directors And Or Combination The first no this The first no this The first no this is the cockroach 10 Back to Example and is the cockroach 10 Back to Example and Subscribe Our Thursday Subscribe Subscribe Our Thursday Subscribe Position in Obscene Vid Position in Obscene Vid * Desh 2002 19 This is basically did not in * Desh 2002 19 This is basically did not in position not loose and combination length its do subscribe strings in the result will be Later this is the on Thursday during the current Later this is the on Thursday during the current character adding a to the results string and will be making connectivity call boy doing to the worst position and observe decreasing the length ok nuvve including 800 x 480 width The Current Position Will Be The The Current Position Will Be The The Current Position Will Be The Character subscribe The Video then subscribe to The Amazing 2018 Widening And They Will Make This Point To The Missions Next Suhaag Next Will Take Care Of 23 Near The Worst Thing Which Left Soi This Point Is Point Into Your Valid String Will return to avoid all the Will return to avoid all the Will return to avoid all the combinations subscribe The Video then subscribe to the Page if you liked The is nothing but the pointer in the previous switch taken upon interview TO TO TO THE BEGINNING OF THE MAP OF NINTH CLASS THE BEGINNING OF THE MAP OF NINTH CLASS TRACTOR COMBINATION INTERVIEW PASS DISTRICT TRACTOR COMBINATION INTERVIEW PASS DISTRICT AND DISCRIMINATION AND AVOID YOU TO THE KNOW WERE ALL AND DISCRIMINATION AND AVOID YOU TO THE KNOW WERE ALL POSSIBLE COMBINATIONS COMBINATION WE WILL IMPROVE THE POSITION OF THE WINNER COMBINATION IMPROVE THE POSITION OF THE WINNER COMBINATION SET OK OTHERWISE WILL NOT BE SET OK OTHERWISE WILL NOT BE INCLUDED IN THIS INCLUDED IN THIS INCLUDED IN THIS performing this operation for all the combination will be having all the graphical user name the author of the point to the first combination to do the first operation operation operation operation point subscribe to this point and Point To Will Be Point To Will Be Point To Will Be Written In This Post And Subscribe Will Give Written In This Post And Subscribe Will Give This Point Is Point To The This Point Is Point To The Subscribe To And When Will Subscribe To And When Will Return Forms Otherwise Will Return Forms Otherwise Will Return To Saudi Operation Sara Gyan Weve The Return To Saudi Operation Sara Gyan Weve The Time Complexity In This Case Was To The Time Complexity In This Case Was To The Point Log In Log In For Point Log In Log In For Point Log In Log In For all elements in ascending order in all possible combinations Subscribe button More You can improve the time complexity of approach Will be coming soon as possible Like | 2024-03-20 10:33:48 | 1,286 | Iterator for combination | BitMasking | Backtracking | Leetcode #1286 |
|
7Gg2WFnX1YM | Hi gas welcome and welcome back to my channel so today our problem is maximum so today our problem is maximum profit in job scheduling so profit in job scheduling so what have you given us in this problem statement what have you given us in this problem statement here we have given you a n jobs here we have given you a n jobs here we have given you a start time like here we have given you a start time like this this this given. Okay, what you have to do is to schedule the job here so that you can get maximum profit. In this way, you have to schedule the job. Okay, so what is the return and pay here? Here you have to give maximum profit and also keep in mind that no two jobs should overlap with each other. If you are taking two jobs and are supposed to schedule both, then you Do not come in an interval. It Do not come in an interval. It Do not come in an interval. It is okay if one of your jobs ends at one point, is okay if one of your jobs ends at one point, then you then you can take another job at that point from where it starts. can take another job at that point from where it starts. Okay, Okay, then this is your problem, so do this first. then this is your problem, so do this first. then this is your problem, so do this first. example, let us understand what exactly is our problem and how can we solve it. Okay, so look here, I have taken all three examples, so let us understand each example first. Okay, so look here, what have I given you? Here, you have been given a start time, an in time and a profit end. Okay, this means that this is the job, this is the start time, this is on the index, this means that this is this van, this is the What is the start time of a job and what is its ending What is the start time of a job and what is its ending What is the start time of a job and what is its ending time? 3. Okay then there is a job time? 3. Okay then there is a job which is starting on 2 and which is starting on 2 and what is its ending time is 4. Okay then what is its ending time is 4. Okay then one of your jobs is starting on 3 and one of your jobs is starting on 3 and on 5. on 5. on 5. starting at three and where is it ending at six? Okay, so if you take this, you will make profit 50 from here, you will make 10 from here, you will make 40 from Okay, so you have to see Okay, so you have to see Okay, so you have to see how you will do the job schedule here how you will do the job schedule here so that you can make maximum profit. so that you can make maximum profit. Okay, then see what you will do here, Okay, then see what you will do here, people like this, from van to third, people like this, from van to third, you don't have to take anyone in between. you don't have to take anyone in between. you don't have to take anyone in between. can take it from three, starting point from here you can take it, okay so everything here we have taken 50 I, now this one is you and four you and four there If you If you If you want to take it, then you are want to take it, then you are looking here, is it 50, is it 10 here, would you prefer 50, otherwise we have taken 50 from here, okay, after that it is starting from 3 because this is a van, we have taken it from 1 to 3. So, we cannot take the four from you right because the timings are overlapping, so we will not take this one from here, so after this, if you are starting two jobs on three, one will give 40 profit and the other will If If If you want to take it, it is obvious that if you want to take the one worth 70 rupees, you want to take it, it is obvious that if you want to take the one worth 70 rupees, then what will you do from here, if you buy the one for 70 rupees, then what will be your then what will you do from here, if you buy the one for 70 rupees, then what will be your total profit here, it will be total profit here, it will be 50 + 70 50 + 70 = 120, okay this is what you will get. = 120, okay this is what you will get. = 120, okay this is what you will get. what do you have to do in this way? You don't have to show how you are doing, this is the maximum profit. We just have to show this. Okay, this is our maximum profit. Okay, so let's look at the gate example and understand the We will see We will see We will see what the approach can be what the approach can be then what is your van tu three four then what is your van tu three four five six then yours 35 10 6 five six then yours 35 10 6 35 10 I think I did something wrong is 35 10 I think I did something wrong is n't van tu three five n't van tu three five 1 2 3 6 3 5 10 6 9 this is 1 2 3 6 3 5 10 6 9 this is 1 2 3 6 3 5 10 6 9 this is time and A in time are ok and what will you do here, here you will make 20 profit, from here you will make 20, perfect from here, 100 from here, 70 from here, 60 from here. Okay, so you have a job, it is You You You take this, you take 13, you take one and three, you take take this, you take 13, you take one and three, you take one and three, here you are getting 10 one and three, here you are getting 10 profit, profit, then what is yours, starting from you, then what is yours, starting from you, here this is also giving you 20 here this is also giving you 20 and going up to five. and going up to five. and going up to five. why would we do this here because five is going till here, so it is possible that someone may come in between, here too we are getting 20, here too we are getting 20, so now let's take this one, okay then We can pick anyone. We can pick anyone. We can pick anyone. After three, we can also pick with three. After three, we can also pick with three. So here is our three and 10. So here is our three and 10. Okay, there is 3 and 10. Here if we Okay, there is 3 and 10. Here if we do 100 then we can pick any between three and 10. do 100 then we can pick any between three and 10. do 100 then we can pick any between three and 10. don't have to do right, then between three and 10, if we take this, if we take 100, then what will happen, it will give 10 + 100, which is your 110. Okay, meanwhile, we come to know that there are two more jobs, four and How much will it give here from six and nine, will it give a How much will it give here from six and nine, will it give a How much will it give here from six and nine, will it give a total of 132, so total of 132, so why will we pick this one, otherwise we will do why will we pick this one, otherwise we will do 130, so that we can do three to 130, so that we can do three to one, three to note, three to four to one, three to note, three to four to six. six. six. we then took six to giving 70, giving 70, how much will be your total, it will be 150, how much will be your total, it will be 150, right, 150 is your answer, so what is your problem right, 150 is your answer, so what is your problem here, this was your problem here. here, this was your problem here. here, this was your problem here. is the problem? What do we need? Okay, now how can we solve it? So, no, we can solve this problem through 01 map set. How can we do that? Look here, it depends on you, You want to take it, you do You want to take it, you do You want to take it, you do n't want to add it to the job, you do n't want to add it to the job, you do n't have a schedule, what do you have to do, you have to rule it, n't have a schedule, what do you have to do, you have to rule it, so what will you do now, look at us, there is so what will you do now, look at us, there is a job here, there is a job here, it is here, it is here, it is a job here, there is a job here, it is here, it is here, it is okay. okay. okay. here the choice is whether we take this or not, what do we want to get, we want to see the profit, so our choice is here, whether we take this or not, take this or not, take this or not, take this or not. Zero van is being built here, the same thing happens in the next step, right, we have two choices, one you take it, one you don't take it, okay, it is there too, now when you pick a job. What do you have to keep in mind in that condition, here you have been given the condition that whatever job you pick next, it should not overlap, we just have to keep it in mind, right, so we always have to keep this in mind Let's take a job. The Let's take a job. The Let's take a job. The suggestion here is that we have taken this job, okay, suggestion here is that we have taken this job, okay, we have taken this job, so we have to keep in mind we have taken this job, so we have to keep in mind that between van and three, that is, that between van and three, that is, look at three, from three starting point, you look at three, from three starting point, you can take any job which starts from three. can take any job which starts from three. See what is happening, See what is happening, we don't want any job between this, okay if we we don't want any job between this, okay if we take this then the second job should take this then the second job should not be between this interval, we cannot take that, so not be between this interval, we cannot take that, so when we pick, we will keep this when we pick, we will keep this in mind. in mind. in mind. what will we have to do to take care of this, here we will have to see which is in its in time this is three which is three which is not its load mount will come out why will we come out lower bound why will we come out lower bound why because we will see What happens in bond, any What happens in bond, any What happens in bond, any numbers, just greater number or equal number, it numbers, just greater number or equal number, it is okay, if someone is starting from three or just is okay, if someone is starting from three or just from three, then this will be our easy one, it from three, then this will be our easy one, it means just the job after that, if you means just the job after that, if you want to tick, then this is this. want to tick, then this is this. want to tick, then this is this. now if you give it a nickel, then you have to get it by nickel, so what will you do, the first choice will be that which will be its load boundary, what is its index of these three, now you can start it from the index, like right, what is it in this case? What will be its loan limit? If it is three times, then the job is starting from three. Look right here, it is starting from three times, so when it is assumed that we have taken this job, then we have taken this job from van to Now we will see that Now we will see that Now we will see that where is this just greater number, we can take it, then this lower bond will give you this nickel, then you will have the choice whether we take it or not, okay, so in this way, It will be your responsibility to It will be your responsibility to It will be your responsibility to fill this condition completely and to fill this condition completely and to ensure that there is ensure that there is no overlapping, you have to go to the load bound no overlapping, you have to go to the load bound and from there you have to pick up the job. Okay, and from there you have to pick up the job. Okay, now after going there you will decide which one you have to now after going there you will decide which one you have to pick. pick. pick. we will do whatever gives maximum. If we do not pick, will we get maximum profit? If we get it, we will take only that. Okay, so this is what happens in our 01 map set, this will be there What would you What would you What would you suggest, if you don't pick in this index then suggest, if you don't pick in this index then we can see the next one from this index, we we can see the next one from this index, we can see the next one, otherwise these two conditions can see the next one, otherwise these two conditions will become ours, so what do I do, I show you the code, I will become ours, so what do I do, I show you the code, I explain it through the code explain it through the code once. What have we done here, we have given start time, we have given in time, we have given profit, we have given these three things, your N job, your N job, what have we done here, let us what have we done here, let us create a vector. create a vector. create a vector. so that what we can do is insert it, what is the starting time, what is the in time of a job and what is the profit, we have written all three together here, like here there is also an index, this will be yours, This one will remain on the index, This one will remain on the index, This one will remain on the index, otherwise this one will remain here, so otherwise this one will remain here, so how can you store it, now how can you store it, now what will you do, starting time in time profit 20, then what can you do here, you will insert You You You can do it together, meaning you don't have to do it again and again, we will store it together, we have done it, so what will be required for this, we will so that in this job job name vector, we will so that in this job job name vector, we will insert all of them here, start time in insert all of them here, start time in time. time. time. sort this, we will sort this, the job is fine so that what we get, look here, whatever sort you will do here, it will be done according to the starting time, it is fine for you and we will also sort the starting time here. Why will we shorten this so that we can know how to make our load easy to mount? What should be easy? See how the lower mount is found. This lower mount can be called kind of. You are doing it What do What do What do we do if it remains sorted? We have to find a we do if it remains sorted? We have to find a number just greater than any number. I will number just greater than any number. I will find it, so what will we do? We will find it, so what will we do? We will do it on the basis of the starting number only. do it on the basis of the starting number only. Why will we do it because look here Why will we do it because look here when you had the suggestion that when you had the suggestion that when you had the suggestion that you pick a job, then after picking it is your time, we have to see according to it, whose red boundary will be there, then whose red boundary will be there, you will see the starting time, what will be the starting time of any job, so if you You are always You are always You are always dealing with the starting time dealing with the starting time but you are looking at the value, lower bonds are but you are looking at the value, lower bonds are coming out of it, but you are dealing with the coming out of it, but you are dealing with the starting time only, starting time only, so here, what we have done here is that we have so here, what we have done here is that we have sorted the starting time only. sorted the starting time only. sorted the starting time only. no need to start the time, okay, we have sorted it here and inserted it here along with the starting time, what will we do, here a record is just a function, find, Geo index has been inserted, this is the Geo index has been inserted, this is the Geo index has been inserted, this is the job, we have inserted all the three here, job, we have inserted all the three here, that is the one with starting time that is the one with starting time and M which is the size of and M which is the size of ours, it is ok, we will come here when ours, it is ok, we will come here when what will happen to us, I >= N will happen. what will happen to us, I >= N will happen. what will happen to us, I >= N will happen. return zero, our base condition is okay, now if we pay us any index, what do we do with it, we pick whatever you pick, okay, so in that condition, we have to keep in mind that the Find the index of the load bond of which Find the index of the load bond of which Find the index of the load bond of which we are fine, so we are fine, so what will you do in this way, you will find the index, what will you do in this way, you will find the index, what happens now, whatever is added, you do it, what happens now, whatever is added, you do it, whose fining you are doing, whose fining you are doing, you have to do it, so we are in you have to do it, so we are in you have to do it, so we are in then whatever is the second element of any index, that is our in time, right here in second, first you do start time and then you are doing in time, hence you will You are You are You are doing mines, start the mine so that you can get the doing mines, start the mine so that you can get the index, which index can you index, which index can you pick, after picking the next one, you have pick, after picking the next one, you have two choices here, whether to pick or two choices here, whether to pick or not, if you pick any index, not, if you pick any index, you will see the profit. you will see the profit. you will see the profit. where are you inserting the profit on this index, if it is on second next then you will get job I2, then you will call find now plus you are doing find index because you have selected this I, so That we should That we should That we should not take any interval in between, take it with index, what is not take any interval in between, take it with index, what is its load bound, in its load bound, in time, so here you have index people, then time, so here you have index people, then job people, start time, end people, okay, this is done for pick, job people, start time, end people, okay, this is done for pick, when you will not pick. when you will not pick. when you will not pick. will you do then what will you do then you will see from the next type i+1 people go start time n and in both of these you see the maximum, what will be your maximum profit here, okay this is done but it will give you early, We will memorize it, there will We will memorize it, there will index, so how far can the index go here, it index, so how far can the index go here, it can go till N, so here we have taken DP, we have sliced it from vector end -1 and I have I have I have also inserted it in the find. It is okay here, also inserted it in the find. It is okay here, so what will you do with yours first? If I <= N so what will you do with yours first? If I <= N then we will return zero. Here it is then we will return zero. Here it is okay, it will be yours, otherwise you will turn zero only, that is okay, it will be yours, otherwise you will turn zero only, that is why you attend zero here. why you attend zero here. First of all, you should check whether you have First of all, you should check whether you have already searched for the particular index. Do not search again and again. Right here, if you have already done so, not search again and again. Right here, if you have already done so, then we will give you the DP ID. then we will give you the DP ID. What will we do with the process? What will we do with the process? What will we do with the process? do this and we will store the value here in DP, okay, so what will happen to you, this will be submitted, so I hope you have understood, if you liked the video, then please like, share | 2024-03-19 12:02:41 | 1,235 | 1235. Maximum Profit in Job Scheduling |
|
iQyqVuAGoOQ | hello everybody and welcome back to the DC AC channel where we saw at least for DC AC channel where we saw at least for this series lead code questions to kind this series lead code questions to kind of prepare for technical interviews and of prepare for technical interviews and just learn programming software Shan's just learn programming software Shan's non-patent learn to think I guess I hope non-patent learn to think I guess I hope all right let's jump to another question all right let's jump to another question relative Frank's sounds interesting okay relative Frank's sounds interesting okay so the question is called 5:06 relative so the question is called 5:06 relative ranks given scores of an athlete's find ranks given scores of an athlete's find their relative ranks and the people with their relative ranks and the people with the top three highest scores will be the top three highest scores will be awarded medals gold medal silver medal awarded medals gold medal silver medal bronze medal so basically given an bronze medal so basically given an athlete's find the relative ranks and athlete's find the relative ranks and the people with the top three high the people with the top three high scores will be awarded medals example scores will be awarded medals example one if we have this input our output one if we have this input our output should be basically this one has the should be basically this one has the highest score relatively to the other highest score relatively to the other one so it gets too cold won the gold one so it gets too cold won the gold medal this one has the second highest medal this one has the second highest score silver medal third highest score score silver medal third highest score bronze medal this one is on the fourth bronze medal this one is on the fourth position this one is on the fifth position this one is on the fifth position position let's see the explanation the first let's see the explanation the first three athletes got the top three highest three athletes got the top three highest scores so they got god-metal silver scores so they got god-metal silver medal and bronze medal for the left for medal and bronze medal for the left for the remaining two athletes you just need the remaining two athletes you just need to output their relative ranks according to output their relative ranks according to this course and there are some to this course and there are some additional notes we know that n is a additional notes we know that n is a positive integer and won't exceed 10000 positive integer and won't exceed 10000 so we know that we wouldn't get any more so we know that we wouldn't get any more than 10,000 athletes but I'm kind than 10,000 athletes but I'm kind assuming we we could be getting 0 assuming we we could be getting 0 athletes as well so we have to account athletes as well so we have to account for that and all the scores of athletes for that and all the scores of athletes are current guaranteed to be unique so are current guaranteed to be unique so we know we wouldn't be having to worry we know we wouldn't be having to worry about any lubrication scores so how do about any lubrication scores so how do we handle that I think I I will be we handle that I think I I will be ordering so basically get these names ordering so basically get these names sorted so I will always know the next sorted so I will always know the next person that gets gets another place on person that gets gets another place on the board and to achieve this we are the board and to achieve this we are going to be sorting or in noms list going to be sorting or in noms list after sorting the list we basically know after sorting the list we basically know that our athletes are now ordered and I that our athletes are now ordered and I think it was reverse through in reverse think it was reverse through in reverse order or in descending order and now we order or in descending order and now we need to actually map them to the actual need to actually map them to the actual result of of noms so how do we do that we copy a array this would be our output we copy a array this would be our output to OB nums dot copy and after that we know that for example we have all that leads here that are sorted and for example and you can see I actually did some some programming before him but I was actually not really focused on focused on the exact definition of this task so I had to redo it anyway let's let's imagine our athletes heads these positions six one two so in other at least with the highest score so with these ones and actually I wanna order something like this so you can I have something like this so you can I have some diversity and in this case we know some diversity and in this case we know that this athlete should get the highest that this athlete should get the highest score in our array they are ordered as score in our array they are ordered as such and one so we can be going through such and one so we can be going through our array we could be getting the our array we could be getting the highest basically let's go over our highest basically let's go over our array for our soda terrain or sorted or array for our soda terrain or sorted or highest highest ranked in noms sorted okay ranked in noms sorted okay so for each one of those hmm we could be so for each one of those hmm we could be going like this or we could be getting going like this or we could be getting the very first three of them and I want the very first three of them and I want to do this beforehand because it will be to do this beforehand because it will be easier afterwards easier afterwards let's get for example four score in our let's get for example four score in our output which is a copy array we know output which is a copy array we know that if this score is equal to nums that if this score is equal to nums sorted zero it should be awarded with and score should be equal and score should be equal to gold-medal else if our score is equal second one in our sorted ranking this second one in our sorted ranking this one should be called sewer metal and also it is core otherwise is in the third position it will be awarded with bronze medal and just to kind of see that that this works I want to just quickly test that what are we getting we're just gonna leave those three and [Music] yeah we're just going to test it like uninvent sorry this is all indented a uninvent sorry this is all indented a bit too much I guess okay bit too much I guess okay oh well I guess we'll be getting an oh well I guess we'll be getting an index and we are enumerated so we know index and we are enumerated so we know exactly where we are and we can exactly where we are and we can basically save things this way and if basically save things this way and if you guys haven't seen the narrate you guys haven't seen the narrate function before it's a very useful function before it's a very useful function it will basically go over function it will basically go over through each of these guys but it will through each of these guys but it will also count indices so you can actually also count indices so you can actually say stuff using the indices if you need say stuff using the indices if you need to and in this case we definitely need to and in this case we definitely need to and as you can see there were silver to and as you can see there were silver gold and bronze medal exactly as as we gold and bronze medal exactly as as we hoped to have them awarded what else do hoped to have them awarded what else do we need and I'm actually not going to be we need and I'm actually not going to be doing it this way or yeah I'm just gonna hard-coded maybe we can make it a bit better like after afterwards if the lengths our numbs is zero we will just return an empty an empty list and we know this needs to be done because for example if you didn't we just have empty amount of athletes here we would be well we're actually returning the same thing so I I just forget about it I think we're actually good even like this let's just test it so if this was some empty lists we should be getting a copy out of an empty list here we wouldn't real iterate and we get the output okay so these are the first three and after we are done with those first three I would actually I just wanted to test this for example we I want to basically pop the first I want to basically pop the first element a couple of times and I want to element a couple of times and I want to see what our array how our array looks see what our array how our array looks like at the end and as you can see we like at the end and as you can see we actually popped some elements from the actually popped some elements from the array from the very beginning so we're array from the very beginning so we're actually gonna gonna be doing this actually gonna gonna be doing this either we are going to be doing this either we are going to be doing this like that or I'm going through let's see like that or I'm going through let's see so we know that our elements here have so we know that our elements here have different order different order and for each of those we need to find and for each of those we need to find them so wait they are ordered now right them so wait they are ordered now right and we know that this one will get the and we know that this one will get the fourth position but we also need to find fourth position but we also need to find it so what can we do we actually we can it so what can we do we actually we can go over to the for each rank over our go over to the for each rank over our sorted nums but we will be starting from sorted nums but we will be starting from the third one until the end why do we the third one until the end why do we start from the third one because from start from the third one because from the four form because the first three we the four form because the first three we already took care of and for each of already took care of and for each of those we are going for score again index those we are going for score again index score in enumerate and in this case we score in enumerate and in this case we are using nums because if we were are using nums because if we were enumerated over and we you see why and I enumerated over and we you see why and I say that because now we are looking that say that because now we are looking that if our score well our rank and the rain if our score well our rank and the rain could be four here right if our rank for actually no it's actually a score again actually no it's actually a score again but this core also has I a rank and the but this core also has I a rank and the rank would be accounted as let's start rank would be accounted as let's start as a rank that would be set to be zero as a rank that would be set to be zero four and or even three we know that we four and or even three we know that we we have given three ranks already and we we have given three ranks already and we are updating our rank and we are on the are updating our rank and we are on the fourth rank fourth rank we know that the score here is two and we know that the score here is two and the rank is four so we need to find the the rank is four so we need to find the one that has the score of tool and one that has the score of tool and assign it the rank for right and if we assign it the rank for right and if we do this in our very first array then we do this in our very first array then we we run into the problem that we are we run into the problem that we are basically creating values that we are basically creating values that we are looking for afterwards so it is better looking for afterwards so it is better to have a basically a third array where to have a basically a third array where you can be doing this substitution right you can be doing this substitution right this one would be five to put it here in this one would be five to put it here in this case we don't really see anything this case we don't really see anything wrong wrong this one of course would be silver gold this one of course would be silver gold and bronze but there would be definitely and bronze but there would be definitely overlaps if we were using our initial overlaps if we were using our initial array so it is better to have this array so it is better to have this copied array which would also be the copied array which would also be the output array so we are going over each output array so we are going over each score in our sorted array starting from score in our sorted array starting from the point after those medals and we know the point after those medals and we know the rank that has to be assigned and now the rank that has to be assigned and now we are looking for a score in the we are looking for a score in the original array and we know if the score original array and we know if the score well score sorted or ranked score input or initial so we know that if the score we can actually substitute this rank or we can actually substitute this rank or basically the value that was in our basically the value that was in our output array and this would be our output array and this would be our output on the on the position of index output on the on the position of index and this would be then our rank and the and this would be then our rank and the rank would be also a string so looking rank would be also a string so looking at this we are basically assigning ranks at this we are basically assigning ranks we are counting for the ranks and of we are counting for the ranks and of course we can actually do a continue in course we can actually do a continue in this case because after we find the rank this case because after we find the rank we know there are no duplicating ranks we know there are no duplicating ranks we can actually break this and after we we can actually break this and after we are done with this basically score out are done with this basically score out for our ranks we can go to the next one for our ranks we can go to the next one and and actually since here we are yeah and and actually since here we are yeah since we are actually done with since we are actually done with searching in our initial array we can searching in our initial array we can actually you know go to the next ranked actually you know go to the next ranked integer we can actually break this loop integer we can actually break this loop and just go over to the next one and and just go over to the next one and quickly I really just want to test it quickly I really just want to test it out see if that works out see if that works the way it was intended and let's say the way it was intended and let's say for example we have 1 & 2 we have them for example we have 1 & 2 we have them ordered like this hopefully we didn't write anything in the output array like we didn't mess up the the values but I don't think we did yeah so as you can see this is the first place gold medal the second place your medal third place is the bronze medal and then of course this one is the next one to go on the fourth place in the fifth place and how are they ranked the forefront the fifth place well we know that we actually already assigned those three three places the very first three places got to Scientology for this one which is here this is correct we we were taking it from our sorted array we know it's a a - so the score rank score is - the rank itself was basically four because it's the fourth ranked position and here we are looking for where in our anniversary can we find the tool that we are looking forward to put our score rank basically for and we are seeing that it is found on the index position of one so we can use this index position of one and update our output array and basically this is it one once we find this element we don't have to go over to the next one and like we you know we don't really need to search over to through the whole array so you actually break the algorithm basically this loop and we go over to the next element the next element is one it's it gets the rank five because it's got updated twice basically now and we are looking for a five I'm sorry we are looking for a one in this array when we see it's on the index zero so we can use the zero index and put the rank five there yeah so this is basically our algorithm it's a bit kind of it's not the best I think I wouldn't really see any way to do it in one line but I think at least we will get a version that is working and I was actually not that easy I really think I thought it was a way easier algorithm at the beginning and maybe I'm still overlooking something but yeah it was still an interesting algorithm and you can definitely see like you can definitely do solutions for example just having a rank like a fixed rank and just going over the whole list of contestants and just finding the biggest one and always assigning the next rank and the next rank but I don't think well actually no I don't think this would have been a better solution sorting definitely helped and I think you can actually do more magic with the sorted array as is I just don't have it in my head right now I should definitely start making those videos so the beginning of the day are not at the very end but anyway that's for me I hope you guys learned something and I hope it was educational definitely try this algorithm yourself I think it's not as easy as it looks like probably like just watching once you start thinking about it you see that it's tricky to get a hold of all the ending at the hold of the values positions and I like their relevance in the whole idea and actually not not mess up swapping values that that are essentially needed for later and stuff like that so yeah it was a good time coding this algorithm I hope you I hope you found that useful if you are new to the channel maybe consider subscribing it will definitely help me a lot I just hit my head a subscriber go and this sounds like amazing to me already but I'm already looking towards the next goal which would be 20 subscribers so if you could help you with that that would be awesome but also thanks to everybody that subscribe although most of you are kind of like friends or family but it doesn't really matter thanks it to everybody and yes | 2024-03-22 16:06:19 | 506 | 506. Relative Ranks | Python + Leetcode Technical Interview Practice |
|
s27_K3ZPLEQ | Hello hello friends welcome to my YouTube channel subscribe channel subscribe [music] subscribe to [ 210 cigarette 210 cigarette gutkha tujhe 30th september ko hua tha loot lo woh to desh bech open na small different or woh to desh bech open na small different or divisible by that the looters Exit age no Exit age no Exit age no Sachin treatment for oo Sachin treatment for oo Ajay Ajay will be the same This is quite simple but only up to will be the same This is quite simple but only up to provide 2001 Then which fast food you need Then which fast food you need Number Number two again length in number one number one go from Karte's side and we will go back to whatever description is on the last day, whatever is its length, then we will number channel is channel is subscribe, subscribe and our then if we go to the second one, then then if we go to the second one, then Descendent that Meghnad Descendent that Meghnad is okay, is okay, then we have not added 5151, now we quote 21 times in China also that the truck, it will never be divisible by two If you add then you will not be If you add then you will not be If you add then you will not be free, then it is not a force, but it is free, then it is not a force, but it is not complete, neither by doing this, there is not complete, neither by doing this, there is no such number which can ever happen and no such number which can ever happen and same to store 5, if I have time written in it, Someone joins from there, this is the Someone joins from there, this is the Someone joins from there, this is the role, it happens with one, then with two, role, it happens with one, then with two, okay, the last line number should be one okay, the last line number should be one and the favorite is simple, the class number and the favorite is simple, the class number should be five or should, so we will go with this check, should be five or should, so we will go with this check, then the first question is simple. then the first question is simple. then the first question is simple. that we will increase towards the length, in this, if we get that number, we will not get one number, if we would have taken 5 more inches, then if the guest is more than that length, then do that. Humble request towards that. After implementing tow, we will use it to see how we can optimize it and if what we have done by coding and in many places, we book tickets in Tehsil Aliganj or use Ticket and Sita, then If we If we If we can, then first of all it is simple that can, then first of all it is simple that if I see this, it is divisible by if I see this, it is divisible by two or if it is white on Thursday, then actually what do we want, we want 250 then actually what do we want, we want 250 then it should not be if this is right there, then it should not be if this is right there, brother, we have returned. brother, we have returned. brother, we have returned. now we have simple so how can we do this by subscribing to the one and a half inch plus top number, now we are on this number till one, one, now how long will we continue until that now how long will we continue until that Number is truck campaign will simple check that number is this number what job we saw so there that number is number plus app will remove one ego here number * on time ink tank plus one When we I get it, then you because I thought that it is necessary that your input poking of these points 1420 then the starting number okay, still the number is coming off. starting same time is starting same time is ok time limit ok time limit now one property some number now if it now one property some number now if it takes time while going there then it took 10 time then how can we use it then we can appoint if it If we If we If we can do it to optimize, then whatever number I have, it is can do it to optimize, then whatever number I have, it is important to remove its notification number, now the city magistrate is directly completed, now the city magistrate is directly completed, but if we can get pass 20% in this, then let's do it again and If you do then it can be another then it can be another and now we come with another approach, and now we come with another approach, we teach with the help of demand, support we teach with the help of demand, support comes to us, if comes to us, if we subscribe, we will we subscribe, we will do it, now we have done it to those who subscribe to our channel, like and So So So then subscribe point two plus loot and fry for 15 minutes. came to the trailer, one fit, we had 700, then 366, so we offered the loudest or had 700, then 366, so we offered the loudest or 21. This proves that 21. This proves that If we had done it then our length would have been If we had done it then our length would have been earlier we had seen that we always do that which of these is cheating, this is SIM, if we go to the bottom Space complexity is like, Space complexity is like, Space complexity is like, whatever length is there then whatever length is there then subscribe this way so that will be our number. subscribe this way so that will be our number. check on the same that which number is A [Music] Picture in A plus one is how is it divisible or not Jhal that if is if Also we saw the number, it comes to zero, Also we saw the number, it comes to zero, Also we saw the number, it comes to zero, then it is ok, we will return, whatever the then it is ok, we will return, whatever the situation, when the situation, when the calculator calculator came to the minute, we commented the calendar, ok, came to the minute, we commented the calendar, ok, so what we were deciding here while I am in so what we were deciding here while I am in trouble was that if When the number comes to zero then it When the number comes to zero then it When the number comes to zero then it is okay to request us and every is okay to request us and every time we increase the length of this then I then I have oh I will just keep mixing but now we had So So So that we can check the feel maximum to them that we can check the feel maximum to them now in the school or again to in again now don't do it again first you have to take meanwhile assigned that whatever hit will be equal to the same after all now we just have to type That if whatever we now index number is if it is that we will set one whenever we do the middle then if it is not then you are trapped in this fact - make it 110 otherwise you close every number whenever we Stay, we will give the best adv1 by asking that you Stay, we will give the best adv1 by asking that you Stay, we will give the best adv1 by asking that you want, you have muted the volume, want, you have muted the volume, don't repeat it again, you don't repeat it again, you can also arrest that this increase has happened, I can also arrest that this increase has happened, I kept fast in the valley, I did not get robbed, so hey, similar, kept fast in the valley, I did not get robbed, so hey, similar, I have to do something, so This is what we need, till then we submit. From now on, if we exceed the time limit and according to the address, the first SIM was very simple because first SIM was very simple because we only had [music], Or Or Or no, it is not no, it is not available and if it is available and if it is 125, then we are the subscribe, thank you will give to someone, how to someone, how to do it while subscribe and subscribe to. | 2024-03-25 14:50:01 | 1,015 | Leetcode 1015: Smallest Integer Divisible by K |
|
IX4xiwBVV3g | so hello everyone in this video i will be explaining the in this video i will be explaining the problem closest desert cost problem closest desert cost so this problem is not that difficult so this problem is not that difficult but it can be a little bit but it can be a little bit confusing uh because of this part lower confusing uh because of this part lower one so one so anyway let's briefly discuss the problem anyway let's briefly discuss the problem so what the problem is saying that you so what the problem is saying that you have to make a desert and have to make a desert and for a desert you have to buy a base and for a desert you have to buy a base and a topping okay a topping okay so you have been given base costs uh so you have been given base costs uh that is in this vector and topping cost that is in this vector and topping cost that is in this vector that is in this vector okay and you have been given a target okay and you have been given a target that your purchase that your purchase should be closed closest to this target should be closed closest to this target okay okay so upper in the purchasing part i can so upper in the purchasing part i can buy buy uh i have to just definitely buy one base base okay and uh and then i have to buy toppings and for each topping there are only two in quantity so i have to buy zero one or none of each topping and then i have to such that that the cost is nearest okay so since the constraints in this video are pretty low it's it suggests me that i can generate all types of combinations of purchase and then from all these combination i will choose the one whose difference to from target is the least okay so what the idea is going to be that i will generate all sorts of costs that are possible using any given data and then i will uh store it and then i will take the one which is closest to the target so my first uh the first part to solve this problem is going to be i will make an ordered set unordered underscore set and costs so what this will store is the all possible costs that are that are possible and i will make a int difference is equal to 1 e9 so this difference will store the minimum difference that is possible from target for any particular cost that for any particular purchase combination so now what i am going to do is that i am going to make an amount is equal to 0 variable then what i will do is that i will traverse from so since i have to choose only one base cost base so i will just traverse through my just let me rename this to bc and bc because it's very long name so entire is equal to 0 i less than bc dot size i plus plus so i'm choosing uh basically i'll be choosing my base co bases one by one so to calculate further calculate all the combinations i will write a function called solve so in solve i will be passing my topping topping cost dc and amount amount for that particular base cost will be amount plus bci comma comma what 0 0 is the index of the topping cost it will start from 0 and target okay so now what i will do is that i will make this function void it will be a recursive function to solve vector and ampersand dc comma int amount comma int index comma into ampersand target okay so since it is going to since i am going to generate all sorts of combination uh this will be a recursive so a recursive has two parts base condition and choices okay so choices so just one second let me close so what the base condition is going to be so the base condition is going to be basically if index is greater than equal to tc dot size so that if that is the base condition if i write uh if i arrive at the base condition i will do something so i will what i will do is that i will explain so my choices what can be my choices so my choices can be solved so i can i can choose not to buy any toppings so that will result in amount being same and index will increase by one index will increase by one comma target another choice can be that i can buy one topping of that particular type so what will that uh from that what uh my amount will increase by one so tc index my like my amount will become increased by tc index price and again my third choice can be control c ctrl v uh into two just a second into two so these are my all possible choices and then i will return so what is my base condition is going to be so after making all these choices i will reach i will cross or the toppings topping vector and once my toppings factor i have processed all the topping prices all the combinations what i will do is that i will store the amount that i have arrived at into my costs unordered set so cos dot insert amount and i will also update my difference that how close is my amount to the target so that will be difference is equal to minimum of minimum of difference comma absolute of what amount minus target so this is the part and now once i have completed all generated all the combinations so what i'm going to do is that if what target what target minus difference is equal to true minus difference is equal to true so for example just imagine that uh for so for example just imagine that uh for example example the target is 10 okay the target is 10 the target is 10 okay the target is 10 and the minimum difference that is and the minimum difference that is possible from generating possible from generating all sorts of combination is one okay so all sorts of combination is one okay so in that case in that case if one is the com one is the if one is the com one is the like difference then there can be two like difference then there can be two possibilities that there is some cost possibilities that there is some cost of 9 available or 11 okay so in this case i will prefer to return 9 because that is the lower one and it has been given in the problem that if there are multiple costs that are at the same distance from target then return the lower one so that is what i am doing if so in this case i will return what target minus difference and if that is not uh that 9 doesn't exist then 11 must exist so in that case i will return target plus difference so that's the problem let's check for any syntax errors so it's accepted so you know this so it's accepted so you know this problem is problem is simple initially i was thinking that the simple initially i was thinking that the target other my possible cost target other my possible cost combination can't be above combination can't be above the what the target so that led to the what the target so that led to my wrong submission in my first attempt my wrong submission in my first attempt but you know you should think about but you know you should think about recursion recursion and you should you should not be afraid and you should you should not be afraid because since the constraints are because since the constraints are very less you can go exponential it will very less you can go exponential it will be 3 raised to be 3 raised to n into m m into 3 h 2 and time n into m m into 3 h 2 and time complexity complexity so if the problem is super clear please so if the problem is super clear please consider subscribing this channel and consider subscribing this channel and thank you and have a nice day | 2024-03-22 14:30:02 | 1,774 | LeetCode 1774. Closest Dessert Cost | Weekly Contest 230| Medium | Algorithm Explained | C++ |
|
qQ15ggXvAU8 | hey hey everybody this is larry this is day day nine of the lego daily challenge hit the nine of the lego daily challenge hit the like button the subscribe button join me like button the subscribe button join me on discord let me know what you're on discord let me know what you're thinking and what you're feeling and all thinking and what you're feeling and all that good stuff uh happy that good stuff uh happy uh happy mother's day for those of you uh happy mother's day for those of you uh in the country that celebrated i uh in the country that celebrated i guess um to all your mothers out there guess um to all your mothers out there and stuff like that and yeah uh and stuff like that and yeah uh and if yeah just a quick re-log update and if yeah just a quick re-log update as i usually well maybe not usually but as i usually well maybe not usually but i try to do from time to time uh the i try to do from time to time uh the contest yesterday was kind of a disaster contest yesterday was kind of a disaster in how they ran it um but you know uh in how they ran it um but you know uh these things happen don't don't get too these things happen don't don't get too stressful about it uh stressful about it uh take it as free problems and just you take it as free problems and just you know it is what it is you know um know it is what it is you know um sometimes sometimes sometimes it's just something like silly sometimes it's just something like silly and people you know make a minor change and people you know make a minor change and it does it all the time it doesn't and it does it all the time it doesn't have to be something structural like have to be something structural like there are definitely times where like there are definitely times where like i don't know i don't know some it could be even something as silly some it could be even something as silly as like the front end changing like a as like the front end changing like a minor thing so that it makes two minor thing so that it makes two requests instead of one request and then requests instead of one request and then now every and then now every and then and the the the thing with these things and the the the thing with these things is that some and i'm not saying that's is that some and i'm not saying that's the case that happened here but then now the case that happened here but then now uh you okay double the request is uh you okay double the request is obviously bad but even then it actually obviously bad but even then it actually because because certain people were seeing certain people were seeing uh there's these like runaway effects uh there's these like runaway effects where you know latency goes up so then where you know latency goes up so then people click on re-spam that refresh so people click on re-spam that refresh so now now that that extra request now leads to that that extra request now leads to like ridiculous about requests right so like ridiculous about requests right so sometimes these things are hard to kind sometimes these things are hard to kind of uh happen and of uh happen and and yeah maybe they'll learn from it and yeah maybe they'll learn from it we'll figure it out it'll be it would be we'll figure it out it'll be it would be very interesting to see if there's a very interesting to see if there's a post-mortem um but yeah these things post-mortem um but yeah these things just happens it is what it is people just happens it is what it is people kind of take all these things for kind of take all these things for granted but uh yeah granted but uh yeah anyway anyway let's look at today's problem letter let's look at today's problem letter combinations of a phone number okay i combinations of a phone number okay i mean this reminds me of the picture that mean this reminds me of the picture that we just had on that contest that didn't we just had on that contest that didn't or hopefully it doesn't count because i or hopefully it doesn't count because i started very late but started very late but uh yeah i don't know why they don't i uh yeah i don't know why they don't i think think they should make these accessible they should make these accessible in general and what i mean by that is in general and what i mean by that is they should make it like not an image they should make it like not an image they should like they should like have a way to describe this without it have a way to describe this without it being an image um being an image um but it is what it is i suppose for now but it is what it is i suppose for now uh and especially since it's very easy uh and especially since it's very easy to miss to miss just like looking at this and maybe if just like looking at this and maybe if you're on a weird or just different you're on a weird or just different platform or maybe browser sometimes platform or maybe browser sometimes there's a lot of inconsistencies but there's a lot of inconsistencies but okay but let's say okay let's actually okay but let's say okay let's actually read the problem given numbers two to read the problem given numbers two to nine we saw all the possible letter nine we saw all the possible letter combinations that could return um okay combinations that could return um okay so a two could be an abc okay uh so now so a two could be an abc okay uh so now we have to type this oh even though you we have to type this oh even though you know know uh uh yeah okay so we have just have to do a yeah okay so we have just have to do a lookup and then we do a brute force uh lookup and then we do a brute force uh one at a time this should be pretty one at a time this should be pretty straightforward in that regards um straightforward in that regards um at least in terms of understanding right at least in terms of understanding right it's just brute force it's easy to it's just brute force it's easy to to uh to uh it's easy to uh uh uh it's easy to uh uh uh you know know what brute force means so you know know what brute force means so a is equal to abc and now we're just a is equal to abc and now we're just doing the like annoying thing doing the like annoying thing uh uh i feel like in other contexts they i feel like in other contexts they usually give you this mapping but maybe usually give you this mapping but maybe i'm wrong on that one i'm wrong on that one um um oops also like if this was during a contest i'll be a little bit sad only because you know this is like i don't know maybe we should like should this be a thing that i already have ready i don't think so that would be like wasting so much time that would be like wasting so much time typing and also like if i have a typo typing and also like if i have a typo this would be a really silly thing to uh this would be a really silly thing to uh to have to debug right so yeah to have to debug right so yeah okay i think this is right abc e f g h i okay i think this is right abc e f g h i j k l m n o p q r s t u v w x y and z j k l m n o p q r s t u v w x y and z okay now i know my abcs okay uh yeah so okay now i know my abcs okay uh yeah so then now it is just then now it is just recursion right recursion right um yeah so then now um yeah so then now we have a recursion we have an index mapping to the number of the digits and then the current uh array maybe cut um and yeah and then now we do we we cut um and yeah and then now we do we we want to request in a serial digit and want to request in a serial digit and then we start with an empty array then we start with an empty array and that should be good and then and that should be good and then and we also have a and we also have a i'm not i'm not for these pro i mean i know that for these pro i mean i know that sometimes i like to especially on tree sometimes i like to especially on tree like problems i like to keep things like like problems i like to keep things like women state and then recursion based on women state and then recursion based on that and then you know combine them that and then you know combine them together it is cleaner but there is a together it is cleaner but there is a lot of overhead especially when you're lot of overhead especially when you're dealing with linear e type things and dealing with linear e type things and you're creating a lot of objects so you're creating a lot of objects so that's why i'm not going to do it here that's why i'm not going to do it here uh and also maybe i'm just a little bit uh and also maybe i'm just a little bit lazy but yeah um if index is equal to n lazy but yeah um if index is equal to n then then we appen we appen this and then we return does this have this and then we return does this have to be sorted in any way or just in any to be sorted in any way or just in any order or in any order okay i mean that i order or in any order okay i mean that i think we'll be keeping it sorted anyway think we'll be keeping it sorted anyway but um but yeah for but um but yeah for c c in in lookup of digits of index um we do a recursion on index plus one uh let's say current we want to append c of course technically speaking if you of course technically speaking if you want to do micro optimization we should want to do micro optimization we should um we should have a fixed length away and then just keep on modifying your w a little bit cleaner but uh but yeah that looks good for that one there's empty and we can even play around with more for these problems i also feel like they should have sevens and nines because and even eights just because like like i feel like like this isn't supposed to be a trick or like maybe not particularly to notice that this is four letters and four letters and eight has three letters right so i think that would have been good to test um i am getting a wrong so that's good that we're getting a so that's good that we're getting a wrong answer i suppose oh i just thought wrong answer i suppose oh i just thought that that's out of the way that that's out of the way and what are we and what are we getting wrong on how ow huh okay so that the wrong answer is actually unrelated in the sense that it is doing with huh [Music] because i'm doing an empty string instead of i'm just trying to think how i want to i'm just trying to think how i want to do it i guess it's okay to just shortcut do it i guess it's okay to just shortcut it right does this yeah can i change the base case of that i this is gonna be the same if we just put this is gonna be the same if we just put like a length of current as you go to like a length of current as you go to one or something like that so i'm just one or something like that so i'm just gonna do it this way it's about the same gonna do it this way it's about the same all right let's give it a submit all right let's give it a submit hopefully this is good on the first try hopefully this is good on the first try i feel like i've been sloppy lately um i feel like i've been sloppy lately um cool 760 769 day streak cool 760 769 day streak during recursion um this is going to be during recursion um this is going to be exponential um exponential um only because that's only because that's the size of the output so you can't the size of the output so you can't really do much faster um in terms of really do much faster um in terms of space same thing it's going to be three space same thing it's going to be three to the n or four to the n or some you to the n or four to the n or some you know like know like uh something like that technically fall uh something like that technically fall to the end as opposed because you want to the end as opposed because you want to do the upper belt but to do the upper belt but that's like the lower band right so uh that's like the lower band right so uh so yeah can we do better than that so yeah can we do better than that um let's see um let's see yeah i did the same thing except i added yeah i did the same thing except i added the thing here i probably noticed the i the thing here i probably noticed the i mean they give it they give it to you in mean they give it they give it to you in the input so the input so yeah and actually it's a little bit yeah and actually it's a little bit whatever but okay whatever but okay um um cool that's all i have for this one let cool that's all i have for this one let me know what you think hit the like me know what you think hit the like button hit the subscribe button join me button hit the subscribe button join me on discord hope you all have a great on discord hope you all have a great week this is going to be my last i week this is going to be my last i should have done this during the vlog should have done this during the vlog but this is going to be my last video in but this is going to be my last video in new york for a couple of weeks so i'll new york for a couple of weeks so i'll see you soon and my setup will be a see you soon and my setup will be a little bit different uh little bit different uh yeah as i usually say stay good stay yeah as i usually say stay good stay healthy to good mental health i'll see healthy to good mental health i'll see you later and take care bye | 2024-03-19 16:00:56 | 17 | 17. Letter Combinations of a Phone Number - Day 9/31 Leetcode May Challenge |
|
Sa3tEYqLVjg | easy question easy question easy question another hard question you're kidding probably another dp question up to a thousand words up to a thousand words each string is a thousand as well it's each string is a thousand as well it's definitely dp but what would this sub definitely dp but what would this sub problem be i guess would be on the problem be i guess would be on the target word so dp target word so dp of i could be of i could be i guess a number of ways i guess a number of ways to get to get prefix prefix [Music] [Music] target target um 0 to i um 0 to i and then what would the transition be so and then what would the transition be so when i add a new i don't think i can do it like that let's say for example i have the entire dp ray is 0 0 0 let's get rid of this i go through the first column of the matrix is a duplicate is a duplicate if i see an a i would have to go through if i see an a i would have to go through all possible a's within the target all possible a's within the target string string and see what the previous value is and see what the previous value is uh so i see the b here when c and a go uh so i see the b here when c and a go through all possible values of a in the through all possible values of a in the target string and add what the number target string and add what the number before that was so this a before that was so this a i try to add some the number before that i try to add some the number before that but there is none so i just add one so but there is none so i just add one so that's a base case that's a base case that's why this is two and then i see an that's why this is two and then i see an a here a here i'm trying to add a one from the i'm trying to add a one from the previous one previous one hmm hmm no that doesn't work no that doesn't work i have to keep two copies because this b i have to keep two copies because this b came from the same row this is the came from the same row this is the previous this is from the previous previous this is from the previous column column and then i make a new copy when i see a b i want to add to the new copy the previous value i came from b so that will be an a here and i'll be one and then when i see an a here i want to add to this a the previous value which is this one and that's zero so that remains zero and this one i want to add the previous value but this is the first letter so which means i actually just want add one right so that's so this is new updated dp array i replace the old one with the updated and then i create a new copy i've made a new copy so now i can go on to the next column next column is cbc uh the only relevant values here x is actually just a b so i go through all possible b's in my target string there's b and i add on the previous value so one plus a two i'll be three so that's saying that there are three ways to get the string a b from the first three columns of this matrix and is that true well we have a b that's one way you have a b that's two ways you have a b that's three ways so now let's replace the old dp array with the new and make a copy of the new one like so then we can move on to the last column we have aba so i see an a for the first one here it's the first letter so all i have to do is increment that to b3 for this a i want to add the previous one which is three i see a b this b i can add two to this b so this is five and for this a now now c and a again so then for the first a i want to increment that to be four and for the other a i can add the previous ones which is going to be six so four five six and there's six ways to do that that's correct let's try the different example this one seems good so apparently the 16 ways to get abba and we'll just try do it a little quicker this time so that my dp area is going to be zero zero zero initially i have two copies so just be a two for the first column then replace the new old with the new and then within i see i have a b here so this will be a two and then i have an a so this increments by 1 have a b here so that means this is an hour 4. i see another a's and this is 4. that makes sense because four different ways to get an a b so f a b that's one if a b that's another one a b that's one you have a b that's another one so there's four different ways okay and place that copy the third column we have an a here so increment this by one um f of b or make sure this is now an eight and this is now a four see another b so then i have to do that again it's now 12 and this is now an eight and then i see an a so this increments by one and this a increments by zero and then i update the old one and make a copy i'm not to the last column now so i have a b this b here i want to add 6 to this b so we have 12 plus 6 which is 18 so that's f plus 3 so of i i guess so let's make this i for this one i add um c to eight okay that's getting out of hand sir so this one would be um 18 which and this one would be 8 plus c i see an a here so then this would be i see an a here so then this would be zero plus eight that's going to be eight zero plus eight that's going to be eight and and another a so this is going to be and and another a so this is going to be 16 16 and then i'm going to see another b so i and then i'm going to see another b so i add to these ones 18 plus 6 which is 24 add to these ones 18 plus 6 which is 24 and then i have 20 plus c and then i have 20 plus c which is going to be 32 which is going to be 32 but that's 16 and that's the answer so but that's 16 and that's the answer so that kind of works out the only thing that kind of works out the only thing left to do is um left to do is um optimize it just a little bit so optimize it just a little bit so one thing you kind of notice is that one thing you kind of notice is that there's only lowercase english letters there's only lowercase english letters so actually i could keep track so actually i could keep track how many a0 how many b's there are so how many a0 how many b's there are so what we can do is actually what we can do is actually break this down a little bit so that we break this down a little bit so that we have have an alphabet a b c p e dot dot how many an alphabet a b c p e dot dot how many a's do we have in the first column there a's do we have in the first column there are two how many b's there are two and are two how many b's there are two and the rest is zero and that's the first the rest is zero and that's the first iteration iteration okay and then for the second column i okay and then for the second column i do the same and i see there's two a's do the same and i see there's two a's and two b's okay good and for the third and two b's okay good and for the third column i see there's two a's to be so column i see there's two a's to be so it'll be the same like this and for the it'll be the same like this and for the fourth columns two a's two b's fourth columns two a's two b's so it looks like this as well so what i so it looks like this as well so what i have is a vector of arrays of size 26 have is a vector of arrays of size 26 and each one denotes the frequency of a and each one denotes the frequency of a letter so they have something like this letter so they have something like this and then for the target array and then for the target array what you can have is 26 vectors a b c d what you can have is 26 vectors a b c d e where each letter here denotes a e where each letter here denotes a vector vector and these vectors would be and these vectors would be for a how what positions well there are for a how what positions well there are in the target string so this will be in the target string so this will be zero zero and one and and one and and three i think zero one two three and three i think zero one two three for the b here what positions there are for the b here what positions there are um well i have one and two so each one um well i have one and two so each one is a vector and so this vector this is a vector and so this vector this column is a vector and i think i have to column is a vector and i think i have to return the answer uh modulo something return the answer uh modulo something 10 to the power of 9 plus 7 and i think 10 to the power of 9 plus 7 and i think i can take the modulus i can take the modulus as i go along so let's first as i go along so let's first make this array make this array so let's um so let's um do for int i is equal to do for int i is equal to zero i less than words dot size squares i or into j is equal to zero j less than words i dot size source j and create a vector called frequency a vector of vectors of int called frequency and how many vectors are there there's going to be words dot size vectors each one is a vector of 26 characters initialized zero frequency so what we actually do is um actually swap these nested arrays so that we have a g j going from word zero dot size because all the words are the same length then do this in the inner array so this is essentially now going through each of the columns one by one so if i do words at i j i'm going through the columns then i could say the frequency at this word of um this column and this column is given by j were frequency of words i j minus a so since it's in in ascii i just turn it into a range from 0 to 25 and just do a plus plus on this to increase the frequency now that i have that i can make a vector of vectors called position um how many vectors should there be 26 should be 26 vectors empty filled with empty vectors i just want to go through the target word and i want to do position um at this word so target i minus a dot pushback this position i so i'm recording the positions of the letters found within the target and then let's create our dp array called current and previous i guess vector of int of target.size and we'll initialize the of target.size and we'll initialize the zero and also the current zero and also the current [Music] [Music] the same way and then i go through each the same way and then i go through each of the columns one by one so now i'm going for the first column which means i go through all letters of the first array within frequencies wait this is wrong this frequency is a number of columns so this should be target.size this one this can also be target.size it's the same thing actually go through all the letters go through each of the letters and for each of the letters go through each of the positions within target string which is given by position of l for end p in position of l just do the current just do the current at i at i at p plus plus uh no not plus plus plus equals to the frequency which is given by uh frequency of this columns this letter else the current at the position plus equals to p minus one the previous position times p minus one the previous position times the frequency the frequency at i at i well well cool cool cool cool so once i've filled out the current so once i've filled out the current um it should be previous actually i'll um it should be previous actually i'll make the previous equal the current and make the previous equal the current and then at the end return the current at then at the end return the current at the last value which is the last value which is target target dot size -1 um i kind of went out drinking yesterday so my brain is not working at all i thought yeah this confused me a little bit so you have the same like the words in target but the words within words may not have the same length as target there may be a lot more columns than i realized that all strings and words have the same length so this actually should be uh words zero dot size it should be words zero size not target size should be uh okay so that's working okay so that's working um let's try this um let's try this aba so this one's the big one hopefully aba so this one's the big one hopefully we get 16. okay cool cool um let's do the modulus thing so it's working so i actually want long long as an ll long long as an ll and then for the dp values they could and then for the dp values they could get pretty large so get pretty large so see this is ll see this is ll actually i could just do here current p actually i could just do here current p is equal to is modulus equals to mod and is equal to is modulus equals to mod and that here i could say what mod is so that here i could say what mod is so it's const static it's const static and mod is equal to one e nine and mod is equal to one e nine plus seven plus seven i should have um actually gone through i should have um actually gone through and and checked what the time complexity of this checked what the time complexity of this is i think it's good enough because is i think it's good enough because words zero dot size is up to a thousand words zero dot size is up to a thousand so you have a thousand times twenty six so you have a thousand times twenty six times a thousand potentially but uh most times a thousand potentially but uh most likely less so it's um likely less so it's um n squared times twenty cool cool let's n squared times twenty cool cool let's uh give that a go awesome awesome that's fantastic hard question on the first go yes yes i'm on a roll i don't know but this one took about an hour and 20 minutes but yeah thanks for watching like and subscribe and i'll see you in the next video and don't forget to keep eating | 2024-03-19 15:47:12 | 1,639 | 1639. (Hard) Number of Ways to Form a Target String Given a Dictionary - Daily Leetcode (Day 75) |
|
i-mr_aRWX3M | [Applause] foreign [Music] so today we are going to talk about this problem it is called a reverse integer so let us in the description so given a signed uh 32-bit integer x i written x with its TZ reversed okay if reversing X causes the value to go outside the sine 32-bit integer range the range is minus 2 power 31 to 2 power 31 minus 1 then written 0 okay otherwise just show the Reversed integer okay assume the environment does not allow you to store 64 integers signed or unsigned 64-bit integers okay example they are given X is one two three output is three to One X is minus one two three output is minus three to one okay for 120 receiving 21 okay so and constants are minus 2 power 31 to 2 power 31 minus 1 okay so these are the constant they have given now let us try to write the code okay so you just need to handle this case which is nothing but out of bound okay if it is going out upon we just need to return zero otherwise it's just a reversing normal thing okay so let us try to do that uh it is an integer we need to integrate it in integer right so what we are going to be doing just create a double okay we can call that as answer initially it can be zero then we can simply run a program or while loop which will do the reversing part for us okay we'll check for X not equals to 0 and then we are going to be doing two things first uh basically three things first we will be getting digit okay which is the last digit here okay we can easily get that by doing X modulus 10 okay X modulus 10 naught hundred okay then we we got the last digit now what we are going to be doing we are going to be adding that into answer so answer equals to okay and that is equals to answer into 10 okay that is okay let's put the brackets there then plus the digit which we have got and the last thing which we are going to be doing is dividing that X by 10 so that we can get the new number every time okay so suppose the value is one two three it's initially it is X is one two three we go we went into this we got the last digit as three in this case when we divide this one to three by ten we'll get the modulus we get three okay so 3 is in this so 3 starting it is 0 so it gets to add directly here then we are dividing that number by 10 so it becomes only 12 okay so now digit is having 3 in this now again when we run the loop we'll be getting 2 this time okay so 3 is already present in answer so it becomes 30 30 plus 2 gets added so it becomes 32. okay then again it gets and the X becomes one okay so for one also it happens like this and it's get reversed like this okay so I hope that was that part now we just need to return that which is will will do tap casting integer and will I get an answer from here okay so one condition we are going to be checking is here only that it goes out of one suppose the number is very close to this range okay to power 31 something okay so in that if we just multiplied that number by 10 okay so that this is the part where it can go out of bound correct so we need to handle this answer case okay so we just need to check that if answer is greater than equals to integer Dot Mini max value okay if it gets out of max value of integer or answer can go below so dot min so dot min underscore value underscore value which is new written which is new written 0 in this case okay 0 in this case okay so that is the part okay I think this so that is the part okay I think this will handle all the cases let us try to will handle all the cases let us try to run the code okay so it's working fine for this it's working fine yes okay so that's it it's working fine yes okay so that's it for this video I hope you got it it's a for this video I hope you got it it's a pretty simple question uh try to uh pretty simple question uh try to uh do it okay that's it for this video do it okay that's it for this video [Music] [Music] foreign | 2024-03-18 11:52:12 | 7 | Reverse Integer | LeetCode 7 | Top Array Interview Question | Geekster Java DSA | Amazon Google Meta |
|
B0wAyI5KaSA | What will this suggestion do or going to the question number of student wing Shiromani female question number of student wing Shiromani female homework on prime time student homework on prime time student now we started listening to Ek Cup Suji Hai because of this and end student is front time subscribe this recipe Do that Do that if we look at the second example, this one, if we look at the second example, this one, in this dream 181 means I am doing it, there were in this dream 181 means I am doing it, there were bigger festivals than this, bigger festivals than this, hello hello because Vansh how seventh class hello hello because Vansh how seventh class result 2017 fluid will do 0.5 inches from the seventh thrill, result 2017 fluid will do 0.5 inches from the seventh thrill, then we will take two then we will take two that I am dot science. that I am dot science. that I am dot science. our time fibroid thank you this is written in pune for every time e main wait of your call fragrancet kar denge india join kar denge song hai aur sanao kya kar rahe ho that we see actually started before or after And after that turn on the setting and let's coming right, then from here onwards it is a very simple question, the | 2024-03-21 02:43:00 | 1,450 | 1450. Number of Students Doing Homework at a Given Time |
|
eptC4nUL_2A | question, actually it is a very standard question, this type of question always comes in hip and it is a standard question, this is fine, find pairs with smallest sons is fine The most The most The most important thing is science, I told that if it is important thing is science, I told that if it is standard, then the standard solution which is absolutely hip, standard, then the standard solution which is absolutely hip, first we will create it, we will first we will create it, we will optimize it, it and where will it come from, as you will get it, and where will it come from, as you will get it, okay, What will happen to this, What will happen to this, What will happen to this, Brute understood, did it in one go, said Brute understood, did it in one go, said that you will pick one number from here, if that you will pick one number from here, if you pick one number from here, then it is ok, do the same you pick one number from here, then it is ok, do the same as mother takes, this is one, if as mother takes, this is one, if you pick from here, then 12 727476727476 Picked up all of them from one and picked up the top minimum one, out of which one, one, four, one, six is the minimum. Look in front of both, what is the sum of one, three, its time, five, its time, If you pick up one then brat If you pick up one then brat If you pick up one then brat force is very simple right key what will I do force is very simple right key what will I do two people have to run loop on two i = 0 two people have to run loop on two i = 0 i < mm m say the name of all one is the length ok i < mm m say the name of all one is the length ok i plus plus this is very simple i plus plus this is very simple The loop will run that Namaskar name for each eye is only taken out at 2:00. Okay, see how I will put it. I will put it in such a way that what was the even. Okay, so now they will be now they will be sorted in the ending order like this, the sorted in the ending order like this, the smallest band will be at the top. So when smallest band will be at the top. So when I will put it all in, then on priority I will I will put it all in, then on priority I will pick up the top elements, pick up the top elements, what will be the top elements, which will be my minimum what will be the top elements, which will be my minimum because I am putting it in mini hit, if because I am putting it in mini hit, if everyone is okay, then I will everyone is okay, then I will give the whole sequence, whatever sequence I am getting, I will get all the elements. give the whole sequence, whatever sequence I am getting, I will get all the elements. I have put all the possibilities in Preetiko, I have put all the possibilities in Preetiko, okay, so now this is a very dirty solution okay, so now this is a very dirty solution actually because I have actually because I have put all the possible legs in the minimum hip and put all the possible legs in the minimum hip and picked up the top minimum elements and returned them. picked up the top minimum elements and returned them. Okay, so the smallest one is that. Okay, so the smallest one is that. Okay, so the smallest one is that. out whatever I want, select the elements and put them in my result, six, so this is a very dirty solution, okay, we can butter it a little bit and the butter that I am going to do I also understand you I also understand you I also understand you and in this playlist of mine in Hip's and in this playlist of mine in Hip's playlist, I have playlist, I have asked some such questions in the beginning from which asked some such questions in the beginning from which he would have learned the method and now I am going to repeat the method from Revise he would have learned the method and now I am going to repeat the method from Revise RBI. Okay, so RBI. Okay, so let's take a small example. let's take a small example. Later we will come to this problem, what is the example of 321876? Okay, it has been said in the question that let's 321876? Okay, it has been said in the question that let's take mother. It has been said in the question that brother, take mother. It has been said in the question that brother, take out the top three smallest elements and take out the top three smallest elements and show us the top three smallest elements. So, there is a show us the top three smallest elements. So, there is a way that you can sort them and what are the ones way that you can sort them and what are the ones with simple toxins? with simple toxins? with simple toxins? minimum is required, okay, what did I do Now I am not telling you whether I have to Now I am not telling you whether I have to take only I or max only, take only I or max only, okay, probably you must have seen my okay, probably you must have seen my video which video which video which first of all I came three, I put three, okay here, after that came two, I put two, look at me, how many elements are needed, three elements are needed, not just three minutes, then the size of the hit is more than three, I won't give it, it's more than three, I won't give it, it's more than three, I won't give it, it's more than three, no, there is a forest here, I no, there is a forest here, I gave it to the forest, now which one is here, I do gave it to the forest, now which one is here, I do n't know yet, but when I came here, n't know yet, but when I came here, let's go, I gave it to the forest, but you can see let's go, I gave it to the forest, but you can see which one is there. which one is there. which one is there. size of the hit should not have been more than three, so now I just have to remove one element each, so you think for yourself, what I told you is that you want minimum elements, so which one would you like to remove, it is easy. Which one would you like to remove from you which is a big element i.e. will you remove the larger element? No, it is obvious that you No, it is obvious that you would like to remove only one larger element. Right, this would like to remove only one larger element. Right, this means that if you guys take only Max, then means that if you guys take only Max, then what will happen from Max Hip or in the top? what will happen from Max Hip or in the top? what will happen from Max Hip or in the top? element and you can remove it easily, okay, so what do we do again, let's run it, okay, first came three, then you, now sense, you are small, then you will come down, 3 will go up, then one is small, Will go to the bottom, then you, then three, Will go to the bottom, then you, then three, Will go to the bottom, then you, then three, after that comes 8, now as they come, science after that comes 8, now as they come, science comes, the biggest one, here comes the butt, look comes, the biggest one, here comes the butt, look how much the size of the hip has become, it has become that of a Greater Dane, how much the size of the hip has become, it has become that of a Greater Dane, so what will I do to everyone, I will pop the one who is on the top. so what will I do to everyone, I will pop the one who is on the top. So I popped this 8, So I popped this 8, okay till now it's okay till now it's clear, made it from then on, then seven came clear, made it from then on, then seven came here, okay, so what did I here, okay, so what did I do, give science grater to 7, size became three, so do, give science grater to 7, size became three, so popped the seven, then six popped the seven, then six is six, also top. is six, also top. is six, also top. biggest element is our maxi and science size, which is > K, so I popped it. Okay, now let's agree that I have one more element, So I would have So I would have So I would have come to zero and put zero, now this riff would have been come to zero and put zero, now this riff would have been successful, at the bottom, zero would have been A, successful, at the bottom, zero would have been A, then it was made, then you come, then three comes, this then it was made, then you come, then three comes, this race becomes successful, B itself is fine, then race becomes successful, B itself is fine, then I saw the truth of good hip> I saw the truth of good hip> I saw the truth of good hip> us top the one above, okay so look at the cake, now I have processed all the elements, now what do I have to do by blindfolding, I have to process all the elements in the hip, Will go to zero Will go to zero Will go to zero one, these are my top three minimum elements, one, these are my top three minimum elements, so notice me, maximum, how much was the size of your hip, if it was only K + 1, then only its size would be approx. If we talk about its size, then it will be closed Okay and Okay and Okay and think about its time complexity, I sense, what am I think about its time complexity, I sense, what am I doing, I am pushing some element, doing, I am pushing some element, how much is the hip operation, the logo is off, the how much is the hip operation, the logo is off, the of the logo is off, it will of the logo is off, it will seem okay in the operation, so this is a butter seem okay in the operation, so this is a butter approach. approach. approach. can apply the butt style now, I can apply the butt style now, I repeat once again with the current problem, so let's so let's solve the Se problem one day with these standard techniques, solve the Se problem one day with these standard techniques, okay and this is actually okay and this is actually okay and this is actually is the method because look at this, pay attention now, what will we do like mother take I, mine is here, yes, mine is here, okay, so what did I do, one comma tu, one comma tu, There will be There will be There will be 3, right, I have given it to 3, right, I have given it to you, see which will be the priority, you, see which will be the priority, what do you have to find in the question, minimum, what do you have to find in the question, minimum, whose minimum is even, then what will I take, I will take max hip, whose minimum is even, then what will I take, I will take max hip, okay, and as soon as the size of my hip okay, and as soon as the size of my hip becomes bigger than K, I will pop it. becomes bigger than K, I will pop it. becomes bigger than K, I will pop it. element with the largest one. Okay, so the one whose sum is the largest will be on the top, then I will delete it, easily, it is empty right now, so what did I do, the sum of both is three and by not doing one comma, Can I put the Can I put the Can I put the index? If I put the index then what will happen? index? If I put the index then what will happen? Index number zero is the index of one Index number zero is the index of one and index number is zero number. Okay, now you and index number is zero number. Okay, now you can also put the value, there is no problem, can also put the value, there is no problem, okay till here it is clear, remove the one after that. okay till here it is clear, remove the one after that. Given Given again where A went one comma four is right again where A went one comma four is right but if I index them further then the biggest one at the top will be even five, here A went index which is index I meaning zero and here index J One is ok, this is also added, One is ok, this is also added, One is ok, this is also added, after this it is bigger then after this it is bigger then ok next to which is bigger then what are the elements ok next to which is bigger then what are the elements 1 is 6 what is the sum of both 7 is science 1 is 6 what is the sum of both 7 is science this is an even bigger element so 7 here this is an even bigger element so 7 here is one is one is one index J, what is you, this is also added, after this, let's move ahead, we will will love others, okay, so will love others, okay, so I am trying all the trees, so I am trying all the trees, so from root four, this from root four, this from root four, this coma are you okay biggest time so he will be on the top biggest time so he will be on the top Look at the size of butt hip He is greater than that Look at the size of butt hip He is greater than that Date is 3 So I have to delete someone Date is 3 So I have to delete someone So So So which is the biggest element because it has been asked in the question that I have to remove the minimum sum, then I have to delete the biggest element, then I will easily pop the proper band, so I have It has popped, it will It has popped, it will It has popped, it will definitely not happen in the future, it is fine till now, it is definitely not happen in the future, it is fine till now, it is going well, now we going well, now we will move it forward again, J will go to will move it forward again, J will go to G, mine will go here, what is the sum of both, G, mine will go here, what is the sum of both, brother, first write down 7 and this is four brother, first write down 7 and this is four elements. elements. elements. added here. What is the i8 index? What is the index and what is the brother-in-law index? Science is 11. The biggest time is the obese, he will be on the top but give a greater butt size, if it is done then the This will This will This will happen on its own, this top only got popped, happen on its own, this top only got popped, I removed it, okay, now let's move ahead I removed it, okay, now let's move ahead whatever will be in this top because I am popping plus the maximum right here If the If the If the one is even, then it definitely does not have it and both of them are 13, so again here we have and both of them are 13, so again here we have 13 and what is the index, you are and its 13 and what is the index, you are and its index is zero. Okay, so index is zero. Okay, so 132 again give the greater and the size is done and 132 again give the greater and the size is done and popped it on top. popped it on top. popped it on top. big one is ok 114 so what has come brother you are here I will pop the top guy this is gone again now here comes here what is this big one 17 17 To process the player's way, you will have to put a loop on the two, which I showed you above. If I can get this one from the look on the two in all the legs, then it will be off M, cross M, then it will be okay, but now inside the loop on Har Par. What are you doing every time, here you are also doing push and pop, so what is the point of pushing? People, of the size of the hip, how much maximum will be given, okay, so now the question comes that friend, is this time Will it be accepted in the lead code Will it be accepted in the lead code Will it be accepted in the lead code or not? The answer is no but if you make a little slide improvement in it then it can be accepted. Look, now I will tell you how, then see if you make a little improvement and you will get the answer yourself. Look, pay attention to So you know, I will have to write So you know, I will have to write So you know, I will have to write because I have to process all the pairs. because I have to process all the pairs. Okay, so okay, I have applied two formulas Okay, so okay, I have applied two formulas here, I have removed everything, Namas plus one, sorry, till now it is clear, now look, only three things can happen, earlier brother. Why is it my priority, what is its size, it is of Lee Dene, if I am of Lee Dene, then it is an obvious thing, you do not have to put any meaning, PK dot top Which is the PK dot top Which is the first element of the element in it? first element of the element in it? first element of the element in it? if it's greater than my if it's greater than my current time, okay look, I'm repeating it again, there's a small one mixed at 1:00, so I have to put this one, so what will I do, what will I do first, I'll push the current one P what will I do first, I'll push the current one P K dot post which I have just got a small one, K dot post which I have just got a small one, okay, the look here, I go back to this example, look here, I go back to this example, okay, on 7th, the okay, on 7th, the band which is in the top of priority here, the new band which has come now is band which is in the top of priority here, the new band which has come now is even. even. even. okay and remember which index number was that index number, it was one, okay, now you think for yourself, when this 13 will come here, he will see that the guy at the top is Okay, Okay, Okay, I am small myself I am small myself so will I put it as obese so no I am obviously but am so will I put it as obese so no I am obviously but am I like which element was taken from the number one, I like which element was taken from the number one, 7 was taken okay and which 7 was taken okay and which element was taken from the name was six okay element was taken from the name was six okay now think for yourself, let's then then then as soon as I get a bigger sum, then I will as soon as I get a bigger sum, then I will increase I again, that is, I increase I again, that is, I can break the loop on the K one, how can I can break the loop on the K one, how can I break it? break it? break it? I saw that I was like my J was here and I was here then I came which element is the name of the name is 7 that is right plus j3 who is in the time of both 13 so 13 so Obviously brother is younger than the top element, so anyway he will come on top, then he will become the top later, okay, so I will not put this one, right, after this, when we move ahead, we will get a guy bigger than six, If you get only Banda, you will get If you get only Banda, you will get If you get only Banda, you will get eight or you will get none, then all of them will also be eight or you will get none, then all of them will also be big, when yours was big, then big, when yours was big, then after this, when it will be added to eight, then what will happen if you after this, when it will be added to eight, then what will happen if you get 15, this will be even bigger with you, get 15, this will be even bigger with you, so go ahead and know that J. so go ahead and know that J. so go ahead and know that J. right? Take K back here and make i bigger. Now explore i. Here you simply break it. Break it. Okay, after that it will start again from i0, otherwise it will move forward It will start from zero, It will start from zero, It will start from zero, that's what I wanted to say, that's what I wanted to say, do it small, otherwise your solution will be accepted, do it small, otherwise your solution will be accepted, now it is very important to know the root four solution also, explain it to you by stressing it well, okay and what I told you in priority, There will be sum There will be sum There will be sum and index i index, so it is an obvious and index i index, so it is an obvious thing, what will be put in the priority, okay now it is an obvious thing, earlier how we used to define normal priority, eat vector of and vector of eat is defined like this, This will be all This will be all This will be all on one, that is, look, I will define it, there will be a separate interior and I am late for both of these, you define it directly, without any other you define it directly, without any other compiler, that is only the max is compiler, that is only the max is distributed, so distributed, so this is actually my max hip this is actually my max hip and and and P vector of P which is then greater and P but science here we also want maxi so our definition will be exactly the same right and look you should understand why max hip It is ok so that as soon as my hip size becomes that of a Greater Dane, I will remove him, it is a big time and has a big value because I want smaller sons, so I would like him to be on the top or Dun and Max Dun and Max Dun and Max come to Kispay at the stop, Max stays in the hip, come to Kispay at the stop, Max stays in the hip, okay so let's code it quickly okay so let's code it quickly and yes, time conflict here, you must have and yes, time conflict here, you must have understood that it will be less than this, right, understood that it will be less than this, right, how is this my worst, isn't it, people are off. how is this my worst, isn't it, people are off. how is this my worst, isn't it, people are off. I am processing it completely but I am not processing it here, as I know that I will break it internally, I also told you the example here right, so let's And let's see if And let's see if And let's see if brute force is accepted or not then brute force is accepted or not then let's quickly solve our brute force. let's quickly solve our brute force. I always repeat I always repeat that never ignore brute force. that never ignore brute force. Brute forces Brute forces are very important especially for interviews. So just are very important especially for interviews. So just start. start. start. beginning that I write in the beginning that what is I on the off eat, time, then there will be a foot of income entry, then there will be index, okay, I have defined P and let me this. but it would be Forint J = size L, if you want to give it then anyway, you don't have to push it, right? We will push P K R, first what is the time and after that what is I, And if the sum is greater And if the sum is greater And if the sum is greater or equal to yours then I am going to check it and or equal to yours then I am going to check it and not pick top first i.e. the not pick top first i.e. the element which is on the top of the sum, if it is greater than my current element which is on the top of the sum, if it is greater than my current sum then now sum then now I can pop it. I can pop it. I can pop it. pop that PK road that brother, you are a big element, so pop it and push it, it is absolutely clear till this point, comma JCO is clear and if it is not so, then it means the If Smaller If Smaller If Smaller goes to America then break it, it is clear from INLD till now, okay so it is a very simple code, simply what we did is we processed all the pairs and added them. Now my simple vector will have only elements of If I am doing this, then If I am doing this, then If I am doing this, then I will put all those K elements in my result I will put all those K elements in my result until the priority key is empty, then until the priority key is empty, then I will remove it from it and I will remove it from it and you time = PK top, it is very simple result dot push underscoreback, I don't want to add index to If you have to enter the value, then I know If you have to enter the value, then I know If you have to enter the value, then I know that the first banda name was taken from one, so the that the first banda name was taken from one, so the name will be of one and the second name will be of one and the second banda name will be banda name will be ok, then after submitting, we will see that brother, No time No time No time compressed, pass all these test cases, compressed, pass all these test cases, which date is the case, indeed yes, they have solved this question, which date is the case, indeed yes, they have solved this question, using is going to come today in which I will also tell about its optical, which will be made of mini hips, sorry, it will be made from hip only, but Will take without Will take without Will take without processing h and every pairs okay to processing h and every pairs okay to come if there is any doubt comment area come if there is any doubt comment area video thank you | 2024-03-24 11:36:59 | 373 | Find K Pairs with Smallest Sums | BRUTE FORCE ACCEPTED | GOOGLE | Leetcode-373 | Live Code |
|
Na79lBT3wfI | Yes, hello, I am one of the developer children, Gary Ni. The problem to be solved today is number 347 kp quant elements. A pure number problem to be solved today is number 347 kp quant elements. A pure number array is given, and an integer k is given. Sort the elements that appear a lot, cut them as much array is given, and an integer k is given. Sort the elements that appear a lot, cut them as much as the top k pop k, and retan them. What is the as the top k pop k, and retan them. What is the order? order? order? appears 3 times, this appears 2 times, and 3 appears once. kkok It is 123 that heats the order of most encounters, etc. Among them, only this first element needs to be returned like this. Let's In order to store how many times a number appears, I In order to store how many times a number appears, I will declare an object called Pat and store the information here. if the corresponding item of Mr. is found, it will be added because it has appeared if the corresponding item of Mr. is found, it will be added because it has appeared once. once. once. out for the first time, so we set this to 1. Then, we store the number of times each number appears in the hash. And now we can create an answer array Well, I'll always use it. Well, I'll always use it. Well, I'll always use it. So, I'll save it as a series of the corresponding number of the answer series and how many times that number appears. The ceiling is completed. Next, I'll sort the answer bears using the sort function in the order of the most frequent occurrences. order of the most frequent occurrences. order of the most frequent occurrences. And since there And since there is no need to listen as under this kk, I will cut it by inserting kale using the splice method. is no need to listen as under this kk, I will cut it by inserting kale using the splice method. If rk join 5 and this encoder array is 3, only The The The array in the upper level is currently in an array of two, and what I want is the number that appears the most, so I use my palm number and return it like this. However, since this use my palm number and return it like this. However, since this has been used as a key up to this point, I put a string in it, has been used as a key up to this point, I put a string in it, so I wrap it in a number function. so I wrap it in a number function. 4 4 4 4 You can see that it has passed normally. This problem also has a 20-session tab, so it would be good to try solving it in a different way. That's Please click like and subscribe once. Please click like and subscribe once. Please click like and subscribe once. Thank you. | 2024-03-24 11:09:15 | 347 | [LeetCode] 347. Top K Frequent Elements |
|
gUc9qO94IlI | welcome back everyone to another video here in the uncle YouTube channel today here in the uncle YouTube channel today we're taking a look at problem 119 we're taking a look at problem 119 askal's Triangle 2. now this one is askal's Triangle 2. now this one is going to be very similar to the first going to be very similar to the first one except slightly different this time one except slightly different this time around we're going to be given some row around we're going to be given some row index and we want to go ahead and return index and we want to go ahead and return that actual row of the Pascal's triangle that actual row of the Pascal's triangle based on the Zero index so once again based on the Zero index so once again what the Pascal triangle looks like is what the Pascal triangle looks like is it's going to be the sum of the two it's going to be the sum of the two numbers directly above it like we see numbers directly above it like we see here so the first one is one we have one here so the first one is one we have one one and we have one plus one here is one and we have one plus one here is equal to two and one plus two plus two equal to two and one plus two plus two plus one is equal to three and three and plus one is equal to three and three and one plus three is equal to four three one plus three is equal to four three plus three is equal to six three plus plus three is equal to six three plus one is equal to four so on and so forth one is equal to four so on and so forth as we go down the array let's go ahead as we go down the array let's go ahead and take a look at the examples and and take a look at the examples and compute some things and then go ahead compute some things and then go ahead and go back and figure out how we can do and go back and figure out how we can do this so for example number one we're this so for example number one we're given the index equal to three so the given the index equal to three so the first index is going to be equal to just first index is going to be equal to just one the second index is going to be one the second index is going to be equal to one one the second index is equal to one one the second index is equal to one two one finally the third equal to one two one finally the third index is equal to one three three one index is equal to one three three one but now we'll go ahead and return one but now we'll go ahead and return one three three one that's how the first three three one that's how the first example breaks down let's take a look at example breaks down let's take a look at the second one for example two we're the second one for example two we're just given index equal to zero again just given index equal to zero again this one's obviously pretty easy this is this one's obviously pretty easy this is just going to return one that's a pretty just going to return one that's a pretty silly one let's take a look at the last silly one let's take a look at the last example in the last example of given example in the last example of given index equal to one still pretty trivial index equal to one still pretty trivial so index zero is equal to one and index so index zero is equal to one and index one is equal to one one we return one one is equal to one one we return one one just like that let's go ahead and one just like that let's go ahead and take a look at the constraints and try take a look at the constraints and try to figure out how we can solve this as to figure out how we can solve this as quickly as possible so on this one the quickly as possible so on this one the only constraint that they give us is only constraint that they give us is zero is less than equal to row index is zero is less than equal to row index is less than equal to 33. obviously this less than equal to 33. obviously this just means that the greatest number of just means that the greatest number of rows we're going to compute is 33 this rows we're going to compute is 33 this also means that once we get down to the also means that once we get down to the 33rd row these are going to be pretty 33rd row these are going to be pretty large numbers so we might run into some large numbers so we might run into some issues with sizes of integers things issues with sizes of integers things like that so what to worry about that it like that so what to worry about that it also means if we're trying to compute also means if we're trying to compute all of these at once or over and over all of these at once or over and over again it might be a little bit slow so again it might be a little bit slow so that means that there must be a faster that means that there must be a faster away which we'll talk about in a second away which we'll talk about in a second so once again the goal of this problem so once again the goal of this problem is to generate a given row of a Pascal's is to generate a given row of a Pascal's triangle at a given index and then triangle at a given index and then return that specific row that the return that specific row that the problem was looking for like I was problem was looking for like I was saying before there's two possible ways saying before there's two possible ways to solve this problem the first one to solve this problem the first one includes generating the entire Pascal's includes generating the entire Pascal's triangle all the way up to the row that triangle all the way up to the row that we're looking for we've already done we're looking for we've already done this and you can still do it relatively this and you can still do it relatively quick and beat a good portion of the quick and beat a good portion of the runtimes on the platform however there's runtimes on the platform however there's actually a mathematical equation that we actually a mathematical equation that we can use to calculate any row that we can use to calculate any row that we want to find we can use this equation to want to find we can use this equation to quickly calculate all the indexes of the quickly calculate all the indexes of the rows we're looking for in a single Loop rows we're looking for in a single Loop without having to store the entire without having to store the entire Pascal's triangle up to that point and Pascal's triangle up to that point and then return the specific index let's go then return the specific index let's go ahead and take a look at the pseudo code ahead and take a look at the pseudo code for this problem and the example for this problem and the example walkthrough for hopping over the lead walkthrough for hopping over the lead code so for the pseudo code we're going code so for the pseudo code we're going to start out by saying let result equal to start out by saying let result equal a new list this is we're going to store a new list this is we're going to store the actual row then we need to go ahead the actual row then we need to go ahead and add 1 to the index 0 of a result and add 1 to the index 0 of a result this is because this is obviously our this is because this is obviously our base case the top one is always going to base case the top one is always going to be equal to one then we want to go ahead be equal to one then we want to go ahead and loop from 1 to the row index plus and loop from 1 to the row index plus one so obviously here if it's only going one so obviously here if it's only going to be zero we're already at one we're to be zero we're already at one we're just going to go and return that list just going to go and return that list but if there's anything bigger than zero but if there's anything bigger than zero we'll start calculating but now we'll start calculating but now obviously we'll calculate the next index obviously we'll calculate the next index of row and then add that calculated of row and then add that calculated index to the row and once this Loop is index to the row and once this Loop is over we'll go ahead and return that over we'll go ahead and return that result list so this is a little bit result list so this is a little bit cryptic so let's go ahead and dive into cryptic so let's go ahead and dive into our example so we can figure out what our example so we can figure out what this mythical calculation is so our this mythical calculation is so our example again will once again be looking example again will once again be looking for index equal to three so like I said for index equal to three so like I said we'll go ahead and start out with a list we'll go ahead and start out with a list equal to an empty list the last for the equal to an empty list the last for the loop will be equal to index plus 1 which loop will be equal to index plus 1 which is equal to four obviously and the is equal to four obviously and the current value will be equal to one now current value will be equal to one now we want to set index 0 of the list to we want to set index 0 of the list to the current value which is equal to one the current value which is equal to one so now our list is equal to one our last so now our list is equal to one our last is still equal to four our value is is still equal to four our value is still equal to one obviously now we still equal to one obviously now we start our Loop for I equal one our list start our Loop for I equal one our list is equal to one our last is still equal is equal to one our last is still equal to four values always total equal to one to four values always total equal to one we want to recalculate our value so a we want to recalculate our value so a value will be equal to Value times last value will be equal to Value times last minus I but this is going to be equal to minus I but this is going to be equal to one times four minus 1 which is equal to one times four minus 1 which is equal to three and if you go back and look the three and if you go back and look the second index or I guess the first index second index or I guess the first index of the third row is definitely equal to of the third row is definitely equal to three so now we still need a little bit three so now we still need a little bit of calculation so now we're going to say of calculation so now we're going to say about equal to Val divided by I which is about equal to Val divided by I which is going to be equal to 3 divided by one so going to be equal to 3 divided by one so now we have our vowel so we're going to now we have our vowel so we're going to go and add value to list but now I equal go and add value to list but now I equal to 2 our list is now equal to one three to 2 our list is now equal to one three our last is total of four obviously and our last is total of four obviously and our vowel is equal to three once again our vowel is equal to three once again we go ahead and calculate Val so Val is we go ahead and calculate Val so Val is equal to valid times last minus I this equal to valid times last minus I this is going to be equal to 3 times 4 minus is going to be equal to 3 times 4 minus two which is either three times two but two which is either three times two but we also need to say Val is equal to Val we also need to say Val is equal to Val divided by I this is going to be six divided by I this is going to be six divided by 2 which is equal to three now divided by 2 which is equal to three now go ahead and add value to list again for go ahead and add value to list again for I equal to three our list equal to one I equal to three our list equal to one three three our last is equal to four three three our last is equal to four and our Val is equal to three once again and our Val is equal to three once again Val is equal to valid times last minus I Val is equal to valid times last minus I so this is equal to three times four so this is equal to three times four minus three which is equal to 3 times 1 minus three which is equal to 3 times 1 which is all obviously three no need which is all obviously three no need about equal to Val divided by I which is about equal to Val divided by I which is equal to three divided by three is equal equal to three divided by three is equal to one we add the value to list now I to one we add the value to list now I equal to four our list is equal to one equal to four our list is equal to one three three one our last is equal to three three one our last is equal to four our Val is equal to one now I is four our Val is equal to one now I is not smaller than last this means that not smaller than last this means that the loop ends let me go ahead and return the loop ends let me go ahead and return that list we created nope it's as simple that list we created nope it's as simple as that that one single calculation can as that that one single calculation can literally determine any single row that literally determine any single row that we want let's go ahead and hop overly we want let's go ahead and hop overly code and take a look at how we code this code and take a look at how we code this here in leak code we're going to go here in leak code we're going to go ahead and start out with our new result ahead and start out with our new result arraylist so list integer result is arraylist so list integer result is equal to a new arraylist obviously we equal to a new arraylist obviously we need this so we can actually go ahead need this so we can actually go ahead and store the entire row and we need a and store the entire row and we need a long previous equal to one like I was long previous equal to one like I was saying earlier this could be a pretty saying earlier this could be a pretty large number so we want to make sure we large number so we want to make sure we have enough space to actually store this have enough space to actually store this we're going to go ahead and set results we're going to go ahead and set results dot add previous as an integer again dot add previous as an integer again this is our basically our base case so this is our basically our base case so no matter what the first index or zeroth no matter what the first index or zeroth index is always going to be equal to one index is always going to be equal to one then we're going to Charter for Loop 4 then we're going to Charter for Loop 4 and I equal to 1 I is less than or equal and I equal to 1 I is less than or equal to row index and I plus plus I'm going to row index and I plus plus I'm going to say long current is equal to previous to say long current is equal to previous times row index minus I plus 1 divided times row index minus I plus 1 divided by I this is basically those two steps by I this is basically those two steps that we did previously merged into one that we did previously merged into one then we're gonna go ahead and set a then we're gonna go ahead and set a result.add that current as an INT then result.add that current as an INT then we need to go ahead and set our previous we need to go ahead and set our previous value equal to the current value so we value equal to the current value so we can go ahead and calculate the next can go ahead and calculate the next value and we'll Loop through until we've value and we'll Loop through until we've gone all the indexes in that row then we gone all the indexes in that row then we want to go ahead and return result so want to go ahead and return result so this one I feel like I probably typo this one I feel like I probably typo this equation somehow so let's go ahead this equation somehow so let's go ahead and give it a spin and see if I talk and give it a spin and see if I talk about anything about anything would you look at that actually got it would you look at that actually got it right in the first try that's pretty right in the first try that's pretty lucky but this is a zero millisecond lucky but this is a zero millisecond runtime which would be to 100 the other runtime which would be to 100 the other option if you do go ahead and create the option if you do go ahead and create the entire Pascal's triangle it's like one entire Pascal's triangle it's like one millisecond it beats like 50 or 60 or millisecond it beats like 50 or 60 or something like that so this one is something like that so this one is really faster but anyway as always if really faster but anyway as always if you guys did find some value on this or you guys did find some value on this or you just enjoyed please leave a like you just enjoyed please leave a like comment subscribe everything helps out comment subscribe everything helps out here in the YouTube journey and as here in the YouTube journey and as always this has been Ethan encoder hope always this has been Ethan encoder hope you all have a great day and I'll see you all have a great day and I'll see you in the next video | 2024-03-21 11:02:10 | 119 | LeetCode 119. Pascals Triangle II || Java Solution Walkthrough |
|
GBbYnqiXbOc | Hello Hi Guys Welcome to Kodiasar Today's question is insert into binary search tree in this question also Aryan root node of binary search tree and value to be interested in the trees were buried under root mode of the best ifton shown it is a Value did not exist in the Value did not exist in the Value did not exist in the original BSP BSP noticed that when original BSP BSP noticed that when combined multiple well as well as for the combined multiple well as well as for the information available on the subject each of the information you can information available on the subject each of the information you can write any form for example write any form for example disposition tree this for 21 30 to disposition tree this for 21 30 to insert values in node this is insert values in node this is insert values in node this is minutes nod ki vinod we can notice reduce the tree after getting this all handed over sp leaders not violet the principles of mystery birthday for multiple ways of interesting history for example so insult phase not be left elements of the the the multiple values of uncertainty note subah can write any one way or in nine reliable questions knowledge took it upon this question can not be given up B.Ed person in this post I will not know weather divine divine divine Divya Divya Incident And 3000 233 Of The Best Known For Win32 Nobody Will Go To Website The Right Side Not Being Undertaken And Person Responsible From State Bank Account Incident Route Noida And Greater Than There Route Not Any Way Consider This Lesson 7 Days In The The left side of the world we move The left side of the world we move The left side of the world we move from moving from 7th form of from moving from 7th form of value value that now Louis Vuitton method of inserting value that now Louis Vuitton method of inserting value and will and will an English joint with flute counter with the an English joint with flute counter with the left address office 7 suggestions will approach left address office 7 suggestions will approach question no let's get another example question no let's get another example a thousand bastes pipe a thousand bastes pipe a thousand bastes pipe 39 Is To Deposit Will Be E Will Be Equating Four Values In Route Notes Element Input Balance Input Value 90 Countries End Druts And Vinod Import Adhikari Route Not Immediately Informed That You Will Be E Will Be Inserted In Difficulty Value This Root Not Nor Will Move To Left Root Not Nor Will Move To Left Root Not Nor Will Move To Left Direction Listen And Roots Vikrampur Not Direction Listen And Roots Vikrampur Not Give Check The Weather In Food Value Is Loot Give Check The Weather In Food Value Is Loot Notes Value And Read And Not Believe In This Notes Value And Read And Not Believe In This Case Which Can See Hidden Truth Not Valid Case Which Can See Hidden Truth Not Valid Notes Will Have The Year Printed On Note Value Hai Begum Ban Note Value Hai Begum Ban Note Value Hai Begum Ban Norms Unchanged At Unkindness Value In Norms Unchanged At Unkindness Value In Food Value Is Dresses Note Value And Less Food Value Is Dresses Note Value And Less Drut Note Value Hidden Truth Not Value Drut Note Value Hidden Truth Not Value Develop And Attain Liberation Otherwise Develop And Attain Liberation Otherwise Development In Right Direction Vacancy Date Development In Right Direction Vacancy Date Meaningless Meaningless Meaning Is Coalition Soe Develop And Only Right Meaning Is Coalition Soe Develop And Only Right Side Only Right Side Only Right Side Only Right vacancy dot right side one not a good citizen al morning to will form root mode of value three length belt joint increase ride point and off the front reduce one note suggestion will do 123 right 123 right 123 right notes and will return this and Vitamin C Root of the Tarzan The Swadeshi thought will solve question no Let's look at record of this question Sunao Vinod Left for insulting value investing Divyavani Tasty ways to traverse through the best EE Review of Prabuddha Elements of Tasty Suno Let's Do You Travel and Travels Give the Respective Were Traveling in a Tree and Deaths Were to Difficult A Function to That Developed Function Name the Help of the Jai Hind Fauj Entry Date Par Date to Return Jai Hind Fauj Entry Date Par Date to Return Also root of entry sudhir typist free Also root of entry sudhir typist free notes of will it be the case notes of will it be the case that is root double do internal soft but will happen i will have what will happen rabbit letter shifted to find rabbit letter shifted to find a correct position for certificate a correct position for certificate position of the new value 233 snow and currently position of the new value 233 snow and currently They Are The Truth Not Support Se They Are The Truth Not Support Se Example This And Contributes For Example This And Contributes For Insulting Hindu Is 500ml Set First Shift Insulting Hindu Is 500ml Set First Shift Value Been Selected Value In Hindi Value Been Selected Value In Hindi Roots Value Roots Value A Little Jaati Roots Value Than What Will A Little Jaati Roots Value Than What Will Not Be In Contact With Mills And Not Be In Contact With Mills And Insulting Value Will Be A Company Will Insulting Value Will Be A Company Will Insulting Value Will Be A Company Will Incident Draw root left and wins it and party root left and wins it and party value2 value2 that boat will look 319 pallu is not less than the roots value that boat will look 319 pallu is not less than the roots value david value in that case what do we david value in that case what do we call the half divine acid of the call the half divine acid of the best all the best all the right side to the Value And Now When We Met Value And Now When We Met Value And Now When We Met Modi Calls Dirty Politics Loopholes And The Also But Modi Calls Dirty Politics Loopholes And The Also But Will Do Vitamin C Root Of The Will Do Vitamin C Root Of The Final Tree Nor Will It Be Know What Will Happen On To Initially I Worked For This Root Not Initially I Worked For This Root Not Inserting Value Is Pipe First Will Come Inserting Value Is Pipe First Will Come In This In This In This This Visible And Not Being Under Root Value Inserting Value Is Not Present Value Swift We Go To Right Side No This End Children Children And New Root End Children Victims 799th Urs Again Will See Is Is Is This Roots Elegant 798 Check Divinely Live This Roots Elegant 798 Check Divinely Live In Discussing A Its Correct Know What Will U Will Make A In Discussing A Its Correct Know What Will U Will Make A Call On This Website Call On This Website And Widening Vacancy Date Of Birth Left And Widening Vacancy Date Of Birth Left Side Has Left Side Is Side Has Left Side Is This Left Side Basnal Morning Encounter Null This Left Side Basnal Morning Encounter Null Butt Butt Butt first form of new note that bill not pass time that film its time and so its value get also slice 250 to insert new job note value that atal turn on this time a pointer see turn But have done this entry was only till there But have done this entry was only till there But have done this entry was only till there is digital seven next9news for the new is digital seven next9news for the new node 510 returns and vitamin this node 510 returns and vitamin this address and decided to 5-wicket win in the address and decided to 5-wicket win in the times when the president will dare devil times when the president will dare devil torch light bill gates or roots left Was Called From Was Called From Was Called From Hair Helper Happiness Times Valuable Hair Helper Happiness Times Valuable Gifts To Roots Left End Vitamin C Gifts To Roots Left End Vitamin C Root Of The Root Of The A Pre So Dishaon Bhi Has Incentive Aluminum A Pre So Dishaon Bhi Has Incentive Aluminum Industry Animal Function What Do You Industry Animal Function What Do You Simply Write This Address At The Red wap.com The Simply Write This Address At The Red wap.com The Function Root Value Of This and Answers and Answers Jai Hind Main Jai Hind Main India Ki Suraj Which D Code Is Running And I Ki Suraj Which D Code Is Running And I Got The Video Thank You To | 2024-03-21 10:10:13 | 701 | Insert into a Binary Search Tree Leetcode | Leetcode 701 | Leetcode october challenge |
|
gPtkIxy9bUo | hello everyone welcome to date 30th of april challenge today is the last day of the month and after solving today's question all of us will get the april batch this will be the 12th batch over the last one year and yes we have solved each and every question from past 365 days without fail my name is sanchez to introduce myself i am working a software developer for at adobe and here i present day 671 of daily lead good problem the question that we have in today's evaluate division so here they have provided us with few equations their values and followed by queries what do we need to do we need to evaluate these queries using the values that are present as part of equation and the values array that we have so i'll be walking you through this example as well as the algorithm to go about it by the presentation so let's quickly hop on to it lead code 399 evaluate division it's a medium level question on lead good and i also feel the same also in case if you have any doubt understanding this question or if you want to ask anything from me in general please feel free to ping on the telegram group or the discord server of coding decoded both the links are mentioned in the description so do check them out so let's take the same example that are specified in the question and also remember by analyzing these equations and values together consider them as a single unit what does this mean let me just walk you through that so here it the first entry in the equation represents a comma by b that simply means a by b evaluates to 2 and the second entry is b comma c so that means b b by c evaluates to 3. so consider these equations and values as an atomic entity do not consider them as separate values separate data what we need to identify we need to identify the value of a comma c that simply means a a by c the next one is b by a followed by a by e followed by a by a followed by x by x so this is a wonderful example because it covers all the possibility of test cases that we can have and let's talk about the algorithm how are we going to arrive at these values using the data that we have in the question now let's try and understand the queries part so if you carefully look at the first query what do we need to evaluate we need to evaluate what is the value of a by c and how that can be done so let's walk through the equations and the values that we just analyzed uh we have a by b as 2 b by c r 3 so what we can do we can simply multiply these two values up and what do we get we get a by b into b by c so b and b in denominator gets concerned with b in numerator and the value left is a by c so what that value would be it would be equal to 2 into 3 so you can figure out that using multiplication across these values something can be and that this equates to 6. now comes and that this equates to 6. now comes the question how can we actually process the question how can we actually process this information so that we reach the this information so that we reach the required queries that can be done using required queries that can be done using graph how let's walk through the same graph how let's walk through the same example example so what we are going to do we are going so what we are going to do we are going to build a graph how are we going to to build a graph how are we going to build this graph let's go step by step build this graph let's go step by step the first entry that we see is a comma b the first entry that we see is a comma b and the value happens to be two so we'll and the value happens to be two so we'll build a graph starting from a and it build a graph starting from a and it goes up till goes up till b with the value of two so let's write b with the value of two so let's write two here so consider this as an entity two here so consider this as an entity where that signifies that where that signifies that a by b happens to be value 2 a by b happens to be value 2 pretty straight forward along with this pretty straight forward along with this we'll also store another value in our we'll also store another value in our graph that would be b by happens to be 1 graph that would be b by happens to be 1 by 2. so using this information you can by 2. so using this information you can reverse the denominator with numerator reverse the denominator with numerator and the value that we get will get and the value that we get will get updated to 1 by 2 instead of 2 updated to 1 by 2 instead of 2 so these two equations are exactly the so these two equations are exactly the same so we are also going to store this same so we are also going to store this information in our graph so b information in our graph so b by by a represents 1 by 2 a represents 1 by 2 so this information you're also going to so this information you're also going to store in the graph store in the graph pretty straightforward so at each entry pretty straightforward so at each entry there are two values stored there are two values stored the first one is the character or string the first one is the character or string and the second one happens to be the and the second one happens to be the value so again it would be of type value so again it would be of type string comma double string comma double so let's represent it over like this so so let's represent it over like this so each entry each connection or each edge each entry each connection or each edge is represented by the starting node is represented by the starting node which would be again of type string and which would be again of type string and uh the value would be a map of string uh the value would be a map of string comma double because string will comma double because string will represent the node up till which the represent the node up till which the connection goes and the double value connection goes and the double value represents the value part that we represents the value part that we derived from the values r a derived from the values r a let's proceed ahead let's proceed ahead next we see is b comma c so let's do the next we see is b comma c so let's do the same thing again so b by c happens to be same thing again so b by c happens to be three so again a new connection will be three so again a new connection will be established and here it would be equal established and here it would be equal to to b by c happens to be three so we'll b by c happens to be three so we'll store this information again in the store this information again in the graph so right now we have three nodes a graph so right now we have three nodes a by b is 2 a b by a happens to be 1 by 2 by b is 2 a b by a happens to be 1 by 2 and b by c happens to be 3 along with and b by c happens to be 3 along with this we'll also store an information this we'll also store an information that c by b happens to be 1 by 3 that c by b happens to be 1 by 3 so this also makes sense to us so this also makes sense to us now comes the question now comes the question how are we gonna find out the queries how are we gonna find out the queries part so let's get started let me just part so let's get started let me just highlight all the highlight all the uh nodes that we have built in the graph so these are the four nodes and let's get started with solving the queries let me just change the color of pen the first equation that we see is a by c so what we can do we can start the dfs traversal or the vfs traverses anything of your choice what is the starting node the starting node happens to be a that means uh we will look out for a node in our adjacency matrix or the graph so the first can and we can go on by traversing in this graph via dfs reversal or the bfs reversal so the first node that we see is b so uh the value here is two so let's store this value too and for let's proceed ahead now from b there are two options the first part is from b to a since a is already visited we will not go on to that path again the other path that we have is from b to c and the value here is three so let's proceed towards that path and what we are going to do we will multiply this value from the previous value that we have traversed so far the previous value that we traverse this 2 so 2 into 3 gives us 6 and what do you see here you see that this happens to be our terminal node for the query a comma c therefore we will avoid the process and return whatever product we have identified so far while traversing starting from the a node up till the c node and the value becomes c the final as 6 is the answer that we found we will as 6 is the answer that we found we will simply return the value for a comma c as simply return the value for a comma c as six so this we are done with this six so this we are done with this equation the rest of the equations are equation the rest of the equations are really simple here it's b comma a b really simple here it's b comma a b comma the direct connection over here comma the direct connection over here you will simply return one by two then you will simply return one by two then you will go for a comma e you can see you will go for a comma e you can see that by when you traverse in the dfs that by when you traverse in the dfs fashion starting from a node and you fashion starting from a node and you keep on searching in this graph you will keep on searching in this graph you will never witness e node therefore what you never witness e node therefore what you should do you should break the should do you should break the dfs once the traversal is done all the dfs once the traversal is done all the traversals are done and you'll simply traversals are done and you'll simply return -1 in those cases so answer here return -1 in those cases so answer here becomes -1 next in an interesting case becomes -1 next in an interesting case and that says a comma a when you and that says a comma a when you whenever you see that the target value whenever you see that the target value happens to be equal to your source value happens to be equal to your source value you should check whether this source you should check whether this source value is present in your graph or not if value is present in your graph or not if it is present then you simply return 1 it is present then you simply return 1 in those cases in those cases this case is an exclusive case that we this case is an exclusive case that we have to handle have to handle out of the regular dfs operation now let out of the regular dfs operation now let us look for the last case where we have us look for the last case where we have x comma x again the values happens to be x comma x again the values happens to be same for the source and the target same for the source and the target however x is not part of our graph as a however x is not part of our graph as a result of which we'll simply say minus 1 result of which we'll simply say minus 1 for this particular query so these are for this particular query so these are the four cases that we discussed and the four cases that we discussed and let's quickly walk through the coding let's quickly walk through the coding section and i'll exactly follow the same section and i'll exactly follow the same steps as i have just talked here so the first thing that i have done here is to build the graph using the equations and the values array that i have so let's walk through the build graph helper method and then we will look out for the rest of the algo so build graph is really simple you create a graph of type uh the key happens to be string as i talked in the presentation the value happens to be again a map of type string comma double where this signifies the target uh this signifies the value that we extract from the values array so let's write it in a better form this is my source or start comma map will have end comma value now let's start the iteration so you reverse over the equations that we have you extract the starting element you extract the ending element you extract the value element you add it into the graph one connection would be starting from start up till end and the value would be val that the connection would be from end up till start and the value here would be one by val rather than the val because you have reversed or swapped end with start once you are done with this you simply return this graph back to the caller method and let's go back to the caller method now what i have done here i have created the answer array that is a return type double because the question itself tells us to do then we go ahead and start reversing over the queries that we have and also i have created a visited set for the dfs reversal which will be needed so what do i do i check whether my source which is query dot get r0 is index happens to be equal to my target value if that is the case then i go ahead and check whether my graph contains the source or not if it does constrain contain then i can simply say that the answer for this part would be 1 and i increment the value of i so consider this as i plus plus and in case my graph doesn't contain the source that simply means you you cannot find that value in your graph you simply done minus 1 in those cases and this is it i have incremented the value of i so this is an important corner case which people often tend to miss out and once i'm done with this what do i do i invoke the dfs method for the cases where my source is not equal to my target i invoke the dfs method and whatever value is returned from the dfs helper method i simply set it to my answer and i proceed ahead with the next reversal in the end i simply return the answer now the problem reduces to writing this dfs method appropriately so the first parameter signifies the source the second parameter signifies the terminal terminal node followed by graph and the visited array that we have created or set that we have created so in case my graph doesn't contain my start what do i do i simply return minus 1 in those cases in case my graph contains start and uh this that at that particular node i can see that there is an edge up till the end so what do i do i simply return the corresponding value there moving ahead i simply update my start node to visited set and then uh what what have i done i have iterated over all the entries of or all the connections that i have starting from the start node and i check whether the uh key the terminal node was visit was part of the visited set of or not if it is not part of the visited set then i invoke the dfs reversal on that and in case the value returned from that dfs traversal happens to be not equal to minus 1 that means the path does exist so i multiply my current value with entry dot get value and return it to the caller method if this condition is never met that means by the dfs reversal the value returned was minus 1 and in those cases the path doesn't exist either as a result of which we have simply returned minus 1 in those cases signifying the dfs was not met accept it with this we have successfully accept it with this we have successfully completed all the questions of the completed all the questions of the monthly challenge april 2022 and this is monthly challenge april 2022 and this is our 12th batch without fail we started our 12th batch without fail we started our journey from may uh 2021 and today our journey from may uh 2021 and today at 30th april we have solved all the at 30th april we have solved all the questions over the entire year starting questions over the entire year starting from may from may uh till today and we have in total got uh till today and we have in total got 12 badges so if you remember this video 12 badges so if you remember this video i'll be glad and there's another i'll be glad and there's another announcement that i would like to make announcement that i would like to make that is i'm going live today and the that is i'm going live today and the agenda for this live session would be agenda for this live session would be let's celebrate the achievement uh this let's celebrate the achievement uh this is our 12th batch 365 days without fail is our 12th batch 365 days without fail it's a big achievement in itself it's a big achievement in itself apart from this i'll be giving away a apart from this i'll be giving away a surprise amazon gift card to one of the surprise amazon gift card to one of the daily contributors of coding decoded daily contributors of coding decoded github repo who have solved along with github repo who have solved along with me all the questions and submitted me all the questions and submitted solutions over there for the month of solutions over there for the month of march 2022 march 2022 last but not the least i'll be going last but not the least i'll be going over your doubts in a lie in this live over your doubts in a lie in this live session so i'm pretty excited about it session so i'm pretty excited about it and i hope you guys will be able to find and i hope you guys will be able to find time to join in and i'm looking forward time to join in and i'm looking forward to seeing all of you there | 2024-03-24 12:18:38 | 399 | Evaluate Division | Leetcode 399 | Simple Graph traversal | Live coding session |
|
A0g-aitC6k4 | hey everybody this is Larry I'm doing this problem as part of a contest so this problem as part of a contest so you're gonna watch me live as I go you're gonna watch me live as I go through my daughter's I'm coding they've through my daughter's I'm coding they've been explanation near the end and for been explanation near the end and for more context they'll be a link below on more context they'll be a link below on this actual screen cats of the contest this actual screen cats of the contest how did you do let me know you do hit how did you do let me know you do hit the like button either subscribe button the like button either subscribe button and here we go yeah cue to count and here we go yeah cue to count triplets that can form to a way that you triplets that can form to a way that you go XO given an array of integers oh okay go XO given an array of integers oh okay oh yeah so this one well I feel a little oh yeah so this one well I feel a little off maybe all the sniffles in the off maybe all the sniffles in the beginning as well but this one I was I beginning as well but this one I was I think I spent some time trying to figure think I spent some time trying to figure out whether I can do better than n cube out whether I can do better than n cube so n is 300 right which and cube is 27 so n is 300 right which and cube is 27 million which is really cutting it close million which is really cutting it close but then it it took and I was thinking but then it it took and I was thinking about how to do it and I end up doing about how to do it and I end up doing with C++ because I thought that n cube with C++ because I thought that n cube at the time I don't n cube would be 27 at the time I don't n cube would be 27 million which which is cutting it close million which which is cutting it close I think for the lead code for enqueue I think for the lead code for enqueue maybe you could get away with it but it maybe you could get away with it but it depends on how strict or not strict depends on how strict or not strict maybe two test cases will be and I just maybe two test cases will be and I just wasn't confident about that particular wasn't confident about that particular piece and now I'm in this moment I'm piece and now I'm in this moment I'm thinking about well can I do better than thinking about well can I do better than n cube you know and I was like yeah n cube you know and I was like yeah maybe not let's do C++ so that I know if maybe not let's do C++ so that I know if there's ever a one time thing that I there's ever a one time thing that I could you know then I could just it could you know then I could just it wouldn't be like it wouldn't factor in wouldn't be like it wouldn't factor in as much if that's an intended solution as much if that's an intended solution so so yeah I would say so the reason why I took 10 I would say so the reason why I took 10 minutes on this problem I think is minutes on this problem I think is actually because I did it with prefixed actually because I did it with prefixed um I so you definitely can't do a prefix um I so you definitely can't do a prefix um and in the explanations later you I um and in the explanations later you I explained why he fixed some works but explained why he fixed some works but looking back right now looking at my and looking back right now looking at my and I you kind of see me hinting at trying I you kind of see me hinting at trying to do this but I was just really worried to do this but I was just really worried about off by once that I didn't really about off by once that I didn't really think it through in retrospect I should think it through in retrospect I should have did what I am doing here where I have did what I am doing here where I didn't really need the prefixed time I didn't really need the prefixed time I could just calculate on the fly but I could just calculate on the fly but I just wasn't doing it quite right so now you see me doing perfect some looking back I probably spent five minutes about this because I was doing it with perfect sum which is correct but I was not necessary what I would did before with her into a like like calculating just honest dreaming basis it's not as you don't put in an additional full loop you're probably okay and that's why I was a cute too and I made it more difficult than it needed to be because I think actually I think I just to be honest I think I've washed it a little bit as well man totally given if it doesn't seem like it because that led to me just I don't know like I feel and I here and now just I want to double and I here and now just I want to double check that I J and K oh yeah and I spent a silly amount time on well this one it's okay I think I was just thinking about what I won which you know I at this point I spent way too much time on this but but I Shep don't I the other thing is that I should have known better here is that so actually I think I mostly got to yeah mostly got to index while but like I knew what to look for but the promise that if you're really good at bitwise operations then you notice what I'm doing wrong and usually I'm better about this but again today maybe it's just one of those days where a little bit silly so I went and I was like okay that's way that right so let's put this out but the short answer is well okay see if you could spot the bug immediately let's say there's no off by once so see if you can spot the bug leave a comment below if you spot the bug before I actually do it before I actually fix it right up but yeah I was like okay maybe there's enough fine one which that one actually actually I was like okay it's still not right and now it is about 10 minutes and I end up spending at least three more minutes on this silliness but I think if I just not did prefix um just would be much faster here I printed I was like wow this is a here I printed I was like wow this is a lot of stuff and I had to mentally just lot of stuff and I had to mentally just figure out where the indices I spent it figure out where the indices I spent it there's a lot of time wasted on this one there's a lot of time wasted on this one I think if I had been able to submit as I think if I had been able to submit as that when I did then this would have that when I did then this would have been an okay problem for me I mean like been an okay problem for me I mean like the prom it's okay it's just I would the prom it's okay it's just I would have considered it that I did okay but have considered it that I did okay but this debugging was painful and yeah see this debugging was painful and yeah see if you can spot the bunt because I took if you can spot the bunt because I took me a while so maybe that's like a fun me a while so maybe that's like a fun challenge at home and in a fun way challenge at home and in a fun way this debug statement actually does not this debug statement actually does not help I know like that doesn't make sense well well it does by omission maybe so if you're if you caught it before I fixed it mad props to you because I really took a while what the answer is that the D cooperation has higher precedence than the bitwise operations so so yeah and now I'm able to be like okay at least it is more correct I might have enough fire one pair this is more and now I'm able to use my debug code to and now I'm able to use my debug code to be like okay where am i off zero to one be like okay where am i off zero to one that should at least be a two so I've that should at least be a two so I've have enough by one there have enough by one there I also recommend in general just I also recommend in general just printing our stuff because yeah you have printing our stuff because yeah you have to learn how debug not every contest not to learn how debug not every contest not every interview is going to go 100% and every interview is going to go 100% and you want to prepare you in those cases you want to prepare you in those cases that you know if you do well we know if that you know if you do well we know if I want to Stephanie a place where well I want to Stephanie a place where well things happen and I hear I'm looking the things happen and I hear I'm looking the constraint again because I'm like just constraint again because I'm like just making sure that I didn't miss read it making sure that I didn't miss read it but I think I don't know I wasn't but I think I don't know I wasn't focusing on my energy because because focusing on my energy because because that doesn't make sense of the output yeah looking and then the antis looks good so I submit and that was a hard problem for me you to count trips that can triplets that can form two arrays of ecoegg so yeah so this is prefix sums I yeah I I thought that and cube it's a yeah I I thought that and cube it's a little bit too slow maybe but but it's little bit too slow maybe but but it's actually not n cube strictly it's n actually not n cube strictly it's n choose 3 which cuts down it's about like choose 3 which cuts down it's about like six times faster or something like that six times faster or something like that wealthy so that's why I initially turned wealthy so that's why I initially turned into C++ I was like oh maybe I needed to into C++ I was like oh maybe I needed to be the fast loops but it turned out not be the fast loops but it turned out not to be necessary and I think after that to be necessary and I think after that though even when I was convinced I was though even when I was convinced I was just a little bit off by one in certain just a little bit off by one in certain places in Alvin I think to think that I places in Alvin I think to think that I had a little needed murder fine was that had a little needed murder fine was that that this would work properly because I that this would work properly because I worried that I would XO a number with worried that I would XO a number with itself and obviously you can't or you itself and obviously you can't or you can do it but when you do it you get can do it but when you do it you get zero instead of that's what I was scared zero instead of that's what I was scared of but actually end up being pretty of but actually end up being pretty straightforward and end up taking ten straightforward and end up taking ten minutes on this problem but it was sharp minutes on this problem but it was sharp and faster but the idea is that it took and faster but the idea is that it took actually explained it all I mean stuff actually explained it all I mean stuff just what I did just what I did so the in this one you can note that the so the in this one you can note that the big key to no solving this form is big key to no solving this form is noticing that well let's say you have noticing that well let's say you have some except I X or X a PI sub I plus 1 X some except I X or X a PI sub I plus 1 X or I sub I plus 2 dot dot a sub X or a or I sub I plus 2 dot dot a sub X or a sub J so that's equal to a sub 0 X or a sub J so that's equal to a sub 0 X or a and you know maybe we could space it out and you know maybe we could space it out a little bit just so that the a little bit just so that the visualization is easier a and then Todd visualization is easier a and then Todd a sub I so that that a subject right something like that but it is this whole thing X owing there are prefix just prefix that's before the I minus 1 right okay so this is someone like that and want you to notice that then well it's prefix sums and I maybe you don't even need to be honest because that maybe we could do some smart things into loops but the prefix some it became easier to just focus on the my off by once because I knew I would have potentially issues with one five one because of why said about the J and K and the other thing that was a little bit maybe odd but maybe not is that even though I has to be strictly less than J J has to be less than or equal to K and I think I didn't have an off by one which as soon as I fixed it was able to submit Bao still not confident after that I was just yeah but yeah cool so that and after that you could just try all possibilities of ijk that's just given and then it's a little tricky to get off by once right but that's pretty much it no yeah so it's been a while since I did one of these cold reviews so let's actually do a couple of code reviews and see where I can learn cuz I definitely did not sound contest way well I end up at 174 so the second one I took way too long it's just I did with prefix um but as you might have saw on the video earlier and I was like oh yeah I should have just do it one in Kell which is the same idea and I started it but I was worried about off by once I really did not I just needed to slow down and think about it more but instead I end up taking more time as it we saw yeah similar to kind of these things for you just keep a running running track and that's pretty much it well this is an n square so that's well this is an n square so that's pretty cool I have to be about this pretty cool I have to be about this later oh I see what it's kind of that's actually really clever that I didn't really think about at all but basically I do is that into code X or some is civil then then then there are then for like so basic you're given I and J if ya like so basic you're given I and J if ya forgiving I and J then if the running forgiving I and J then if the running count from like I've everything between count from like I've everything between a zero that means all the indexes in a zero that means all the indexes in between those two indexes will be will between those two indexes will be will be true because that's like that like if be true because that's like that like if there's equal then they were EXO will there's equal then they were EXO will always be wow that is a because you're always be wow that is a because you're dividing them in halves and byte if by dividing them in halves and byte if by definition because yes if a xop is 0 0 definition because yes if a xop is 0 0 that means a is equal to p and does and that means a is equal to p and does and this is and just kind of reworded that this is and just kind of reworded that back and it's true for all indexes wow back and it's true for all indexes wow that is actually a great answer that's I that is actually a great answer that's I think that's the kind of stuff that you think that's the kind of stuff that you get when you're good at math oh yeah get when you're good at math oh yeah everyone else okay everyone else okay like good but I still either way I like good but I still either way I should have done this really quicker should have done this really quicker because it's known to be good anyway but because it's known to be good anyway but where I shoved on someone like this with where I shoved on someone like this with the rowing rowing number but I did not the rowing rowing number but I did not unfortunately because I was worried unfortunately because I was worried about off-by-one Finister I also went about off-by-one Finister I also went off by one so that didn't really save me yeah same thing here with the n square so well played I know in something today that was kind of good I don't have I learned enough to be able to do it next time still good cool now this is an N square prefix some dad also does the same thing red what okay what okay I mean it's just for you it's it's the same I just the other ones with the same idea and square algorithm where it uses the dynamic programming to do it that way that's clever and to get zeros and then sum up all the counts in between that's a pretty clever way of doing it I was actually thinking about something similar for n square by couldn't come over to any contest well at least I didn't want to spend more time coming | 2024-03-21 02:35:19 | 1,442 | 1442. Count Triplets That Can Form Two Arrays of Equal XOR (Leetcode Medium) |
|
b1sDgaLstd0 | so hello everyone welcome to this new video and i will be explaining the video and i will be explaining the problem number of orders in the backlog problem number of orders in the backlog so this problem is a little bit tougher so this problem is a little bit tougher than medium because than medium because this problem is pretty long okay and as this problem is pretty long okay and as humans we avoid doing long things humans we avoid doing long things so but you know what if you read this so but you know what if you read this problem if you read problem if you read this statement this paragraph is the key this statement this paragraph is the key key to solve this problem it will be key to solve this problem it will be pretty much clear to you pretty much clear to you that what data structure you have to use that what data structure you have to use and how to solve this problem and how to solve this problem okay so uh i will be i please pause this okay so uh i will be i please pause this video and i suggest you that please read video and i suggest you that please read this this statement carefully okay and if you statement carefully okay and if you i hope you have already understood this i hope you have already understood this example okay i just don't want to example okay i just don't want to re-explain and waste time i will get to re-explain and waste time i will get to the coding part okay the coding part okay so let's solve this problem so i will be so let's solve this problem so i will be using this statement to solve the using this statement to solve the problem okay problem okay so first things first let's uh code it so the first thing i will do is that since the answer can be pretty large what i will do is that i will make a modulo in time is equal to what 1 in 9 plus 7 okay uh not a big thing so now what i do is that i read this problem statement if the order is a buy order you look at the sell order with the smallest price in the backlog okay so you know this thing is saying look for the smallest price in the backlog okay and in the second statement you it is saying that look for the largest price in the backlog okay so when you read this kind of things like look for the smallest you know like in a group of things uh what should strike you is that you have to use a priority queue okay so for this problem i have to use two types of priority queue one is maxip and a minip okay so first so in case of a selling backlog in cell backlog uh i it should be the least element should be as at the top so it should be a what minip i guess it is called a mini uh sorry if i intermix them okay and one will be a maxi in which the top element will be the largest so that will be the that will be my buying uh backlog okay so let me let's make these priority queues so let me increase the font 16 will be fine actually it is the maximum so let's make this what is happening so let's make this priority queue priority underscore queue priority queue vector int okay so these vectoring are the order okay buy and sell orders so let's name it bpq that is buying priority queue and one will be our minip so priority priority underscore queue vector in so to make a min heap what you have to do is that along with this thing you have to write uh two other statements vector component one is greater uh let let's name it spq okay so and what you have to do in this uh this vector and greater is that just copy and paste them paste paste okay uh i think i should just decrease the font a little bit okay now it is fine so i have made my two priority queues okay return zero oh just to check if i have not made any uh what uh these arrow mistakes okay it is fine just a second cool so now what i will do is that cool so now what i will do is that i will do i will make a for loop and i will do i will make a for loop and process all the orders okay process all the orders okay all the orders one by one okay so just all the orders one by one okay so just let's write the follow for entire is let's write the follow for entire is equal to zero i less than equal to zero i less than orders dot size i plus plus orders dot size i plus plus i plus plus uh so i plus plus uh so the orders can be of two types uh it is the orders can be of two types uh it is said said either it can be a buy order or it can either it can be a buy order or it can be a sell order okay be a sell order okay so first of all let's make another so first of all let's make another vector vector in vector vector in order it it just basically means the order it it just basically means the current order current order order so i just is just because i am order so i just is just because i am writing this because it is easier for me writing this because it is easier for me to explain like this to explain like this so now the order can be two types so if so now the order can be two types so if order orders uh order two the second order orders uh order two the second is it is a it is zero then it means that is it is a it is zero then it means that it is a buy type of order it is a buy type of order else it will be a cell type of order else it will be a cell type of order okay so okay so if it is a by type of order what i will if it is a by type of order what i will do do i will do exactly what this statement i will do exactly what this statement says so says so i will see i will make a while loop so i will see i will make a while loop so while while is not spq i will just explain it in it is not spq i will just explain it in it in a while in a while empty spq is not empty and and empty spq is not empty and and what spq dot top what spq dot top 0 is less than equal to 0 is less than equal to order order zero okay order order zero okay so basically what i'm saying is that so basically what i'm saying is that what if this statement is saying that if what if this statement is saying that if it is a buy order okay it is a buy order okay you look at the sell order with the you look at the sell order with the smallest price in the backlog okay smallest price in the backlog okay so since uh sell order is a min heap so so since uh sell order is a min heap so if the sell order is not if the sell order is not empty uh cell priority queue is not empty uh cell priority queue is not empty i'm looking at the sell orders top empty i'm looking at the sell orders top element that is the minimum element that is the minimum the smallest one and if the smallest the smallest one and if the smallest ones price ones price okay the price is less than the current okay the price is less than the current order order then i will do something okay so then i will do something okay so uh so this is what this while loop means uh so this is what this while loop means uh so uh so now what i will do is that uh you know now what i will do is that uh you know they will be matched and they will be matched and executed so and that cell order will be executed so and that cell order will be removed from the backlog removed from the backlog okay so what i will do is that i will okay so what i will do is that i will remove that remove that that cell order from the spq so that cell order from the spq so let's make it factor in what let's make it factor in what selling let's name it selling batch selling let's name it selling batch selling batch is equal to what selling batch is equal to what spq dot top and i will remove this spq dot top and i will remove this selling batch from my uh priority queue selling batch from my uh priority queue spq dot pop spq dot pop now what i will do is that there can be now what i will do is that there can be two two possibilities either the selling batches possibilities either the selling batches amount is amount is greater the number of items in the greater the number of items in the selling batch is greater than order or selling batch is greater than order or it can be it can be less than okay so if selling less than okay so if selling batch selling batch one is greater than batch selling batch one is greater than or equal to or equal to order one then what i will do is that i order one then what i will do is that i will will just let me go full screen uh okay just let me go full screen uh okay so now what i will do is that so first so now what i will do is that so first thing first thing first i will do is that i will it since it can i will do is that i will it since it can be greater than the be greater than the order so i will reduce the order so i will reduce the number of amount the amount in my number of amount the amount in my selling batch so selling batch so selling batch one minus equals to order selling batch one minus equals to order one okay so as a result what will happen one okay so as a result what will happen is that my all is that my all my all the amount in my order current my all the amount in my order current order will get exhausted it will become order will get exhausted it will become zero zero okay and if the selling batch is okay and if the selling batch is not exhausted if the selling batch still not exhausted if the selling batch still has some amount left then what i will do has some amount left then what i will do is that if is that if selling batch batch selling batch batch is greater than equal to sorry is greater than equal to sorry let it be greater than zero greater than let it be greater than zero greater than zero zero then what i will do is that i will just then what i will do is that i will just push it push it back into my spq dot push into back into my spq dot push into into my uh selling backlog because into my uh selling backlog because something is still something is still left okay batch be a dch left okay batch be a dch so and after that i will break from this so and after that i will break from this while loop while loop because why because all my order is because why because all my order is exhausted okay exhausted okay on and the second possibility can be on and the second possibility can be else else if the selling batch is less the amount if the selling batch is less the amount is less than the current is less than the current buying orders amount so in that case buying orders amount so in that case what i will do is that what i will do is that i will simply order one minus equals to i will simply order one minus equals to selling batch one selling batch one so my current uh amounts order will be so my current uh amounts order will be used to cancel this used to cancel this selling batch okay and i will selling batch okay and i will go and look for another what another go and look for another what another another order in my backlog another order in my backlog so that's it and after this while loop so that's it and after this while loop is completed what i will do is that is completed what i will do is that if there is some current order still if there is some current order still left if order one is left if order one is greater than equal to one greater than equal to one then what i will do is that or let it be then what i will do is that or let it be greater than zero okay if there is greater than zero okay if there is something left something left then what i will do is that i will push then what i will do is that i will push this current order into my this current order into my buying backlog so bpq dot buying backlog so bpq dot push into what order push into what order order so i don't know if i'm doing a order so i don't know if i'm doing a decent job explaining here because this decent job explaining here because this is a pretty long problem but i hope you is a pretty long problem but i hope you are understanding it okay are understanding it okay so in this way i have processed what if so in this way i have processed what if my order is a buying backlog okay my order is a buying backlog okay so now what i have to do now the thing so now what i have to do now the thing is pretty simple is pretty simple now what i have to do is that exactly now what i have to do is that exactly the same just the same just vice versa basically okay so ctrl vice versa basically okay so ctrl c i will just copy this thing ctrl c and c i will just copy this thing ctrl c and paste this okay paste this okay ctrl v so in this case what i will be ctrl v so in this case what i will be instead instead of s i will be writing bpq is not empty of s i will be writing bpq is not empty and and bpq dot top is what greater than or bpq dot top is what greater than or equal to the current order equal to the current order because you know this is what it is because you know this is what it is saying if the order is a sell order you saying if the order is a sell order you look at the buy order look at the buy order with the largest price okay with the with the largest price okay with the largest price in the backlog if that buy largest price in the backlog if that buy orders price is larger than or equal to orders price is larger than or equal to the current sell orders price the current sell orders price they will match and be executed and that they will match and be executed and that by order will be removed from the by order will be removed from the backlog backlog else the sell order is added to the else the sell order is added to the backlog so this is what i am going to do backlog so this is what i am going to do here so uh i have written this statement here so uh i have written this statement now what i will uh now what i will uh instead of writing selling batch here i instead of writing selling batch here i will just make it will just make it buying batch buying batch so buying buying batch buying batch so buying batch will be bpq dot top and bpq dot batch will be bpq dot top and bpq dot pop pop after using that i will pop it out of my after using that i will pop it out of my buying priority queue buying priority queue and now there again can be two and now there again can be two possibilities either the buying patches possibilities either the buying patches amount can be greater than the order so amount can be greater than the order so in the if the buying batch is greater in the if the buying batch is greater than the order then what i will do is than the order then what i will do is that buying batch minus that buying batch minus order one and my order one will be zero order one and my order one will be zero and if the buying batch is still greater and if the buying batch is still greater than than i'm sorry buying batch buying batches i'm sorry buying batch buying batches amount is greater than one amount is greater than one then i will push it to bpq dot push then i will push it to bpq dot push buying batch also i had done this buying batch also i had done this mistake here it should be one here mistake here it should be one here buying batch one okay so after buying batch one okay so after uh doing this uh another thing can be is uh doing this uh another thing can be is if the buying patch is smaller than the if the buying patch is smaller than the current orders current orders amount then i will subtract this buying amount then i will subtract this buying batches amount from my batches amount from my current order and in the end what i will current order and in the end what i will do do is that uh is that uh in the uh and if my in the uh and if my selling uh selling batch the the current selling uh selling batch the the current order is a selling one order is a selling one okay so if the current orders amount is okay so if the current orders amount is greater than zero after this while loop greater than zero after this while loop then i will push it into my then i will push it into my spq backlog okay so you know this is the spq backlog okay so you know this is the thing thing main thing you have to do main thing you have to do so i have done this so i have done this now uh my thing is done now what i will now uh my thing is done now what i will do is that i will just do is that i will just make a what int make a what int res is equal to zero and while res is equal to zero and while i will just process that whatever is i will just process that whatever is left in my priority queues left in my priority queues i will i will just i will i will just uh i will just count them okay uh i will just count them okay so while is not bp so while is not bp bpq dot empty empty while bpq is not bpq dot empty empty while bpq is not empty what i will do is that res is empty what i will do is that res is equal to i will increase my results equal to i will increase my results count okay count okay so res is equal to res so res is equal to res plus what bpq dot plus what bpq dot top bpq dot top one top bpq dot top one percent m uh so here also it will be percent m uh so here also it will be percent m percent m because amount can be because amount can be go a little bigger than go a little bigger than like what 10 raised to 9 like what 10 raised to 9 so i will just add it and now what i so i will just add it and now what i will do is that bpq dot will do is that bpq dot pop and now again i will pop and now again i will write a while loop while is not bp write a while loop while is not bp for spq while is not spq dot for spq while is not spq dot empty uh what i will do is that empty uh what i will do is that res uh just basically the same thing res uh just basically the same thing ctrl c ctrl v so ctrl c ctrl v so i will write s here and s here and i will write s here and s here and return res return res so that's the problem so so that's the problem so let's submit it so it is running fine let's submit it so it is running fine on the test cases now let's submit it on the test cases now let's submit it and hope if it is working it is 100 and hope if it is working it is 100 faster that's faster that's that's very good so you know just let's that's very good so you know just let's summarize it summarize it so this is basically a simple priority q so this is basically a simple priority q questions questions make two priority question the main make two priority question the main thing is writing this logic thing is writing this logic it can you can go wrong but if you it can you can go wrong but if you follow these statements the statements follow these statements the statements that are given here that are given here it will not be very much tough so if you it will not be very much tough so if you have understood the problem have understood the problem please like this video and subscribe the please like this video and subscribe the channel so thank you and have a nice day | 2024-03-21 21:50:04 | 1,801 | LeetCode 1801. Number of Orders in the Backlog | 🏆 Weekly Contest 233 | Medium | Algorithm Explained |
|
miZ3qV04b1g | 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 ones and zeros let's solve the problem ones and zeros we're given an array of binary strings we're given an array of binary strings and two integers M and N it's gonna be and two integers M and N it's gonna be fun saying those two because they sound fun saying those two because they sound so similar so suppose these are the so similar so suppose these are the binary strings that were given there's binary strings that were given there's five of them each of them is composed of five of them each of them is composed of just ones and zeros and we're given a just ones and zeros and we're given a couple integers let's say m in this case couple integers let's say m in this case is 5 and N in this case is three just is 5 and N in this case is three just like in this example over here we want like in this example over here we want to return from this the length of the to return from this the length of the largest subset of this set of strings we largest subset of this set of strings we can create if we're allowed to use at can create if we're allowed to use at most this many zero characters so m in most this many zero characters so m in this case corresponds to zero and these this case corresponds to zero and these are the zeros in our input strings and N are the zeros in our input strings and N corresponds to one so these ones over corresponds to one so these ones over here and we can use at most three ones here and we can use at most three ones and at most five zeros so I guess the and at most five zeros so I guess the first thing you might consider is can we first thing you might consider is can we just take all of these strings all five just take all of these strings all five of them well how many zeros would we get of them well how many zeros would we get in that case we'd get one two three four in that case we'd get one two three four five six seven that's too many zeros how five six seven that's too many zeros how many ones would we get in that case I many ones would we get in that case I think we're allowed to get three but we think we're allowed to get three but we would get one two three four five six would get one two three four five six seven so more than we're allowed to get seven so more than we're allowed to get so we definitely can't take all five of so we definitely can't take all five of these strings so then how do we these strings so then how do we intelligently figure out how many we can intelligently figure out how many we can get well the Brute Force way to solve get well the Brute Force way to solve this problem would be with a decision this problem would be with a decision tree so for each one of these we tree so for each one of these we consider if we include it so in this consider if we include it so in this path maybe we're including that string path maybe we're including that string and the other path is where we skip it and the other path is where we skip it and we don't include it and we make this and we don't include it and we make this same decision for every single string so same decision for every single string so continuing with this decision tree here continuing with this decision tree here we can either choose to include zero we can either choose to include zero zero zero one or we skip it here we can zero zero one or we skip it here we can do the same thing include it or skip it do the same thing include it or skip it so you can see each one of these paths so you can see each one of these paths is going to tell us by the time we get is going to tell us by the time we get all the way to the bottom each one of all the way to the bottom each one of these paths is going to tell us which these paths is going to tell us which one of these we would have included or one of these we would have included or not included and each one of these paths not included and each one of these paths will be a different subset and how do we will be a different subset and how do we know which one we're going to return know which one we're going to return from all of those well we're going to from all of those well we're going to find the one that is the longest as in find the one that is the longest as in it has the most strings in it and let's it has the most strings in it and let's say in this case that's going to give us say in this case that's going to give us a 4 we're going to get a set of four I a 4 we're going to get a set of four I think that would look like this these think that would look like this these four over here because in that case four over here because in that case we'll have three ones and we'll have we'll have three ones and we'll have five zeros so these four do satisfy our five zeros so these four do satisfy our requirements and it's the longest requirements and it's the longest possible set we could create the largest possible set we could create the largest as four strings in it so that's what we as four strings in it so that's what we would return now this Brute Force would return now this Brute Force approach the size of this decision tree approach the size of this decision tree the height of it is going to be in the the height of it is going to be in the worst case the length of this strings worst case the length of this strings well the size of this array that's the well the size of this array that's the height of this tree is going to be we height of this tree is going to be we can call that n and we're going to be can call that n and we're going to be branching twice every single time so to branching twice every single time so to calculate the size of the tree it's calculate the size of the tree it's going to be roughly 2 to the power of n going to be roughly 2 to the power of n so it's not super efficient how can we so it's not super efficient how can we make this better well as we go along make this better well as we go along this decision tree we're going to be this decision tree we're going to be keeping track of how many M's and ends keeping track of how many M's and ends we have initially it's five and three we have initially it's five and three this is how many we have available to us this is how many we have available to us and then when we go down to this path we and then when we go down to this path we don't have five and three remaining we don't have five and three remaining we have four zeros remaining and two ones have four zeros remaining and two ones remaining because we used one of each remaining because we used one of each and by the time we get down here we have and by the time we get down here we have three less M's remaining because those three less M's remaining because those keep track of zeros so instead of having keep track of zeros so instead of having four and two like over here we'd have four and two like over here we'd have one and one because we used three zeros one and one because we used three zeros and we used one of our ones and we'd and we used one of our ones and we'd keep doing this now we're keeping track keep doing this now we're keeping track of our M's and our ends but we have a of our M's and our ends but we have a third variable which is going to be I third variable which is going to be I it's going to tell us which string we're it's going to tell us which string we're currently at first we start at the first currently at first we start at the first string then we go to the second string string then we go to the second string then we go to the third that like then we go to the third that like decides what level of this tree we're in decides what level of this tree we're in as well so we in total have three as well so we in total have three parameters M and an I but we can use parameters M and an I but we can use these three parameters to implement a these three parameters to implement a dynamic programming technique called dynamic programming technique called caching or AKA memoization but we have caching or AKA memoization but we have to calculate how many possible to calculate how many possible combinations will there be for these combinations will there be for these three parameters well for M there's three parameters well for M there's going to be what the capacity of M going to be what the capacity of M possibly was so we'll just use M to possibly was so we'll just use M to denote itself same with n it can't have denote itself same with n it can't have more possibilities than these it'll be more possibilities than these it'll be from zero all the way through what the from zero all the way through what the true value of n is passed in as a true value of n is passed in as a parameter so we'll have M times n times parameter so we'll have M times n times times the length or the number of times the length or the number of strings we have in the input let's say strings we have in the input let's say that's s so overall this is how many that's s so overall this is how many times the function could be called our times the function could be called our recursive function when we cache the recursive function when we cache the result every time we compute a possible result every time we compute a possible value for it we're going to Cache it and value for it we're going to Cache it and then we're never going to have to repeat then we're never going to have to repeat that work this time complexity will be that work this time complexity will be the same as the memory complexity as the same as the memory complexity as well because this is the size of our well because this is the size of our cache now let me show you what I've been cache now let me show you what I've been talking about this entire time so this talking about this entire time so this is going to be the memoization code I'm is going to be the memoization code I'm going to show you our cache is initially going to show you our cache is initially going to be this dynamic programming going to be this dynamic programming hashmap it stands for dynamic hashmap it stands for dynamic programming this is our recursive programming this is our recursive function I'm going to call it DFS you function I'm going to call it DFS you can call it what you'd like but we have can call it what you'd like but we have three parameters i m and n the other three parameters i m and n the other parameters we don't have to worry about parameters we don't have to worry about because this function is nested inside because this function is nested inside of this one so in this recursion we know of this one so in this recursion we know it's going to be pretty simple but we do it's going to be pretty simple but we do have to worry about a few base cases one have to worry about a few base cases one one is what if we go out of bounds like one is what if we go out of bounds like how do we know when we can stop going how do we know when we can stop going through all the strings well when our through all the strings well when our pointer I is equal to the length of that pointer I is equal to the length of that array in which case we can return 0 array in which case we can return 0 because there's zero strings that we because there's zero strings that we could add at that point if we don't have could add at that point if we don't have any left to choose from and the other any left to choose from and the other base case is if this has already been base case is if this has already been computed meaning if this Tuple is computed meaning if this Tuple is already a key in our DP hash map then already a key in our DP hash map then we're just going to return the value we're just going to return the value that this key corresponds to now if that this key corresponds to now if neither of the base cases execute then neither of the base cases execute then we actually have our recursive step so we actually have our recursive step so we're going to call DFS now we have two we're going to call DFS now we have two choices remember we can either not choices remember we can either not include the value not include the string include the value not include the string at index I what would we do in that case at index I what would we do in that case then we're going to call DFS on I plus then we're going to call DFS on I plus one and we're going to leave M and N the one and we're going to leave M and N the same we're not going to do anything with same we're not going to do anything with them now the the other case is if we're them now the the other case is if we're going to include the string at index I going to include the string at index I in that case we're still going to pass in that case we're still going to pass in I plus 1 we're going to go to the in I plus 1 we're going to go to the next string but what are we going to next string but what are we going to pass in for M and N because we have to pass in for M and N because we have to count how many zeros were in the string count how many zeros were in the string which string am I talking about well which string am I talking about well it's the string at index I we have to it's the string at index I we have to count how many zeros there were so I'm count how many zeros there were so I'm going to run that function count the going to run that function count the number of zero characters we also have number of zero characters we also have to count the number of one character so to count the number of one character so let's do the same thing here and let's let's do the same thing here and let's store these in a couple variables let's store these in a couple variables let's say m count and N count and then using say m count and N count and then using these counts we're going to subtract these counts we're going to subtract from these variables so M the new count from these variables so M the new count of M is going to be what it originally of M is going to be what it originally was minus the M's in the current string was minus the M's in the current string that we just used same thing for n so that we just used same thing for n so let's do do just this now we have our let's do do just this now we have our two recursive calls what do we want to two recursive calls what do we want to do with them we want to figure out which do with them we want to figure out which one led to the maximum that's what we're one led to the maximum that's what we're trying to do here we're trying to find trying to do here we're trying to find what is the maximum number of strings we what is the maximum number of strings we could include without overflowing these could include without overflowing these two restrictions so let's just take the two restrictions so let's just take the max of both of these I'm going to write max of both of these I'm going to write it like this I don't know what the it like this I don't know what the cleanest way to write it in Python is cleanest way to write it in Python is but I'm going to put it onto multiple but I'm going to put it onto multiple lines this Max we're going to set it lines this Max we're going to set it equal to the value but we're going to equal to the value but we're going to store it in our DP hash map using this store it in our DP hash map using this as the key and we of course want it to as the key and we of course want it to be set to the maximum and then after be set to the maximum and then after that we're going to go ahead and return that we're going to go ahead and return that same value actually I missed that same value actually I missed something here maybe you already caught something here maybe you already caught it but how do we know that the remaining it but how do we know that the remaining count of M and the remaining count of n count of M and the remaining count of n is actually valid what if this be became is actually valid what if this be became negative that means we didn't have negative that means we didn't have enough zeros or ones to actually use the enough zeros or ones to actually use the string at index I in the first place so string at index I in the first place so actually we have to change this a bit I actually we have to change this a bit I think the easiest way to write it is to think the easiest way to write it is to initially set the value in DP equal to initially set the value in DP equal to this value where if we were to skip the this value where if we were to skip the string at index I and then we check this string at index I and then we check this if M count is less than or equal to how if M count is less than or equal to how many M's we're allowed to use and N many M's we're allowed to use and N count is less than or equal to the count is less than or equal to the number of ends we're allowed to use then number of ends we're allowed to use then in that case we will possibly be able to in that case we will possibly be able to set the new DP value equal to a set the new DP value equal to a different one we'll have to set it equal different one we'll have to set it equal to the max of what it currently is and to the max of what it currently is and the max of this call down here so let me the max of this call down here so let me cut that and add it down here clean this cut that and add it down here clean this up a bit but maybe this was even more up a bit but maybe this was even more educational to have caught a bug la live educational to have caught a bug la live as we're coding so these are the two as we're coding so these are the two cases now we just have to actually call cases now we just have to actually call our DFS we'll start at index 0 our M and our DFS we'll start at index 0 our M and N count will be whatever is supplied to N count will be whatever is supplied to us up here and then we're just going to us up here and then we're just going to return the value that we compute from return the value that we compute from that ah there was one last bug and it's that ah there was one last bug and it's over here if we are choosing to include over here if we are choosing to include the string at index I then the total the string at index I then the total number of strings is guess going to be number of strings is guess going to be the total number of strings from the sub the total number of strings from the sub problem which is if we were to have this problem which is if we were to have this new M and N remaining and starting at I new M and N remaining and starting at I plus 1 but we have to include the string plus 1 but we have to include the string that we just added so we're going to say that we just added so we're going to say one plus the result of this sub problem one plus the result of this sub problem if we actually do include the string if if we actually do include the string if we don't include the string we don't we don't include the string we don't have to put a plus one because we didn't have to put a plus one because we didn't include anything we just have to go and include anything we just have to go and solve this sub problem I hope that solve this sub problem I hope that clears it up but now let's run the code clears it up but now let's run the code and as you can see it works and it's and as you can see it works and it's pretty efficient let me quickly show you pretty efficient let me quickly show you the more efficient dynamic programming the more efficient dynamic programming solution without recursion now if we solution without recursion now if we were to code this up without recursion were to code this up without recursion we could do so with three Loops because we could do so with three Loops because in this case our cache is going to be in this case our cache is going to be three dimensions we're going to follow three dimensions we're going to follow very similar ideas we're going to use very similar ideas we're going to use the same key as you can see over here the same key as you can see over here we're using i m and n as the composite we're using i m and n as the composite key for the string we are counting how key for the string we are counting how many zeros and ones it has and then many zeros and ones it has and then we're iterating through possible M and N we're iterating through possible M and N values in this case M and N are once values in this case M and N are once again going to whoops refer to how many again going to whoops refer to how many zeros and how many ones we have zeros and how many ones we have remaining so we're going to use the remaining so we're going to use the count of the string to make sure we have count of the string to make sure we have enough to actually use this string and enough to actually use this string and if we do have enough to use it then if we do have enough to use it then we're going to take the max of pretty we're going to take the max of pretty much the same value that we used before much the same value that we used before 1 plus the sub problem DP now here 1 plus the sub problem DP now here instead of saying I play plus one we're instead of saying I play plus one we're doing I minus 1 because we're iterating doing I minus 1 because we're iterating through from left to right you could through from left to right you could iterate in Reverse I'll show you that iterate in Reverse I'll show you that one in just a second but here we're one in just a second but here we're iterating in the opposite direction so iterating in the opposite direction so we're doing I minus one that's the sub we're doing I minus one that's the sub problem so in this case I refers to problem so in this case I refers to we're allowed to use the string at index we're allowed to use the string at index I and every previous string that's kind I and every previous string that's kind of like the sub problem in this case of like the sub problem in this case that's why we say I minus 1 when we look that's why we say I minus 1 when we look to solve a sub problem now if we're not to solve a sub problem now if we're not allowed to use it then we just set it allowed to use it then we just set it equal to the value at I minus 1 because equal to the value at I minus 1 because yes we can't use the string at I at yes we can't use the string at I at index I but we're allowed to use every index I but we're allowed to use every previous string so we just take the max previous string so we just take the max value from I minus 1 with the same M and value from I minus 1 with the same M and N values and then we will return the N values and then we will return the value at the largest possible indices in value at the largest possible indices in this case actually I change the M and N this case actually I change the M and N to be Capital so then I can actually use to be Capital so then I can actually use these two as like iterators through our these two as like iterators through our Loops but you can see otherwise this is Loops but you can see otherwise this is pretty similar to the recursive solution pretty similar to the recursive solution the complicated part is pretty much just the complicated part is pretty much just figuring out which direction to iterate figuring out which direction to iterate through and also that here we need to through and also that here we need to start at zero instead of one the reason start at zero instead of one the reason being in some cases we might decide to being in some cases we might decide to use zero occurrences of a character of a use zero occurrences of a character of a zero or a one we can choose to not zero or a one we can choose to not include any if we want to but otherwise include any if we want to but otherwise this is the iterative solution the time this is the iterative solution the time and space complexity is pretty much the and space complexity is pretty much the same though now let me show you a way we same though now let me show you a way we can actually improve the space can actually improve the space complexity and this is how we could do complexity and this is how we could do it you can see we are once again using a it you can see we are once again using a hash map the fact that this is a default hash map the fact that this is a default deck just means that if we go out of deck just means that if we go out of bounds it's going to return a default bounds it's going to return a default value in this case an integer and the value in this case an integer and the value is going to be zero which is value is going to be zero which is exactly what we need in our case this is exactly what we need in our case this is pretty similar except we are iterating pretty similar except we are iterating in reverse order and the previous in reverse order and the previous solution I actually showed you will not solution I actually showed you will not pass I think it gives time limit pass I think it gives time limit exceeded even though the time complexity exceeded even though the time complexity is the same as the recursive one leak is the same as the recursive one leak code is just kind of weird but this one code is just kind of weird but this one will pass this iterative solution will will pass this iterative solution will pass on leak code because it's a bit pass on leak code because it's a bit more efficient not just because we're more efficient not just because we're using less memory here you can see when using less memory here you can see when we set a value we're setting it once we set a value we're setting it once again equal to the max but we're not again equal to the max but we're not using I as a key in our hash map and we using I as a key in our hash map and we are iterating through this in reverse are iterating through this in reverse order while the M and N values in order while the M and N values in reverse order because the way we build reverse order because the way we build the grid and it's going to be hard to the grid and it's going to be hard to explain so let me go back to the explain so let me go back to the Whiteboard real quick we know that our Whiteboard real quick we know that our cache is three dimension so it's going cache is three dimension so it's going to be hard to describe it visually but to be hard to describe it visually but let's say that this is one of the layers let's say that this is one of the layers of the three dimensions this is like our of the three dimensions this is like our grid M by n this is for I equals one grid M by n this is for I equals one basically the first string and then we basically the first string and then we have another grid over here for I equals have another grid over here for I equals one the second string previously I one the second string previously I showed us filling in the grid like this showed us filling in the grid like this from top to bottom this is what I meant from top to bottom this is what I meant when I said top to bottom but suppose when I said top to bottom but suppose from this position sometimes we need to from this position sometimes we need to take our M value and subtract it so we take our M value and subtract it so we have to look up from here if we want to have to look up from here if we want to fill in the value at this position we fill in the value at this position we have to look above us sometimes we have have to look above us sometimes we have to subtract from the N so we have to to subtract from the N so we have to look to the left so we might have to look to the left so we might have to look to the left or up or maybe even to look to the left or up or maybe even to the top left because if we use the the top left because if we use the current string then we have less zeros current string then we have less zeros and less ones remaining to choose from and less ones remaining to choose from so we have to possibly look in this so we have to possibly look in this direction when we look in that direction direction when we look in that direction we never look at the same grid we never we never look at the same grid we never look at the same I value right now what look at the same I value right now what we're doing is taking the I value and we're doing is taking the I value and saying I minus 1. we're going to look in saying I minus 1. we're going to look in the previous grid and we're going to the previous grid and we're going to look at it going in the top left look at it going in the top left Direction now what I'm doing instead of Direction now what I'm doing instead of having both of these grids in memory having both of these grids in memory though I'm only keeping a single Grid in though I'm only keeping a single Grid in memory because I want to reduce the memory because I want to reduce the memory complexity from being n times m memory complexity from being n times m times s I'm changing it to now only be n times s I'm changing it to now only be n times M so doing it this way if we fill times M so doing it this way if we fill this in going top to left and then when this in going top to left and then when we get to here and we want to look in we get to here and we want to look in the top left but what we actually want the top left but what we actually want to find is the original value that we to find is the original value that we stored up here but if we overwrote that stored up here but if we overwrote that we can't do that anymore so what we we can't do that anymore so what we instead do is don't fill top to bottom instead do is don't fill top to bottom we fill bottom to top so like this so we fill bottom to top so like this so now if we got to this position and now if we got to this position and looked at the top left we would find the looked at the top left we would find the original values we would never search original values we would never search bottom or to the right so we'd never bottom or to the right so we'd never even care what we have stored here we'd even care what we have stored here we'd only look at the top left so that's why only look at the top left so that's why we're doing this in reverse order and we're doing this in reverse order and lastly not only are we doing it in lastly not only are we doing it in reverse order but here starting at M reverse order but here starting at M we're going to go up until the count we're going to go up until the count minus one the number of zeros minus one minus one the number of zeros minus one and the reason we have the minus one and the reason we have the minus one here is just because in Python this last here is just because in Python this last value is non-inclusive so we have to go value is non-inclusive so we have to go one past that but the reason we're going one past that but the reason we're going up until M count is because we don't up until M count is because we don't need to go to any values smaller than need to go to any values smaller than that because if we need three zeros for that because if we need three zeros for this current string why should we even this current string why should we even consider any of the loop iterations consider any of the loop iterations where we have less than that why should where we have less than that why should we even consider any of the loop we even consider any of the loop iterations where we only have zero zeros iterations where we only have zero zeros or maybe we only have two zeros but we or maybe we only have two zeros but we need three of them so we're not even need three of them so we're not even going to consider this iteration of the going to consider this iteration of the loop this is kind of a shortcut and this loop this is kind of a shortcut and this is what helps get this solution to pass is what helps get this solution to pass on leak code so lastly I'll run this on leak code so lastly I'll run this just to prove it to you that it does just to prove it to you that it does work and as you can see it does but the work and as you can see it does but the runtime is kind of random on late cut I runtime is kind of random on late cut I don't really pay too much attention to don't really pay too much attention to it but if this was helpful please like it but if this was helpful please like And subscribe if you're preparing for And subscribe if you're preparing for coding interviews check out neat code.io coding interviews check out neat code.io it has a ton of free resources to help it has a ton of free resources to help you prepare thanks for watching and you prepare thanks for watching and hopefully I'll see you pretty soon | 2024-03-18 10:55:54 | 474 | Ones and Zeroes - Leetcode 474 - Python |
|
zBCsKSFRRYY | hello and welcome back to the cracking fang youtube channel today we're going fang youtube channel today we're going to be solving leap code problem 1344 to be solving leap code problem 1344 angle between hands of a clock before we angle between hands of a clock before we get into the problem i would just like get into the problem i would just like to ask you to subscribe i have a goal of to ask you to subscribe i have a goal of reaching 1 000 subscribers on my channel reaching 1 000 subscribers on my channel before the end of may and i need your before the end of may and i need your help to get there so if you're enjoying help to get there so if you're enjoying the content and you like the videos that the content and you like the videos that i'm making please subscribe to my i'm making please subscribe to my channel and help me grow this is going channel and help me grow this is going to help me reach a broader audience and to help me reach a broader audience and make more videos for you guys so you can make more videos for you guys so you can get into fang as well that being said get into fang as well that being said let's read the question prompt given two let's read the question prompt given two numbers hour and minutes return the numbers hour and minutes return the smaller angle in degrees formed between smaller angle in degrees formed between the hour and the minute hand the hour and the minute hand for example if we're given this hour 12 for example if we're given this hour 12 and minutes 30 so 12 30 we want to and minutes 30 so 12 30 we want to calculate the difference in degrees calculate the difference in degrees between the two hands so basically what between the two hands so basically what is the difference here is the difference here so what we need to do is we need to so what we need to do is we need to figure out what the degrees of the hour figure out what the degrees of the hour is and the degrees of the minutes is is and the degrees of the minutes is so the minutes is a little bit simpler so the minutes is a little bit simpler because we don't have to deal with the because we don't have to deal with the fact that the hour hand is actually fact that the hour hand is actually going to move relative to where going to move relative to where um um you know the minutes is right the the you know the minutes is right the the hour hand will move as we can see it's hour hand will move as we can see it's halfway between 12 and 1 because we're halfway between 12 and 1 because we're halfway through the hour so that's going halfway through the hour so that's going to be a little bit trickier so let's do to be a little bit trickier so let's do the minutes first so minutes as we know the minutes first so minutes as we know is going to be whatever the minutes is is going to be whatever the minutes is so 30 and how many degrees are in a so 30 and how many degrees are in a minute right so if there's 360 degrees minute right so if there's 360 degrees in an hour in an hour then every minute and the 60 per hour so then every minute and the 60 per hour so we expect 360 divided by 60 we expect 360 divided by 60 uh degrees per minute so this means that uh degrees per minute so this means that this calculation so we can really think this calculation so we can really think of this as six so of this as six so we can think of it as having the minute we can think of it as having the minute hand is going to have 180 degrees hand is going to have 180 degrees now for the hour hand so we'll just say now for the hour hand so we'll just say m here m here the hour hand its degrees is going to be the hour hand its degrees is going to be a little bit more complicated not only a little bit more complicated not only do we have to account for you know the do we have to account for you know the base position of the hour we need to base position of the hour we need to also account for how far to the next also account for how far to the next hour it is relative to the minute hand hour it is relative to the minute hand so the way that we're going to do this so the way that we're going to do this is we're going to calculate the base is we're going to calculate the base kind of degrees for the hour which is kind of degrees for the hour which is going to be the hour going to be the hour uh times so how many degrees are in an uh times so how many degrees are in an hour so we have 360 degrees per hour and hour so we have 360 degrees per hour and then you know 12 hour markers then you know 12 hour markers uh per day right so sorry 360 per day uh per day right so sorry 360 per day and then we have 12 hour markers so we and then we have 12 hour markers so we can think of this as really being 30 can think of this as really being 30 right right oops you can't really see that uh so oops you can't really see that uh so this upper portion here is 30. so we're this upper portion here is 30. so we're really multiplying the hour times 30 really multiplying the hour times 30 plus then we need to account for the plus then we need to account for the fact that the hour hand is actually fact that the hour hand is actually going to be somewhere between the going to be somewhere between the current hour and the next hour based on current hour and the next hour based on where the minute hand is so where the minute hand is so we just need to account for that by okay we just need to account for that by okay we have if we have 30 degrees per hour we have if we have 30 degrees per hour now we need to multiply it by how far it now we need to multiply it by how far it is between uh the next hour which is is between uh the next hour which is going to be going to be you know the number of you know the number of uh essentially minutes uh essentially minutes that have elapsed in this hour so we'll that have elapsed in this hour so we'll do minutes over do minutes over 60 right 60 right because that's the amount of degrees because that's the amount of degrees that we're gonna have in that one that we're gonna have in that one um period so um period so for this one in particular so we have for this one in particular so we have the hour so it's going to be 12 so we the hour so it's going to be 12 so we have 12 have 12 times uh 30 times uh 30 plus plus uh what do we have here 12 times 30 uh what do we have here 12 times 30 times times 30 30 times what is it uh 30 times what is it uh 30 over 60 over 60 right so right so this is going to be what this is going to be what uh let's see uh let's see 12 times 30 this is 360. 12 times 30 this is 360. plus 30 times basically one half so 15 plus 30 times basically one half so 15 so here we actually get 375 which so here we actually get 375 which doesn't really make sense right because doesn't really make sense right because right an hour only has 360 degrees right an hour only has 360 degrees well the reason that we get this is that well the reason that we get this is that you know you know when we get our solution we actually when we get our solution we actually just need to take the difference between just need to take the difference between the i guess the hour the i guess the hour uh degrees and the minute degrees but as uh degrees and the minute degrees but as you notice we can get you know negative you notice we can get you know negative numbers here or they can be in the wrong numbers here or they can be in the wrong direction so what we need to do is we direction so what we need to do is we now need to take the difference between now need to take the difference between these two so we're going to say 375 these two so we're going to say 375 minus 180 so this is going to be what um minus 180 so this is going to be what um 195 right 195 right but this actually isn't the correct but this actually isn't the correct answer answer uh because it's too big right that would uh because it's too big right that would actually be this bigger half so what we actually be this bigger half so what we need to do is we don't know which side need to do is we don't know which side we're actually calculating it for we we're actually calculating it for we could be on the wrong side could be on the wrong side we could be calculating the bigger side we could be calculating the bigger side but remember we want the smaller angle but remember we want the smaller angle right there's two angles that are formed right there's two angles that are formed here this big one and the small one but here this big one and the small one but we don't know which one it is so our we don't know which one it is so our final answer is actually going to be the final answer is actually going to be the minimum minimum of whatever the difference is so like of whatever the difference is so like 195 195 and then 365 and then 365 minus 195. so we take the difference of minus 195. so we take the difference of 300 no not 365 sorry it's 360. uh let me 300 no not 365 sorry it's 360. uh let me undo that 360 minus whatever 195 is and undo that 360 minus whatever 195 is and we can see that this is actually going we can see that this is actually going to be the smaller one so this will be to be the smaller one so this will be our answer our answer and that's what we're going to return and that's what we're going to return right 165 here so that's how we get that right 165 here so that's how we get that answer so that's really the approach answer so that's really the approach that we want to take what we want to do that we want to take what we want to do is first calculate the degrees for the is first calculate the degrees for the minutes which is going to follow the minutes which is going to follow the formula of whatever the minutes is so formula of whatever the minutes is so this is the minutes that we were given this is the minutes that we were given times 360 divided by 60 which is six and times 360 divided by 60 which is six and we're going to get that degrees then we're going to get that degrees then we're going to calculate the hour which we're going to calculate the hour which is going to be whatever the hour is is going to be whatever the hour is times 360 divided by 12 which is 30 plus times 360 divided by 12 which is 30 plus 30 which we just got here 30 which we just got here times times the amount of minutes that have elapsed the amount of minutes that have elapsed in the hour and that'll tell us how far in the hour and that'll tell us how far in between the next hour it is and that in between the next hour it is and that will be our hour degrees then we take will be our hour degrees then we take the difference between these two the difference between these two absolute value absolute value because it could be negative and then we because it could be negative and then we want to return is the minimum between want to return is the minimum between that value we just got and 360 minus it that value we just got and 360 minus it because again we don't know which angle because again we don't know which angle we're going to be working with so that's we're going to be working with so that's the approach that we want to take the the approach that we want to take the code is super simple it's literally four code is super simple it's literally four lines of code here so let's go to the lines of code here so let's go to the code editor write this up it's going to code editor write this up it's going to take no time at all so i'll see you take no time at all so i'll see you there and now remember that i said the there and now remember that i said the lines of code for this is only going to lines of code for this is only going to be four so this is going to be super be four so this is going to be super simple let's write the code so all we simple let's write the code so all we need is the minute degrees and the hour need is the minute degrees and the hour degrees so let's derive those so degrees so let's derive those so remember that the minute degrees is remember that the minute degrees is going to be equal to the number of going to be equal to the number of minutes we have minutes we have times the number of degrees for each times the number of degrees for each minute so if there's 360 uh degrees in minute so if there's 360 uh degrees in an hour and there's an hour and there's 60 minutes in an hour then 360 divided 60 minutes in an hour then 360 divided by 60 will tell us the number of degrees by 60 will tell us the number of degrees per minute and if we multiply by that by per minute and if we multiply by that by the minutes we'll get the minute degrees the minutes we'll get the minute degrees now for the hour degrees remember that now for the hour degrees remember that it's a little bit more complex in that it's a little bit more complex in that we need the base hour we need the base hour and then we need how far it is to the and then we need how far it is to the next hour right we need to figure out next hour right we need to figure out you know how far in between 12 and what you know how far in between 12 and what it is relative to how far the hour hand it is relative to how far the hour hand is through the hour so to calculate the is through the hour so to calculate the base hour we're going to say we're going base hour we're going to say we're going to take the current hour and we're going to take the current hour and we're going to multiply it by 360 divided by 12 to multiply it by 360 divided by 12 right because there's 12 positions for right because there's 12 positions for the hour and the clock and there's you the hour and the clock and there's you know 360 degrees for one full rotation know 360 degrees for one full rotation of the hour hand of the hour hand then we need to account for the fact then we need to account for the fact that the hour hand is going to move uh that the hour hand is going to move uh part way to the next hour so we're going part way to the next hour so we're going to do that by saying okay to do that by saying okay again there's 360 divided by 12 again there's 360 divided by 12 degrees in an hour but we need to figure degrees in an hour but we need to figure out what fraction of it the next hour out what fraction of it the next hour we're closer to so we need to multiply we're closer to so we need to multiply that so we can just rewrite this as 30 that so we can just rewrite this as 30 just to keep things tidy and we'll just to keep things tidy and we'll rewrite this i will just leave that for rewrite this i will just leave that for now now and then we'll do minutes and then we'll do minutes time divided by 60. so this is the ratio time divided by 60. so this is the ratio of how far the minute hand is of how far the minute hand is to the next hour which will tell us how to the next hour which will tell us how far our current hour hand is between the far our current hour hand is between the two hours so that will be our minute two hours so that will be our minute degrees and our degrees now remember degrees and our degrees now remember that we need to calculate the difference that we need to calculate the difference between these two and since it can be between these two and since it can be negative we need to have the absolute negative we need to have the absolute value so we're going to say minute value so we're going to say minute degrees minus our degrees and since we don't know um you know which side of the angle we actually took from this because we took the absolute value we now need to simply return whichever one is smaller our difference or 360 degrees minus our difference in the case that we took the larger half on accident because of this absolute value we won't actually know uh which half we took so that's why we need to return the minimum here so let us submit this make sure we haven't made any bugs and we can see that we solve the problem so what is the time and space complexity for this algorithm well the time complexity is going to be big o of one why because we don't need to make any sort of you know parsings through our hour and minutes all we're gonna have to do is just um do some simple calculations and this is gonna happen in constant time right this is just three constant time computations and that's it for the space again we just create some variables to hold these arithmetic results we're not creating any new data structures anything like that so it's also going to be big of one and big of one for the space so the time is bigger one space is big oven super simple this problem is really easy i'm not sure why it's medium i think it's just knowing how to operate um you know i guess a clock but you know if you get it it's always good to know how to solve it anyway if you enjoyed this video please leave a like comment uh subscribe to the channel if there's any videos you'd like me to make please leave it in the comment section below i'll be happy to get back to you guys just tell me what you want to see and i'll make the videos otherwise have | 2024-03-21 00:17:07 | 1,344 | ANGLE BETWEEN HANDS OF A CLOCK | LEETCODE 1344 | PYTHON SOLUTION |
|
swVRcSXT_Eg | today we're going to be solving lead code problem 303 range sum query and code problem 303 range sum query and this one is immutable this one is immutable so given an integer array nums handle so given an integer array nums handle multiple queries of the following type multiple queries of the following type so we have to calculate the sum of the so we have to calculate the sum of the elements of nums between indices left elements of nums between indices left and right inclusive where we have left and right inclusive where we have left is less than equal to right is less than equal to right so for our first example so for our first example we have we have negative 2 0 three negative five two and negative 2 0 three negative five two and negative one in our array so then we negative one in our array so then we take take the sum range from zero to two the sum range from zero to two these three indices and then two to five these three indices and then two to five and then zero to five and so then our and then zero to five and so then our output would just be null or or just output would just be null or or just zero zero and then we have one negative one and and then we have one negative one and then three respectively to each of those then three respectively to each of those so this problem is a dynamic programming so this problem is a dynamic programming problem and the solution to this problem problem and the solution to this problem is pretty straightforward so we have to is pretty straightforward so we have to create create some variable i'm going to call it acc some variable i'm going to call it acc for accumulate and that's going to just for accumulate and that's going to just equal an array with 0 in it equal an array with 0 in it and then for num and nums and then for num and nums we say self we say self dot acc dot acc plus equals an array of self dot acc plus equals an array of self dot acc negative one negative one plus num and then for the sum range all we have to do acc acc rights plus one rights plus one minus the self minus the self diac diac left okay so what we're doing here left okay so what we're doing here is is we're creating an array acc we're creating an array acc for accumulate for accumulate that stores the accumulated sum for nums that stores the accumulated sum for nums such that accumulated left such that accumulated left equals equals the nums zero with element plus and nums the nums zero with element plus and nums first element and so on and so forth in first element and so on and so forth in the initializer of num array the initializer of num array then we just return in the sum range we then we just return in the sum range we just return acc of right plus 1 minus just return acc of right plus 1 minus acc of left and the sum range and that acc of left and the sum range and that will give us our answer will give us our answer as you can see this is a pretty decent as you can see this is a pretty decent solution and our time complexity is o of solution and our time complexity is o of n and our space complexity is also o of n and our space complexity is also o of n n if you found this video informative if you found this video informative please like and subscribe to the quant please like and subscribe to the quant bear | 2024-03-24 10:01:40 | 303 | LeetCode Patterns: LeetCode 303 Range Sum Query - Immutable | Python |
|
52m78U1QNsM | hey hey everybody this is Larry this is November 28th in New York anyway uh I'm November 28th in New York anyway uh I'm gonna do an extra problem just to give gonna do an extra problem just to give myself a little bit more of an exercise myself a little bit more of an exercise that I that I I think I didn't I think I didn't um I think I didn't click on to do so I um I think I didn't click on to do so I think I've done that one okay let's see think I've done that one okay let's see and hopefully not a premium question so and hopefully not a premium question so uh paid for premium if anyone wants to sponsor me for premium I have four more days to get that deal and then I'll do more problems not doing uh SQL here obviously again uh for good reason hopefully it makes sense um as you can see everything is very random because I am spending a lot of effort on randoming I don't think I've done all of them right so all the nine uh non-premium mediums but it's uh it's getting thin maybe I just need to I'm not doing more type for edit stuff uh because python is kind of weird I would say it's weird just I don't know all the constructs in Python mode diet floating um um taking a while here though a minute of just RNG and so far no good I might just go down the list at some point maybe it is just one of those uh situations these days maybe I've done all the non-premium ones pretty much uh except for these I mean I could see problems that they're just not RNG me right so I don't know okay fine let's do at least three more ing's and then we'll just go down the list maybe uh this is the beginning of the end until someone uh gives me oh there we go so that was actually the oh there we go so that was actually the last one anyway okay so today's problem last one anyway okay so today's problem is 874 working robot simulation a vote is 874 working robot simulation a vote button Infinity X5 Point starts at zero button Infinity X5 Point starts at zero zero facing north it could turn what a zero facing north it could turn what a weird thing oh I guess okay still weird thing oh I guess okay still awkward so you could turn that if you awkward so you could turn that if you could turn right uh move forward K and could turn right uh move forward K and then there can be obstacles weapons will then there can be obstacles weapons will stay okay stay okay so it seems like a simulation because so it seems like a simulation because you can only move K steps anyway so like you can only move K steps anyway so like there's no weirdness with respect to uh there's no weirdness with respect to uh whatever and then we just take the whatever and then we just take the maximum maximum uh every step uh every step um I don't think that yeah it should be um I don't think that yeah it should be okay right so um let's see right what okay right so um let's see right what are we doing so basically um what are we looking at North I guess it doesn't really matter it is facing north but everything's symmetric anyway right so basically we have the way that I like to set it up is maybe I've set up Direction so the north is going to be I mean this is up to you but I'm going to choose minus X um and then if we turn left as long as you're consistent it should be fine um actually they tell you this but whatever we can ignore it it doesn't really oh we don't we can because there are obstacles so we have to be very precise okay fine so North is going to be plus y fine so zero plus one um and then what I want to do is just rotate to the right so rotate to the right is going to be rest right or Yeast which which side is used in which side is West um okay okay I think it's West so West is negative X um and then South is you know obviously oops uh not leastly uh not leastly uh the yeast why is there one extra brand okay so then now we have current direction is you go to zero for North and then we have our current x y but and that's pretty much and then maybe uh max distance right um okay and then let's process the obstacles first into a set so we could look it up because I'm lazy um yeah so they just called ops as you go to set okay and then now we just have to okay and then now we just have to simulate simulate um yeah sorry guys so yeah so then now just for um I think there's rules so if C is um I think there's rules so if C is equal to negative two then we turn left equal to negative two then we turn left so current is equal to current plus so current is equal to current plus three mod four or something right three mod four or something right um and then if C is equal to negative um and then if C is equal to negative one then we move to the right uh and then else it'll be from there's no we don't have to um okay yeah I just wasn't sure if we have to validate that's all um and then yeah and then we just in [Music] range of uh C I suppose if it's one it does one okay fine yeah this D doesn't isn't necessarily have just confusing myself uh okay then yeah then we walk forward so NX and Y as you go to X Plus DX uh um that's why dxty as you go to directions of current uh X Plus DX y plus d y and the way the reason why I write it like this is so that we can check for the obstacles right so if obstacles there are Ops in my case oops obstacles there are Ops in my case oops um then we can break I mean we can kind um then we can break I mean we can kind of in theory we just do nothing and of in theory we just do nothing and continue but continue but in this command in this for loop it's in this command in this for loop it's just going to keep on running into it so just going to keep on running into it so we can break otherwise X Y is equal to we can break otherwise X Y is equal to NX and Y I think that's pretty much it NX and Y I think that's pretty much it um except for now we have to update the um except for now we have to update the the max distance so max distance is the max distance so max distance is equal to Max of Max distance x times X equal to Max of Max distance x times X Plus y times Y and I know that we have Plus y times Y and I know that we have the square rooted but the square rooted but oh I was going to say I actually didn't realize this but the reason why I like to keep it this way so that we could square wood later and we don't have to worry about floating point but apparently they wanted the square anyway so easier for us um let's kind of give it a spin I have the wrong answer so that's kind of sad uh what's good for this one good for maybe I'm not hitting the obstacles maybe I'm not hitting the obstacles correctly correctly that's probably why that's probably why um okay because it was going so it's saying it goes from zero zero to zero four turn right go four but it stops at two wait stops at one right so it starts at 1 4 goes to the right and okay um I mean the good point about this is we can print it out at the end of every frame so let's kind of see what what it's trying to do [Music] maybe my my set thing is weird that's awkward that's awkward so after the first move it goes to 2A so after the first move it goes to 2A did I mess up my directions oh so I could take this out we don't let's do that let's do that those cars are getting sloppy there but those cars are getting sloppy there but so silver one so silver one is X Y to begin with this should be zero is X Y to begin with this should be zero zero right hmm so 0 1 X Y is 2 4 to begin with why is so 0 1 X Y is 2 4 to begin with why is it two foot oh man I am being dumb it two foot oh man I am being dumb because I use X Y here because I use X Y here that is a very silly mistake okay fine that is a very silly mistake okay fine uh uh uh this is why you should not Shadow uh this is why you should not Shadow kids kids Shadow variables Shadow variables makes people sad okay I mean it may makes people sad okay I mean it may still get you one but at least still get you one but at least hopefully it'll be wrong for the right hopefully it'll be wrong for the right reason uh okay let's point it out again reason uh okay let's point it out again though because apparently I'm still well though because apparently I'm still well um okay so zero one today it goes to zero four okay turns right [Music] um did I do the science one turns right as negative one and right is rest right it is which which side is yeast which size breast they should tell you [Laughter] maybe I'm just being dumb uh huh did I mess it up maybe I just messed it up okay let's try it this way negative two is turned left right I mean I guess I just yeah okay because man which side is these let me I'm going to try Googling yeast is he still left away in East Village oh oh man I am I did confuse myself wow I confused which size you sandwich size West I'm just like looking up maps of yeast Village and I'm like oh yeah of course these were interested away wow it's just one of those days I guess um okay luckily this isn't a contest but that would be kind of sad of divorce but yeah um cool uh kind of a long video because of uh all the detours but um this is going to be linear time linear space uh yeah uh well it depends on what you mean by linear as well um the the space comes from the if you want to be more specific it's going to be of O we're always the size of the obstacles and and okay let me just write the time is uh space is going to be of oh well oh is the obstacles and in time of course it's going to be uh C plus o where C is commands right um and of course that's only execute 10 times you can maybe add an extra constraint on on um how many steps per command if you want to do that as a variable but you know yeah you can play around with that in terms of analysis but yeah that's what I have for this one let me know what you think um yeah that's it stay good stay healthy took a mental health I'll see y'all | 2024-03-22 17:21:10 | 874 | 874. Walking Robot Simulation (Leetcode Medium) |
|
itYouMQ0ZQM | hey everyone today we'll be doing another leaked code 205 isomorphic another leaked code 205 isomorphic strings and easy one strings and easy one given two strings essentially determine given two strings essentially determine if they are isomorphic if they are isomorphic two string s and t are isomorphic if the two string s and t are isomorphic if the character in s can be replaced to get t character in s can be replaced to get t all occurrences of a character must be all occurrences of a character must be replaced with another character while replaced with another character while preserving the order of the characters preserving the order of the characters no two characters may map to the same no two characters may map to the same characters a character so this is the characters a character so this is the key point here no two characters may key point here no two characters may have two same characters no two have two same characters no two characters we have to stream the same characters we have to stream the same character just keep in mind but our character just keep in mind but our character may map to itself with okay character may map to itself with okay so we are given by mapping the means you so we are given by mapping the means you are going to use a are going to use a hashmap hashmap dictionary hashtable you can say and so we'll be making two hash maps and what we will be doing is for the hashmap of let me explain like for egg and also we have add so we'll be making two hash maps for the hash map one which will be of for the hash map one which will be of the egg s the egg s this is this is the s string egg this is this is the s string egg so so egg itself will be holding the keys and egg itself will be holding the keys and add will be the values so what does it add will be the values so what does it mean the hash map will look like this g is holding d and g is again holding d this is it and now if we make another hash map which will be just for our second string the things will be opposite add will be the keys and egg will be the the character in egg will be the values so a will be holding e and d will be holding g and d will again hold g so this will return true because everything is fine everything in this whole situation is fine uh we are passing our base conditions like uh no two characters may have to send the same character and a character member will say the main problem is this no two characters they map to the same character this is just the same now it were if it was like this this would have been an error this is the same thing like this will return true like you can say in the example one but now if we see the example two if you understand what how how the if you understand what how how the things are working here you probably things are working here you probably guess why is this returning false so guess why is this returning false so we'll be making another map for we'll be making another map for i will just code it down i think you i will just code it down i think you guys know what is happening here is just guys know what is happening here is just o will be holding o will be holding a a and o will be holding r and p will be and o will be holding r and p will be holding f holding f a will be holding a will be holding it will be holding o r r r will be holding o so here we are r will be holding o so here we are failing the base condition like two failing the base condition like two characters may not map to the same characters may not map to the same character character like this like this so that's why it is returning false so that's why it is returning false so we have to check if the character is so we have to check if the character is present in our map and the value of that present in our map and the value of that character is equal to the value character is equal to the value of the character in the correspondence of the character in the correspondence you can say parallel you can just you can say parallel you can just parallel is more more understandable uh the parallel character so that's it now just make hash maps and do all the coding stuff so we'll be making a map one mapman will be mapped of s which will be the s string and a map2 making a dictionary for i in range of you can take one of for i in range of you can take one of these strings and put them in range these strings and put them in range their lengths basically because the their lengths basically because the length will be the same so now we have length will be the same so now we have to check to check if if but before checking we will make but before checking we will make some variables for our own understanding some variables for our own understanding a and b it will be a holding address oh a and b it will be a holding address oh the value at index s and b will be 40 the value at index s and b will be 40 so if a is present in our map one and so if a is present in our map one and also also map one at map one at a a shall not be equal to b shall not be equal to b so that basically we are just checking so that basically we are just checking that if a is in a map obviously if a is that if a is in a map obviously if a is in a map then obviously then we are in a map then obviously then we are going to check its value what it is and going to check its value what it is and if it is not equal to b then we shall if it is not equal to b then we shall just return just return false in that case because it should be false in that case because it should be equal to b equal to b so now we will do the same so now we will do the same for for map map second second and map and map two two for map to be for map to be and and just doing the same thing here just doing the same thing here so here so here is one after doing this we can just is one after doing this we can just return false because return false because we have found we have found a character a character which is two characters which are which is two characters which are mapping to the mapping to the same correct to the same characters so same correct to the same characters so just return just return false false false and if not we will just do this like swapping you can not swapping just like putting taking the value from a b and putting it back to the hashmap of one and taking the value from hashmap to and putting that uh one two yes to two obviously two two so map two will be b map to the index b shall be equal to a and if we are done with all of this and we didn't return false it means there are no you can say two characters that are mapping to the same character to the yes two characters mapping to the same character and that's it this is just fine i think this works | 2024-03-22 09:54:00 | 205 | 205. Isomorphic Strings | Leetcode | Python |
|
_ZOK7sPDVzs | hello everyone liquid product number 1684 1684 count the number of consistent strings count the number of consistent strings though problem statement though problem statement you are given a string allowed you are given a string allowed consisting of distant characters consisting of distant characters and an array of string words a string is and an array of string words a string is consistent if all characters foreign [Music] [Music] now faster than 64 of java online submissions thank you so much for | 2024-03-20 12:12:52 | 1,684 | 1684 Count the Number of Consistent Strings (Leetcode) | Easy Solution |
|
AYeV4_baiOc | hello and welcome to another one of my lead code videos in this one we'll do lead code videos in this one we'll do lead code 103 binary tree zigzag level lead code 103 binary tree zigzag level order traversal this is today's daily order traversal this is today's daily challenge so basically we're given the challenge so basically we're given the root of a binary tree and we need to root of a binary tree and we need to return the zigzag level order traversal return the zigzag level order traversal so that means that we go first from left so that means that we go first from left to right and then in the next level we to right and then in the next level we go from right to left and then the next go from right to left and then the next level we go from left to right and so on level we go from left to right and so on right so in this case 3 29 15 7. so we right so in this case 3 29 15 7. so we we have to return the output as a list we have to return the output as a list of list of list so what will be our approach to solve so what will be our approach to solve this problem basically we will just use this problem basically we will just use breadth first search because that's how breadth first search because that's how you do a level order traversal right so you do a level order traversal right so we'll first add three into our q and we'll first add three into our q and then look at what are the all of the then look at what are the all of the children of everything in the queue so children of everything in the queue so we'll get 9 and 20. and then we look at we'll get 9 and 20. and then we look at at the next level what are the children at the next level what are the children of everything in the queue so it will be of everything in the queue so it will be 15 and 7 and so on right but then as we 15 and 7 and so on right but then as we do that we'll have to keep track of the do that we'll have to keep track of the direction whether we're going left to direction whether we're going left to right or right to left and accordingly right or right to left and accordingly add things in the queue so that will be add things in the queue so that will be our overall approach let's just go ahead our overall approach let's just go ahead and code it and hopefully you'll see how and code it and hopefully you'll see how it looks like so we'll start off with it looks like so we'll start off with our list of list of integers which is our list of list of integers which is the result and that will initialize to a the result and that will initialize to a new arraylist and ultimately that's what new arraylist and ultimately that's what we'll return we'll return so there's our results list and then so there's our results list and then what we'll do is we'll initialize a what we'll do is we'll initialize a linked list of the current level and linked list of the current level and I'll use a linked list instead of a I'll use a linked list instead of a queue because queue because it'll make it a bit easier for us to it'll make it a bit easier for us to deal with the directions right so we'll deal with the directions right so we'll keep track of our current level as a new keep track of our current level as a new linked list and then we'll just do the linked list and then we'll just do the standard BFS template which is standard BFS template which is we keep looping while current level is we keep looping while current level is not empty right and inside that as well not empty right and inside that as well we'll have another loop that says while we'll have another loop that says while current level is not empty so we'll take current level is not empty so we'll take out everything from the current level out everything from the current level and add it to see if there's a Next and add it to see if there's a Next Level right and at the end we'll say Level right and at the end we'll say current level equals Next Level right so current level equals Next Level right so this will keep going until this will keep going until there are no more levels right so the there are no more levels right so the outer loop checks if if there are still outer loop checks if if there are still more levels and the inner loop checks if more levels and the inner loop checks if you know during the current level you know during the current level basically to compute the next level basically to compute the next level and obviously we need to initialize our and obviously we need to initialize our next level over here so let me just do next level over here so let me just do that real quick that real quick and so that's our next level and at the and so that's our next level and at the end we'll set current level equals Next end we'll set current level equals Next Level so that's our BFS template Level so that's our BFS template now let's go ahead and write the code now let's go ahead and write the code for this so initially we'll add for this so initially we'll add our current uh node which is three or our current uh node which is three or the root to the linked list right and the root to the linked list right and sorry this should not be a integer sorry this should not be a integer basically this will be a tree node so basically this will be a tree node so let me just let me just adjust all of those real quick and so adjust all of those real quick and so yeah initially we'll have the root as yeah initially we'll have the root as the current level and we also need a the current level and we also need a Boolean Boolean to know whether we're going left to to know whether we're going left to right for the next level or right to right for the next level or right to left right so we'll say is left to right left right so we'll say is left to right equals false initially because the root equals false initially because the root goes left to right so the next level has goes left to right so the next level has to go right to left to go right to left right and so now let's pull our current right and so now let's pull our current node from the tree node from the tree or sorry from the cube or sorry from the cube so we've captured our current node and so we've captured our current node and here we're just going to add you know here we're just going to add you know compute the things for the current level compute the things for the current level so if you notice the result is a list of so if you notice the result is a list of list of integers so at each level we'll list of integers so at each level we'll have to compute that list so I'm just have to compute that list so I'm just going to say going to say integing just a normal list of integers integing just a normal list of integers which is basically result for level which is basically result for level is a new array list right and at the end is a new array list right and at the end what we'll do is we'll say result dot what we'll do is we'll say result dot add result for level add result for level right so at every time we drain the right so at every time we drain the queue we'll compute this result for queue we'll compute this result for level and we'll add it to our overall level and we'll add it to our overall result result and here what we'll do is we'll just say and here what we'll do is we'll just say result for level dot add node result for level dot add node .vel right because whatever we pull from .vel right because whatever we pull from the current level we'll add it to the the current level we'll add it to the result result and we'll just make sure to put things and we'll just make sure to put things in the right order when we populate our in the right order when we populate our next level so that way next level so that way you know when the it goes through the you know when the it goes through the result for the next level it's already result for the next level it's already in order right so that we'll add that in order right so that we'll add that logic over here but there's just one logic over here but there's just one more structural thing we need to do is more structural thing we need to do is basically at the end of each loop after basically at the end of each loop after draining the current level we have to draining the current level we have to flip this flag right so we'll say flip this flag right so we'll say is left to right equal to not is left is left to right equal to not is left right so that will just flip the flag right so that will just flip the flag right so just to summarize the structure right so just to summarize the structure we have a queue for the current level we have a queue for the current level and here we're going through the BFS and here we're going through the BFS while there are still more levels and while there are still more levels and each time what we're draining the each time what we're draining the current level we're populating the current level we're populating the result and Computing Next Level which result and Computing Next Level which we'll do in a second and after draining we'll do in a second and after draining the current level we're flipping or left the current level we're flipping or left to right to right we're appending the result for the we're appending the result for the current level to the result current level to the result and we're setting curve level equals and we're setting curve level equals Next Level so it can check if there are Next Level so it can check if there are still more levels right and at the end still more levels right and at the end we return results so that's structurally we return results so that's structurally how the code looks like and so now what how the code looks like and so now what we just need to do is populate our next we just need to do is populate our next level based on the right order right so level based on the right order right so we will have two branches here right if we will have two branches here right if is left to right and if it's not left or is left to right and if it's not left or right right so if it is left to right right right so if it is left to right what we want to do is we're going from what we want to do is we're going from left left sorry let's populate the other Branch sorry let's populate the other Branch first so if we're not left to right first so if we're not left to right right that means the right that means the the nodes in the previous level are the nodes in the previous level are being taken out as in order from left to being taken out as in order from left to right right but then as within their children we but then as within their children we have to add them have to add them going from right to left and let's just going from right to left and let's just imagine that this level was processed imagine that this level was processed from left to right right so in the else from left to right right so in the else case what we want to do is when we pop case what we want to do is when we pop the children the children we want to add them to a list in reverse we want to add them to a list in reverse order right so we add the left at the order right so we add the left at the right at the left at the right but in right at the left at the right but in reverse order right so what we'll do is reverse order right so what we'll do is nextlevel dot add first nextlevel dot add first node.left node.left and the same thing for node.right and and the same thing for node.right and obviously we only do this if node.left obviously we only do this if node.left is not null right and sorry the next one is node.right so the next one is if node.write is not null then we'll add Next Level that add first node.right and so what add first is going to do is going to say okay every time we add a node make it the first so that way the list will be from the next list will be from left to right right and so then if is left to right is true meaning the next list has to go from from left to right what we'll do is that means the elements are being popped from right to left right so what we want to do is make them it from The Next Level from left to right so what we'll do is again we'll insert the right one first and then the left one and then we'll do the same ad first technique so it the list is basically appeared in reverse order and this is why we have to use a linked list because that will make sure that we're adding you know it will give us this capability to add first so that makes it easier to um to add things to the next level so that will basically do it let's run it all right there's just one base case we all right there's just one base case we need to take care of is basically if the need to take care of is basically if the root isn't also over here we'll also root isn't also over here we'll also just say if root is not null only then just say if root is not null only then we'll add the root to our current level we'll add the root to our current level and you know if there's nothing in the and you know if there's nothing in the current level it will just skip out of current level it will just skip out of this and return results so that check this and return results so that check should be enough over there should be enough over there all right accept it let's submit perfect 100 solution thanks so much for watching I'll see you in the next one | 2024-03-21 10:14:43 | 103 | Leetcode 103 Binary Tree Zigzag Level Order Traversal (Java) - Beats 100% |
|
wD7fs5P_MVo | if you're Jeff starting your journey towards Tech interviews trust me this towards Tech interviews trust me this problem is really really important at it problem is really really important at it is one of the facial is that it navigates beautifully how you start to understand the problem and then make your way all the way towards an efficient approach why is that true let us try to find it out Hello friends welcome back to my channel and yes I've got some cold but anyways first of all what we're gonna do is we will understand the problem statement and we will look at some sample test cases going forward we will try to solve this problem using a Brute Force approach then we will start optimizing it we'll optimize it for time and when we will optimize it for space ultimately you will also do a dry run of the code so that you understand how all of this actually works in action without further Ado let's get started [Music] first of all let's make sure that we are understanding the problem statement correctly in this problem you are given an array of integers and you have to find the majority element so what is the majority element a majority element is one that occurs more than n by two times where n is the total number of elements present in the array right so if an already have 10 elements then the majority element will be one that occurs more than 10 by 2 that is more than 5 times right to understand it better let us look at a sample test case in our first test is you can see that the value of n is 3 right because it has three elements so therefore n by 2 will be equal to 1.5 and thus you need to find the majority element that occurs two times or more than two times right so when you look at this array you can see that the element 3 occurs two times correct so for a test case number one three will be your answer 3 is the majority element correct similarly let us look at our second test case in our second test case once again what we do is you find the value of n that will be 7 so n by 2 will be 3.5 so you need to look for a majority element that occurs more than four times or just 4 right so when you look at this array you can see that the element 2 is occurring four times and hence 2 is the majority element so for a test case number two two will be your answer now for this problem it is guaranteed that the array will have a majority element there could be some other problem or some other scenarios where the array may or may not have a majority element but that depends upon the problem in this problem specifically there will be a majority element and that is guaranteed so now if you feel that you have understood the problem statement even better feel free to first try it out otherwise let us dive into the solution and see how you're gonna approach this problem as I said earlier this problem is interviews favorite because it helps the interview to judge how the candidate is thinking so when you're given this problem and you have said that okay now try to solve this problem what do you do first of all as a good developer you will always try to come up with a Brute Force solution because that can guarantee you if a solution to this problem even exists so what you're going to do is you say that okay I'll do one thing I'll say that okay how many times can I find the element one so you will travel through the array and you can say that okay one two you found the element one two times right and then you're gonna look for elements two you find the element to four times right and then at the last you're gonna look for element three how many times do you find the element you only find it one time right next you need to see it say that okay the size of the area so n by te will be equal to 3.5 and hence I need to find some majority element that occurs four or more times and voila you can find this over here right you can see that okay 2 is my majority element so you were able to arrive at a solution right and that's perfect but then the interview will say okay you are taking a lot of time and why is that so because to find out the frequency of each of this element you are traversing through the array again and again right first of all you Traverse the array for element one then you Traverse the alloy for element two and then you Traverse the array for element three so in this case your time complexity is very high your interviewer will say okay I need a better solution so what can you do about it and once again you have the same problem and you have a fresh sheet of paper in front of you and you are asked okay optimize the solution correct so when it comes to array-based problems and integers always try to sort your array because 14 can really help you to arrive at an answer and think about it for a second suppose you have this array in front of you right and you've tried to sort this array what will happen when you sort it all the similar elements will come together right so all the ones will get collected together all the tools will get collected together and all the threes will get collected together right and whatever will be the majority element in the array you know that the majority element is gonna occupy a size greater than half the size right so if your error size is 10 then there will be more than five elements that will be the majority element right if your array size is 20 then 10 of the elements will be the same right so what you can say is that once your array is sorted all the majority elements will lie somewhere in the array right it they could all lie in the beginning they could all lie at the very end they could all lie somewhere in the middle or they can lie somewhere else right anywhere in between but the major point that you have to notice is that the majority element it will always pass through the center of the array right and that is because the majority element occurs more than n by two times and you cannot have a combination where the majority element will not be at the center so this tells me right if I sort the array and if I look at the middle element that will be my majority element right so that is exactly what we do we take this array and then we sort it what happens then you get a faulted array right and the next step is simply look at the middle element of the array and this element will be the majority element so you can safely say that for this particular problem 2 will be a majority element and this is the reason because it is guaranteed that the majority element will pass through the center right so this should make your interviewer a little happy you did not iterate through the array again and again you just sorted it once and returned the middle element right but when it comes to sorting what is the best time complexity that you can have you can have a Time complexity of order n log n right that is the fastest one quick font unless there are special cases correct so your interview say that okay I'm still not satisfied I need an even better approach what can you do about it so you see why this problem is interesting it will keep on poking you again and again to come up with a better approach and now you'll think okay what can I do next so once again you would refresh your mind and you have the same problem and a blank sheet of paper the ideas are endless what can you do well you tried farting the array right but we did not try okay what if I can take a help of an additional data structure maybe that can help me with time so this is one approach what you can do is you can take a help of a hash table right so this hash table will store all the numbers in your keys column and all the frequencies in the value column so what we're going to do in this case is we will start iterating through the array from the beginning I see one number I see two so I put 2 in my hash table and I put its frequency as one now move ahead the next element I see is 2 again check your hash table two if already perfect right so if an element is present just increment its frequency correct now move on you see element one check your hash table this element does not exist so you will add this number and put its frequency as 1. similarly you will keep on going along you will see three three is not present over here so I am going to add 3 and put its frequency F1 next I get a one again one is present in the table so I will update its frequency now I get a 2 again check its frequency and update it the last element is 2 again check its frequency and ultimately update it now in just one iteration you were able to find out the frequency of each element right and you already know that the majority element will have a frequency of 4 or more correct so just scan through your hash table once and see that okay two will be your majority element you were able to optimize your code correct in just one scan you were able to determine the majority element correct but this time what did you do you took help of an additional data structure right and that means you took some extra space this is where your interview will catch you again and he will say okay I do not want you to use any extra space What do you do now so this is why I keep saying that this problem is really interesting and the last solution that I'm going to offer you will really blow your mind it is so simple and you will say that hey why didn't I think of it before so what do you do about it when it comes to majority what comes to your mind well you can say that voting comes to your mind right because based on number of votes a certain candidate can get elected right if there are a thousand people and the candidate gets more than 500 votes they are a majority and they form a government so we can try to apply the same voting algorithm on this problem as well so I have the same array with me and then I will try to determine who is the majority and how many votes they have so starting off with my first candidate someone comes and they vote for candidate too so what I can say is that okay right now two has a majority and they have one vote correct next one more person comes and they vote for two so what I'm saying gonna say is okay the number of votes for two increase by one so I do a plus one over here right now moving along a third person comes and they vote for one so to laugh double right so I'm gonna reduce this count but we do not update the majority element because it could still be possible that 2 might win again now move ahead the next person votes for three so two lost his vote again and if total number of votes again became zero so now you are in a dilemma okay who has the majority do you remember how in the beginning we chose two as a majority candidate so this time it could be possible that okay three could be a possible candidate right and three will have one vote right because he just got the vote now move ahead a next candidate came in again and they voted for one so once again three lost a vote their votes became zero and it could be possible that one is a new candidate right he got one vote correct based on a similar idea just go ahead one more candidate comes and they vote for two again so check the vote this vote reduces to zero and now no one have a majority again let us say that 2 will be the majority so I'm gonna choose 2 as a majority element and their vote counts get updated to 1. move ahead for one last time and you feed two again so what does that mean the number of votes of 2 increased by one and we have reached the very end everyone has casted their votes correct and what do you see over here you see that 2 is the majority element in the array correct so you see how in just one iteration we did not take any extra space and we were able to determine the majority element in the array now let us quickly do a drawing of the code and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right I have this sample array that is passed in as an input parameter to the function majority element oh and by the way this complete code and its test cases are also available in my GitHub profile you can find the link in the description below moving ahead with a dry iron what is the first thing that we do first of all we choose a majority element and we say that okay let the first element be the majority element and I give them one vote right now as the next step what we'll do is we will start a for Loop that will start from the first element and go all the way up to the end right so we will get the vote of each person correct so now in this Loop what do we do if the vote counts becomes 0 at any point we update our majority element and we increase the vote count back to 1 right and if our current number equals the majority element we will increase the number of votes else what we do if someone casted a vote for the other person we decrease their vote count right so this this and at the very end whatever will be the majority value that will be your majority element in the array right note that this part of the code is doing exactly what I just explained you a few seconds ago right so the time complexity of this solution is order of n because we iterate through the array only once and the space complexity of the solution is order of 1 because we do not take any extra space to arrive at a solution I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that I know this problem is not very difficult and after some iterations you will be able to arrive at an efficient solution and even if you practice on lead code you will ultimately get an accepted Foundation but the interesting part and the Beautiful part about this problem is there are so many ways to solve it and I would highly recommend you to go on and explore all of them because that will segue and open a gateway to you to attack more problems and it will show you ways how you can look at new problems so when you are approaching such problems try to come up with new Solutions try to optimize for time as much as you can try to optimize for your space as much as you can because these problems are not very complex they are very simple right so it kind of helps you to widen your brain and your thinking power so always watch out what other problems did you find that can be solved in a so many number of ways while going through this video did you face any problems tell me everything in the comments section below and I would love to discuss all of them with you you would be also glad to know that a text-based explanation risk problem is available on the website study algorithms.com a pretty handy website for your programming needs as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what problems do you want me to follow | 2024-03-21 14:01:22 | 169 | Majority Element (LeetCode 169) | Full solution with 4 different methods | Interview Essential |
|
cGAXF_ZumCk | hello friends today we gonne discuss this question founded code one 2:07 this question founded code one 2:07 unique number of occurrences this is an unique number of occurrences this is an easy question instead start you're given easy question instead start you're given an array of integers ARR I have to write an array of integers ARR I have to write a function that returns true if and only a function that returns true if and only if the number of occurrence of each if the number of occurrence of each value in the array is unique it means value in the array is unique it means that as you can see in this example one that as you can see in this example one occur three times two occurs two times occur three times two occurs two times and three occurs one time the occurrence and three occurs one time the occurrence of each number is dooty then only after of each number is dooty then only after return true okay so what we can't do return true okay so what we can't do this as you can see this is the original this as you can see this is the original edit I written out all the numbers and edit I written out all the numbers and it's occurrences so what we can do it we it's occurrences so what we can do it we make a map I make a map M in which each make a map I make a map M in which each number corresponding corresponds to its number corresponding corresponds to its occurrence then I also made a map called occurrence then I also made a map called B and then in that I check whether each B and then in that I check whether each occurrence is unique or not not a simple occurrence is unique or not not a simple logic would face it so what what we have logic would face it so what what we have done here is you have to first make the done here is you have to first make the first map to store the values and since then if we find any take any value in the array we just store it in the map of M as you can see in here then I and make another map to check if each element has so what we can do is we just iterate so what we can do is we just iterate over the the stored values in the map m over the the stored values in the map m and check whether each value is like and check whether each value is like unique or not how you can check it if unique or not how you can check it if you just in count one value encounter you just in count one value encounter when value like if we encounter one in when value like if we encounter one in the map one we just if you have not seen the map one we just if you have not seen it then we just put it in the map and if it then we just put it in the map and if you have see it returns false and if you have see it returns false and if each value is unique we just did we just each value is unique we just did we just put all values in this map and we just I put all values in this map and we just I come out of this tube and you turn come out of this tube and you turn through I hope you understand this logic through I hope you understand this logic if you have any problem mention all in if you have any problem mention all in the comment box I applied to all the the comment box I applied to all the comments thank you for watching this comments thank you for watching this video and I will see the next week thank video and I will see the next week thank you | 2024-03-18 11:13:34 | 1,207 | 1207. Unique Number of Occurrences || leetcode || easy problem|| c++ solution with explanation |
|
fNVs1J2KCyo | Hai Hello Guys Welcome Back There Devotion In This Video Will See The Vote Back To Problem Video Will See The Vote Back To Problem Swiss Roll Absolutely Number One 409 The Swiss Roll Absolutely Number One 409 The Requested For Watching This Problem Is To Requested For Watching This Problem Is To Watch Videos One Is The Problem And Watch Videos One Is The Problem And Explain The Cockroach Explain The Cockroach Video Solving Problems Video Solving Problems Unit-2 Such Remedy Unit-2 Such Remedy Try Try Try Problem Problem Subscribe Very Well Written All Possible Subscribe Very Well Written All Possible Sentences In The Sentences In The Budding Dictionary Also Reduce Multiple Budding Dictionary Also Reduce Multiple Times In The Segmentation So Let's Fuel And Times In The Segmentation So Let's Fuel And Inverter Virver Dictionary Request To Efforts And Efforts And Different Words Will Be In Between subscribe to The Dictionary Dictionary Dictionary valid tense which is Dictionary Dictionary Dictionary valid tense which is formed by segmentation of this interest in no way can form no The sentence as well as a partition in between December and sentence with sentence with multiple times in this is not needed to multiple times in this is not needed to This problem was already discussed in the This problem was already discussed in the This problem was already discussed in the video problem only partition and the given dictionary dictionary will give you want to you want to live in live in are you can make the partition and any are you can make the partition and any point but between any two characters you can point but between any two characters you can create partition here and will see the create partition here and will see the first word you first word you and and and only person 9999999999 this is the thanks partition so let's create partition in between 10 first words not present at the and again is not valid and again is not valid and subscribe to that In this pain is considered it is not a In this pain is considered it is not a In this pain is considered it is not a petition in the present in the world against partition in between their goals painting painting competition subscribe The Channel subscribe subscribe the the Video then Video then subscribe to the Page if you subscribe to the Page if you liked The Video then liked The Video then subscribe to the Page subscribe to the Page if you The Video The Video झाल झाल झाल Partition Display in Detail A Video Endeavor's Return to the World Need Not Arrested in Rape Cases Problem Subscribe Now Your Data Structure for Watching the Validity of Its Data Structure for Watching the Validity of Its Present in the They are They are They are always Sentence Cats and Dogs Dog Show is from Lab Cat and Dog Saunf How to Make Diwali Petition Knowledge is Deficit Between There are a few NCERTs are not valid for subscribe and subscribe Please Noida And Deposit Will Never Create Partition On The Left Side And Was The First Politician From Left To Right The Indian Indian Partition In Between When You Can Create Partition In Between When You Can Create Partition Partition subscribe The Channel and subscribe the subscribe The Channel and subscribe the Video then subscribe to the The Video subscribe to the Page and no I will recover back to 10 condition dedicated to partition between India and I can create any modifications to the right of every true Indian homes and did not valid word against York between you The The The Chapter Note Send Your Dog Chapter Note Send Your Dog Is Not A Is Not A Valid subscribe Valid subscribe to liked The Video liked The Video then the Page China's Cats And Will Go Tow Schedule See The World And Value Must Be Greater Than Soon Like This Like Share and Subscribe Middle-aged Called a Friend on Thursday I'll Keep Adding Spaces Whenever a Big Question Call No Verification Call Divert Raees Ahmed Partition Avoid and You You and Your Subscribe Subscribe Sentences Sentences and -20 Values Where I Have Intervention Z World And Indicators Effective Video give 12345 [ 12345 [ Music] Music] Withdrawal dictionary.com A Soap Is You Already Know How To Implement Destroy Evidence Was My And usage examples for we will And usage examples for we will And usage examples for we will not be spared them know what is the time not be spared them know what is the time complexity building destroy what is complexity building destroy what is the the order of total number of characters in the order of total number of characters in the total number of the total number of the characters total number of the total number of the characters of of wave the great wave the great indian laughter indian laughter number to the length of number to the length of the So in the worst case How Many Politicians Can You Read This Book So in the worst case How Many Politicians Can You Read This Book Example Like Share And Example Like Share And That Dictionary Apps That Dictionary Apps 1114 1114 subscribe The subscribe The Amazing 1000's Not Only Single Single Again A Sensitive A Sensitive Were Is Answer Is The Length Of Resident Evil Bhind Saunf Bal Se Dam Minus One Capsule Bhind Saunf Bal Se Dam Minus One Capsule Partition Points Partition Point Will Have Two Partition Points Partition Point Will Have Two Choices But To Enter And To Not Choices But To Enter And To Not Include Total Include Total Number Of Items Which Can Be Made To Number Of Items Which Can Be Made To Minus One To Three Do Subscribe Subscribe Due to which Partition subscribe subscribe The Channel and The Channel and subscribe the Channel Please subscribe and subscribe the Channel Tomorrow Morning Tried All Possible Combinations with the 251 Total Time Complexity of the Total Time Complexity of the World Channel World Channel Subscribe My Video Subscribe Subscribe Subscribe must subscribe here all the same will eliminate them in this program will only two functions special no problem give the validity subscribe channel subscribe channel subscribe subscribe and subscribe the ke din hai bill record se 10 years function to solvent and 10 years function to solvent and 10 years function to solvent and avoid the rate of the ring starting from withdraw from plus one will be sending this world and and and share thank you thank you for for watching my video and once watching my video and once you get all the politicians and your to the position of to the position of to the position of Position Chest Size Dekh Chali You Have Petition That You Are Madea Valid Politicians Know Your Success Fully Segmented This Entering Into A Writ Petition Restored And Also In The Answer The Answer Is The Answer Is Very Mostly In The Sentence Will Be Understand this video Understand this video please like | 2024-03-21 12:26:59 | 140 | Word Break 2 | Leetcode #140 |
|
_taehsxPeGo | Question No. 1757 Recyclable and Low Fat Products: A 1757 Recyclable and Low Fat Products: A simple table of a product is given and simple table of a product is given and inside it it is said that it should be low fat, it should also be inside it it is said that it should be low fat, it should also be recycled, so inside the recycled, so inside the table of this product table of this product it is simply said Fat should also be yes Fat should also be yes Fat should also be yes and recycled power should also be yes, which is and recycled power should also be yes, which is no here, it means here wa is yes no here, it means here wa is yes and this yes then this cry will come, and this yes then this cry will come, after that no y this will not come and this after that no y this will not come and this two this cry will come then the wava wali cry will come. two this cry will come then the wava wali cry will come. Which of these two has come? One has come and this one has come. Which of these two has come? One has come and this one has come. Simply select star from Simply select star from select name from table where select name from table where this one is yes and this one this one look from name name this one is yes and this one this one look from name name product name fat and cable name. product name fat and cable name. | 2024-03-22 12:07:25 | 1,757 | 1757. Recyclable and Low Fat Products | LeetCode | Hindi | Top 50 sql interview questions |
|
0Zix7iuuxAo | yo what is up youtubers today i'm going to be going over rotate image i'm going to be going over rotate image it's a medium leak code problem has to it's a medium leak code problem has to do with arrays it's been asked by do with arrays it's been asked by microsoft microsoft apple and amazon please check out my apple and amazon please check out my channel and subscribe if you haven't channel and subscribe if you haven't already i post videos basically every already i post videos basically every day about recode day about recode so now let's get to it it teaches you a so now let's get to it it teaches you a lot about lot about how to manipulate arrays so it's really how to manipulate arrays so it's really i think it's really important to know i think it's really important to know this problem this problem um i could see it being asked an um i could see it being asked an interview question i've i've heard it interview question i've i've heard it it's been asked before so let's jump it's been asked before so let's jump right into it you're given an n by n right into it you're given an n by n 2d matrix so that means the the rows and 2d matrix so that means the the rows and the columns are going to be equal the columns are going to be equal um that makes it a lot easier it could um that makes it a lot easier it could be m-by-n where they're different be m-by-n where they're different which is actually another problem that i which is actually another problem that i will get to in the future will get to in the future so we just need to rotate the image by so we just need to rotate the image by 90 degrees clockwise so they just want 90 degrees clockwise so they just want us to basically us to basically pick it up and rotate it so one two pick it up and rotate it so one two three will be on the right three will be on the right and um the and um the the column the first column will be on the column the first column will be on top so it's like top so it's like just imagine picking it up and switching just imagine picking it up and switching it right here as you can see right here it right here as you can see right here um and so yeah they're end by end so um and so yeah they're end by end so there's four here there's four here four columns four rows three columns four columns four rows three columns three rows it's always going to be the three rows it's always going to be the same so that makes it easier i actually same so that makes it easier i actually have all the code written i need to have all the code written i need to clear that and so the logic behind this this is a great one to whiteboard i drew it out the logic here you don't actually want to like there's you don't actually want to like there's not an easy way to not an easy way to as far as i'm aware to just like you as far as i'm aware to just like you can't really just like pick it up and can't really just like pick it up and turn it turn it you have to turn them oh and the other you have to turn them oh and the other thing is we have to thing is we have to rotate the image in place so they want rotate the image in place so they want us to us to not create another array we have to not create another array we have to change it inside the array so that means change it inside the array so that means we're going to have to use we're going to have to use temp variables to keep temp variables to keep reference of previous variables that reference of previous variables that we're going to change it's similar to we're going to change it's similar to like swapping when we swap two variables like swapping when we swap two variables we're gonna have to basically do that we're gonna have to basically do that um so the one thing to um so the one thing to notice is that um notice is that um the the row is down here so if we the the row is down here so if we first transpose it i think this is first transpose it i think this is probably the hardest part the logic probably the hardest part the logic to realize is if you transpose it which to realize is if you transpose it which means means if you switch the so if you transpose it if you switch the so if you transpose it you're basically taking you're basically taking um you're basically rotating it to the um you're basically rotating it to the left left um so this this row um so this this row becomes this column um becomes this column um you're just swapping the rows and the you're just swapping the rows and the columns and you're going through the columns and you're going through the whole thing whole thing so you see uh as you can see this so you see uh as you can see this the last column becomes the last row the last column becomes the last row that's transposed that's transposed now how close is this to now how close is this to um this well if you look here we have um this well if you look here we have oh sorry it's my video is in the way oh sorry it's my video is in the way there you we have 147 on top if we there you we have 147 on top if we transpose it transpose it now if we reverse it now if we reverse it 741 it it matches it's just the 741 it it matches it's just the transpose transpose is reversed of the um is reversed of the um the rotated matrix basically so we need the rotated matrix basically so we need to to transpose it and then reverse it transpose it and then reverse it so now we just need to write code to do so now we just need to write code to do that that so let's go ahead and jump right into it so let's go ahead and jump right into it um i'm going to create a temp variable um i'm going to create a temp variable and uh i'll do and uh i'll do no i'll name it and so into end this no i'll name it and so into end this we're going to grab the length so we're going to grab the length so matrix dot length um matrix dot length um so because it's m by n we can just do so because it's m by n we can just do matrix that length because they're going matrix that length because they're going to be the same if we needed to be the same if we needed m by n we would have to do n is matrix m by n we would have to do n is matrix that length that length m is matrix.length zero m is matrix.length zero it would be like the zero how you grab it would be like the zero how you grab it for a it for a 2d matrix 0 and then blank um 2d matrix 0 and then blank um so yeah so and then we just need to so yeah so and then we just need to transpose it i've done a video on this transpose it i've done a video on this before before so we're going to do a net 2 nested for so we're going to do a net 2 nested for a nested for loop i guess so for a nested for loop i guess so for instance i instance i equals zero whoops i less than equals zero whoops i less than n we're gonna loop through all the rows n we're gonna loop through all the rows i plus plus and then we're gonna do j same thing um actually so we're i believe it's j equals i uh we have to once we let me show you on uh we have to once we let me show you on the board the board once we swap this row um we're going to once we swap this row um we're going to so we swap this one i is one here once so we swap this one i is one here once we get to i equal we get to i equal or i equals zero i'm sorry because it's or i equals zero i'm sorry because it's zeroth index once we get to i equals one zeroth index once we get to i equals one we are only swapping these two we're no we are only swapping these two we're no longer doing the four the four's already longer doing the four the four's already been swapped been swapped so um j is going to be equal to i we so um j is going to be equal to i we don't need to do j equals zero we've don't need to do j equals zero we've already done that already done that in when i is one so that's why we're in when i is one so that's why we're doing that doing that hopefully that that makes sense um hopefully that that makes sense um that's a little bit harder concept to that's a little bit harder concept to pick up but you just gotta pick up but you just gotta think about it logically draw it out think about it logically draw it out picture it in your head picture it in your head however you need to figure out how to do however you need to figure out how to do that so temp is that so temp is let's set i'm sure you guys have swapped let's set i'm sure you guys have swapped variables before so let's set variables before so let's set um temp equal to you could do either i um temp equal to you could do either i j or j i it doesn't matter what order j or j i it doesn't matter what order you do it but when you're swapping you do it but when you're swapping variables variables you do so now we're going to change you do so now we're going to change we're storing matrix we're storing matrix i j and temp so now we can change i j and temp so now we can change matrix i j we can update it when we're matrix i j we can update it when we're transposing it transposing it and we still have the original value in and we still have the original value in temp temp so just remember it goes in so just remember it goes in order so i'll show you what i mean by order so i'll show you what i mean by that so we're setting it equal to matrix that so we're setting it equal to matrix ji we're just swapping the rows and ji we're just swapping the rows and columns columns and then matrix j i we still have that and then matrix j i we still have that original value original value or yeah it's still the original value so or yeah it's still the original value so we need to update it to temp we need to update it to temp so what i mean by is they go in order is so what i mean by is they go in order is first you first you um store matrix age i intend and then um store matrix age i intend and then you change matrix you change matrix i j to make j i and then i j to make j i and then matrix you update matrix j i so it's matrix you update matrix j i so it's like i j like i j i j j i j i that's what i was trying to i j j i j i that's what i was trying to explain that's how i think about it explain that's how i think about it and um oh i'm still in the for loop and um oh i'm still in the for loop so that was transpose and so obviously that's oven squared it's two for loops it's pretty simple okay so now we just need to um reverse the rows so um let me reverse rows so how we're going to do this is um the biggest thing we're going to take basically two pointers we just need to swap this one with this one um so we're gonna swap i which is we're gonna swap i j this is i j with um how do we get to the last one well you take the length which is so n equals three this is the second index so you would think well three minus one yeah that works for this scenario but imagine we had one two three four five this is the fourth index third index zero one two yeah that works for um the last index only we need to um so if n is five we third well in this case we're still swapping it with this one so we get n so we get n minus 1 minus j so 5 minus 1 minus 1 minus j so 5 minus 1 minus 1 equals 3 which is minus 1 equals 3 which is the index we want to swap so it's just n the index we want to swap so it's just n minus 1 minus j minus 1 minus j hopefully that makes sense i don't know hopefully that makes sense i don't know how else to explain that how else to explain that um so yeah let's code it out um so yeah let's code it out i equals zero i less than n i equals zero i less than n i plus plus and so i plus plus and so if you see here we're only if you see here we're only i'm gonna draw i did a lot of drawing up i'm gonna draw i did a lot of drawing up here so i'm gonna do it on this one here so i'm gonna do it on this one we're only swapping this in this we're we're only swapping this in this we're doing doing one swap um per row so we're in a row one swap um per row so we're in a row we're doing one swap how do we do that we're doing one swap how do we do that we do we do so j while j is less than n divided by so j while j is less than n divided by two two n equals three so j n equals three so j less than 3 divided by 2 equals 1.5 less than 3 divided by 2 equals 1.5 as you know in coding it rounds down as you know in coding it rounds down so it's going to be while j is less than so it's going to be while j is less than one we're only doing one swap so it's one we're only doing one swap so it's only going to execute once only going to execute once so that is going to be for our second so that is going to be for our second for loop equals zero and j less than n divided by two and j plus plus okay so now we just need to swap them let's store it in temp so matrix equals matrix i and j matrix i the j equals so now we need to we're not um we're staying in the same row so it's still i uh you don't want to swap it with uh the other column so it's a little bit different so now we do n minus 1 minus j like i just said and then you do matrix i we're just n minus 1 minus j equals 10 n minus 1 minus j equals 10 and there you have it this is a void um and there you have it this is a void um function function so we don't need to return anything this so we don't need to return anything this should should work yup it works work yup it works as fast as too hundred percent five as fast as too hundred percent five percent percent uh memory usage so it's o of one we did uh memory usage so it's o of one we did it in the description it in the description it's in play in place we're not creating it's in play in place we're not creating a new matrix so it's over and space a new matrix so it's over and space complexity complexity o of n squared um running o of n squared um running time complexity it's just two time complexity it's just two and two nested for loops so i mean and two nested for loops so i mean there's two separate ones so there's two separate ones so technically it's two n squared but we technically it's two n squared but we just simplify it to just simplify it to n squared and there you have it please n squared and there you have it please like this video if you haven't already like this video if you haven't already it really helps with the youtube it really helps with the youtube algorithm algorithm and subscribe and i'll see you guys in and subscribe and i'll see you guys in the next video tomorrow | 2024-03-20 09:45:41 | 48 | LeetCode 48 | Rotate Image | Solution Explained (Java + Whiteboard) |
|
GfRQvf7MB3k | all right so today we are going to look at how we sort or merge two sorted lists at how we sort or merge two sorted lists now Alyss is an abstraction I can have a now Alyss is an abstraction I can have a linked list I could have an array so the linked list I could have an array so the question on lis code is with linked question on lis code is with linked lists or walkthrough will be with a lists or walkthrough will be with a linked list so I can show you how it's linked list so I can show you how it's done and how we can like avoid some work done and how we can like avoid some work at the end you'll see what I mean in at the end you'll see what I mean in like a little case where we exhaust one like a little case where we exhaust one list but so the question is given two list but so the question is given two sorted lists this is very similar to my sorted lists this is very similar to my video talking about merging K sorted video talking about merging K sorted lists this is actually a smaller video lists this is actually a smaller video in scope because this is the fundamental in scope because this is the fundamental that I built off in that video merging that I built off in that video merging two sorted lists this is very important two sorted lists this is very important for algorithms like merge sort I have a for algorithms like merge sort I have a video on merge sort for algorithms like video on merge sort for algorithms like merge sort we need to know how to merge merge sort we need to know how to merge two sorted lists because what we do is two sorted lists because what we do is we drill down to base cases and those we drill down to base cases and those base cases push us back upwards and we base cases push us back upwards and we have sorted lists as we go back upwards have sorted lists as we go back upwards and medium merge those after doing the and medium merge those after doing the split steps for this problem two sorted split steps for this problem two sorted lists we have a sorted list how do we do lists we have a sorted list how do we do this let's look at how we do this so this let's look at how we do this so we're gonna do this with a linked list we're gonna do this with a linked list so the thing is length las' problems are so the thing is length las' problems are pretty tricky when I first started pretty tricky when I first started learning them I was horrible at like learning them I was horrible at like pointer manipulation and moving those pointer manipulation and moving those pointers around to solve problems linked pointers around to solve problems linked those problems can become very easy with those problems can become very easy with practice and just like knowing the practice and just like knowing the methods that we do to work with these methods that we do to work with these nodes so what we're gonna do for this nodes so what we're gonna do for this problem is we're going to put a pointer problem is we're going to put a pointer at the beginning of each of these lists at the beginning of each of these lists and we're going to use a dummy head to and we're going to use a dummy head to builds this new list so this is what the builds this new list so this is what the setup looks like all right so we have setup looks like all right so we have pointers on each of our first nodes we pointers on each of our first nodes we have a dummy head I really like using have a dummy head I really like using dummy head nodes for limitless problems dummy head nodes for limitless problems why because we do not need to worry why because we do not need to worry about having an empty state on the dummy about having an empty state on the dummy head when we're building our new list if head when we're building our new list if I put a pointer cur on this head which I put a pointer cur on this head which is what we're going to do actually let is what we're going to do actually let me rename things so it's a little more me rename things so it's a little more clear so what I'm going to do is I'm clear so what I'm going to do is I'm going to build my list off of curve if I going to build my list off of curve if I didn't have a dummy head what if cur is didn't have a dummy head what if cur is know what occur has nothing I can't just know what occur has nothing I can't just say cur Tom next because what if the say cur Tom next because what if the actual actual her is not a dummy head node gets rid of her is not a dummy head node gets rid of this problem by when we points occur I this problem by when we points occur I know it's gonna have a value it's just know it's gonna have a value it's just going to be my dummy head I keep saying going to be my dummy head I keep saying dummy head this is kind of annoying so I dummy head this is kind of annoying so I point list 1 points are here L 2 points point list 1 points are here L 2 points are there we are going to advance those are there we are going to advance those pointers as we eat up the parts of the pointers as we eat up the parts of the list and we choose items so we perform list and we choose items so we perform our first comparison we want the lesser our first comparison we want the lesser item the lesser item gets the placement item the lesser item gets the placement if they're equal we can take it from if they're equal we can take it from both list one or list two negative one both list one or list two negative one versus one the smaller item is going to versus one the smaller item is going to be negative one negative one gets the be negative one negative one gets the placement so this is what happens so placement so this is what happens so what just happened I appended the what just happened I appended the negative one node to the dummy head so negative one node to the dummy head so now this is the first node in our list now this is the first node in our list and it's the last node in our list and and it's the last node in our list and what I did was I moved her to this node what I did was I moved her to this node so cur is always going to be pointing at so cur is always going to be pointing at the tail of the list we are building the the tail of the list we are building the tail of the sorted list we are building tail of the sorted list we are building and I advanced L 2 and now L 2 points and I advanced L 2 and now L 2 points here and now we can continue our here and now we can continue our comparisons between l1 and l2 and comparisons between l1 and l2 and advance and just stay with me advance and just stay with me it becomes very straightforward the it becomes very straightforward the thing about these length list problems thing about these length list problems is they're often done in M plus n time is they're often done in M plus n time or linear time and we use constant space or linear time and we use constant space because it's just about rewiring it's because it's just about rewiring it's literally like reelect wrists we're just literally like reelect wrists we're just rewiring stuff so what we do is 1 versus rewiring stuff so what we do is 1 versus 2 one gets the placement because it is 2 one gets the placement because it is less so turn X we point it to list 1 and less so turn X we point it to list 1 and we advance list 1 and of course we we advance list 1 and of course we advance occur to the tail of the sorted advance occur to the tail of the sorted list cur always points to the tail of list cur always points to the tail of the sorted list the sorted list and so as you can see we rewired the and so as you can see we rewired the node kurwa sitting at 2 now points to node kurwa sitting at 2 now points to this node and now cur hops itself to this node and now cur hops itself to what it just pointed itself to because what it just pointed itself to because current needs to stay at the end of the current needs to stay at the end of the sorted list so list 1 is sitting here sorted list so list 1 is sitting here list 2 is sitting here those are list 2 is sitting here those are pointers they're pointing into the lists pointers they're pointing into the lists so 2 versus 3 2 gets the placement let's so 2 versus 3 2 gets the placement let's do our rewiring we advance list 2 do our rewiring we advance list 2 because we just add up to one of its because we just add up to one of its nodes we point this node that cur is nodes we point this node that cur is pointing to to this node I Bakr hops on pointing to to this node I Bakr hops on to the node is pointed to and now to the node is pointed to and now Kearney's who stay at details and list Kearney's who stay at details and list always always that's what happens and so now do you that's what happens and so now do you notice how as we're going through this notice how as we're going through this we're slowly building up a sorted list we're slowly building up a sorted list we start at negative one we go to one we we start at negative one we go to one we go to two so you see it slowly we're go to two so you see it slowly we're eating up these lists through these eating up these lists through these comparisons and we're building a sorted comparisons and we're building a sorted list so now what we do is compare list list so now what we do is compare list one and list two again cur is sitting at one and list two again cur is sitting at the tail of the sorted list this is the the tail of the sorted list this is the sorted list this is the stuff we still sorted list this is the stuff we still are working on so now three and three are working on so now three and three hoomans so we can take it from either hoomans so we can take it from either the list let's just take it from the the list let's just take it from the list one so what we do is list one hops list one so what we do is list one hops here we rewire the node that Curtis here we rewire the node that Curtis sitting on two points to the node that sitting on two points to the node that just one and now kurz got a point to the just one and now kurz got a point to the tail which is this node that is about tail which is this node that is about 2.2 and again Curt always sits at the 2.2 and again Curt always sits at the tail of the sorted list do you see how tail of the sorted list do you see how we're building a sorted list and now we we're building a sorted list and now we continue our comparisons unprocessed continue our comparisons unprocessed territory processed territory territory processed territory unprocessed so now comparison three gets unprocessed so now comparison three gets the placement the reverse is five three the placement the reverse is five three is the winner is the winner so now curve points over here this arrow so now curve points over here this arrow gets erased curve points over here and gets erased curve points over here and then cur hops onto what I just pointed then cur hops onto what I just pointed to and L to needs to advance because we to and L to needs to advance because we just ate one of its nose and so now what just ate one of its nose and so now what we do is we look at l1 and l2 who is the we do is we look at l1 and l2 who is the winner the winner is altitude how to winner the winner is altitude how to gets the placement we point cur to where gets the placement we point cur to where l2 was and we move cur to the tail of l2 was and we move cur to the tail of the list for building which is the note the list for building which is the note that it is about 2.2 all right so now that it is about 2.2 all right so now you see we're slowly building a sorted you see we're slowly building a sorted list and notice wait I've exhausted l2 list and notice wait I've exhausted l2 so if I've exhausted l2 what conclusion so if I've exhausted l2 what conclusion can I make I can make the conclusion can I make I can make the conclusion that everything from l1 and beyond is that everything from l1 and beyond is going to be greater than the last going to be greater than the last element in this list it's going to be element in this list it's going to be greater than or equal to the last greater than or equal to the last element in this list so I could still element in this list so I could still have a four there and I'd still tack have a four there and I'd still tack this on so what we do is this is a this on so what we do is this is a linked list so all we need to do is I linked list so all we need to do is I arrange this pointer I point to l1 I arrange this pointer I point to l1 I points to where l1 is pointing because points to where l1 is pointing because we made the conclusion all these nodes we made the conclusion all these nodes must be greater and as you can see they must be greater and as you can see they are going to be greater than the are going to be greater than the element which is for we can make that element which is for we can make that 504 it still be greater than or equal to 504 it still be greater than or equal to it it so what I do is I point this note to l1 so what I do is I point this note to l1 and then I am finished because I have and then I am finished because I have exhausted the second list and I know exhausted the second list and I know that the first list is all going to be that the first list is all going to be in the right place and so this is how in the right place and so this is how our algorithm works and this is our our algorithm works and this is our final linked list so let's write it out final linked list so let's write it out so at the end of our function all we do so at the end of our function all we do is hey we have a reference to the dummy is hey we have a reference to the dummy head point the dummy hat next return the head point the dummy hat next return the value of dummy head next return the value of dummy head next return the pointer to this note when we have the pointer to this note when we have the pointer to this node then bang we have pointer to this node then bang we have our whole list negative 1 1 2 3 3 4 5 10 our whole list negative 1 1 2 3 3 4 5 10 15 and this is how you merge a sorted 15 and this is how you merge a sorted list so this is just how we would do it list so this is just how we would do it with an array although with linked list with an array although with linked list is kind of easier because I can just do is kind of easier because I can just do that pointer I could just adjust that that pointer I could just adjust that pointer and then bang I have the first pointer and then bang I have the first list in place first list is finished and list in place first list is finished and we know it's going to be greater than we know it's going to be greater than this last item that is how you merge two this last item that is how you merge two sorted lists so now let's look at time sorted lists so now let's look at time complexity we always declare our complexity we always declare our variables when we're doing Big O so M is variables when we're doing Big O so M is the length of the first list and is the the length of the first list and is the length of the second list you can swap length of the second list you can swap those I don't know why I put it in this those I don't know why I put it in this order I shouldn't mean anything Swan order I shouldn't mean anything Swan anyway but M comes before and in anyway but M comes before and in alphabetical order but we use n more alphabetical order but we use n more often so I would assume that guess often so I would assume that guess precedence so the time complexity is precedence so the time complexity is going to be Big O of M plus and at worst going to be Big O of M plus and at worst we traverse the length of both of those we traverse the length of both of those lists if they're very similar we're lists if they're very similar we're going to have to do a lot of comparisons going to have to do a lot of comparisons and then we'll go towards detail if and then we'll go towards detail if they're very different if I have a list they're very different if I have a list of 1 2 & 3 and then the other list is of 1 2 & 3 and then the other list is all values greater than 10 then I'm all values greater than 10 then I'm going to terminates very quickly and going to terminates very quickly and just do the rewiring and then jump out just do the rewiring and then jump out of there because I'm finished we're of there because I'm finished we're going to be using constant space we're going to be using constant space we're going to be using constant space because going to be using constant space because all we're doing is shifting of pointers all we're doing is shifting of pointers jumping around doing our little rewiring jumping around doing our little rewiring and then getting out of there and then getting out of there we're not creating a whole new array we're not creating a whole new array we're not create we're not create who knows we're not creating an array who knows we're not creating an array we're not creating anything that will we're not creating anything that will scale as our input gets arbitrarily scale as our input gets arbitrarily large which is what's big o is about large which is what's big o is about what these complexities and asymptotic what these complexities and asymptotic analysis is about if you like this video analysis is about if you like this video if this was a clear explanation hit the if this was a clear explanation hit the like button subscribe I know that this like button subscribe I know that this video was kind of easy but the thing is video was kind of easy but the thing is we'll have our fair share of hourly code we'll have our fair share of hourly code horns and Li code mediums we'll get to horns and Li code mediums we'll get to those and do those but I want to set a those and do those but I want to set a fundamental basis and teach these fundamental basis and teach these because it is key to have these because it is key to have these fundamentals for our sorting algorithms fundamentals for our sorting algorithms and apply to other questions like merge and apply to other questions like merge K sorted lists that's all for this video K sorted lists that's all for this video [Music] | 2024-03-19 17:13:24 | 21 | Merge 2 Sorted Lists - A Fundamental Merge Sort Subroutine ("Merge Two Sorted Lists" on LeetCode) |
|
dX3BbTVA0Ro | hey everyone today I'll be doing another delete code problem 86 partition list delete code problem 86 partition list this is the medium one given the head of this is the medium one given the head of the link list add a value X partition it the link list add a value X partition it such that all the node less than x comes such that all the node less than x comes before nodes greater or equal to X so before nodes greater or equal to X so you should preserve the original order you should preserve the original order relative order of the node in these two relative order of the node in these two partitions so if you if the link list is partitions so if you if the link list is given to us a linked list head given to us a linked list head 143252 then we are going to have also an 143252 then we are going to have also an X variable which will be just an integer X variable which will be just an integer and if it is 3 in this case you can see and if it is 3 in this case you can see the values we are going to have less the values we are going to have less than 3 will be coming to the left of the than 3 will be coming to the left of the linked list and the value is equal to or linked list and the value is equal to or greater are going to be on the very greater are going to be on the very right and their order should remain same right and their order should remain same one two two one two two four three five one two two one two two four three five and the right side of the resultant link and the right side of the resultant link list should also have the same four list should also have the same four three five order three five order so first of all we'll be making just two so first of all we'll be making just two separate lists so separate lists so left and right left and right which will be just list nodes which will be just list nodes a dummy node the dummy nodes so a dummy node the dummy nodes so list list node node node okay node okay so we will have an Alger variable and a so we will have an Alger variable and a right current variable right current variable so right current left current variable so right current left current variable left will be for the left and right will left will be for the left and right will be for the right be for the right and a current variable for our current and a current variable for our current pointer pointer these are also pointers uh for the left these are also pointers uh for the left and right link list which we are going and right link list which we are going to create and then we will join it later to create and then we will join it later to form our original linked list so to form our original linked list so while current is equal to head we will while current is equal to head we will go till current becomes null in our go till current becomes null in our original linked list and if the value of original linked list and if the value of current current dot well if it is less than x then we dot well if it is less than x then we are going to add it in our left link list and then just updating the pointer on dot next and in the else case we are dot next and in the else case we are going to do this for the right side so going to do this for the right side so girl dot next is equal to girl dot next is equal to current and right oh okay okay just updating the pointer in our just updating the pointer in our original linked list so current is equal original linked list so current is equal to current dot next and after that we to current dot next and after that we know that our L Cur variable know that our L Cur variable pointer Al current pointer is going to pointer Al current pointer is going to be at the very end of the left link list be at the very end of the left link list so we can just say L current dot next is so we can just say L current dot next is equal to the right dot next equal to the right dot next because right itself is a dummy node so because right itself is a dummy node so rigst dot next rigst dot next so if we have a left linked list like so if we have a left linked list like this and the light linked list will be this and the light linked list will be like this but with like this so bar 2 like this but with like this so bar 2 will be pointed to 4 and now the whole will be pointed to 4 and now the whole link list will become like this but we link list will become like this but we have to make five point at null because have to make five point at null because the at this point the 5 does have the at this point the 5 does have the next node pointing at 2 so we will the next node pointing at 2 so we will go like our current go like our current dot next is equal to none dot next is equal to none none and just return no not dummy dot next the left dot next so left dot next and that's it this should work let's see if this works or let's submit it | 2024-03-20 12:42:04 | 86 | 86. Partition List | Leetcode | Python |
|
97YbdxpZmn4 | Hello Hello Guys Welcome To Know The Video The Series According Dhb Blood Circulation Lakshya Series According Dhb Blood Circulation Lakshya Studio Painters Painters Painters Of Studio Painters Painters Painters Of Is Difficult To Win The Inside Of An Is Difficult To Win The Inside Of An Appointed To Another Indian Live With 1.138 Appointed To Another Indian Live With 1.138 Volts And Short Term Interest Rate And Volts And Short Term Interest Rate And Which Is The Longest River In This Question Which Is The Longest River In This Question Is the longest in increasing order for Is the longest in increasing order for example subscribe The two in this eliminates all elements are increasing and example you love you love you all the best during subsequent problem and truly of elements definitely limit of elements definitely limit like this perform look at like this perform look at like this perform look at To Change The Language For Example 12345 125 The Look For This Is The Parameter Gift Enough Look For This Is The Parameter Gift Enough To So Let's Move With Example 12071 To So Let's Move With Example 12071 Subscribe Consisting Of Elements Are To To To To To To To To 9 Question Six And Cigarette In The Basis Of Question Six And Cigarette In The Basis Of Increasing Sub Chipk Bittu Element Weight Increasing Sub Chipk Bittu Element Weight 600 Vacancy In The Value Of One Year To Win 600 Vacancy In The Value Of One Year To Win The Correspondents Pay Are Switch Enter Value The Correspondents Pay Are Switch Enter Value And Visit To Elements Of Knowledge To And Visit To Elements Of Knowledge To Connect With Subscription For Increasing Clutch Point Subscription For Increasing Clutch Point To The Point Where You Were Too To The Point Where You Were Too Old For Increasing With Other Old For Increasing With Other Elements In Entry Entry Sequence Of Elements In Entry Entry Sequence Of Events Of The Day Qualification For Its Elements In This Form Of Increasing Subsequent So Let's Take More Examples To Hate You Welcome More And More Teer Website In This Is Called Afternoon And Job Change So Gel Change From Zero Flashes Will Be One And They Will Be Two In The Morning Punishment Influential Doctor Follow Variable Is Selected For A Question Is The Three ranges echoes Three ranges echoes Three ranges echoes in this will have two elements for in this will have two elements for informing subjects which country is the informing subjects which country is the value of d p kar is point to medium value of d p kar is point to medium size two two two two two three subscribe size two two two two two three subscribe decoration definitely add two two two two two two decoration definitely add two two two two two two two watch Thomas Subjects With Subjects With Subjects With Another Element Of Clans 2017 Senior Another Element Of Clans 2017 Senior Citizen For Giving Information Supply Citizen For Giving Information Supply Switch On The Amazing Value To Three And Switch On The Amazing Value To Three And Immediately St Mira And Clearly Person Immediately St Mira And Clearly Person Weakness Ok No Let's Go Forward To Our Weakness Ok No Let's Go Forward To Our Website For More Details In 12 And Is Website For More Details In 12 And Is Equal To 9 4 6 Increasing In And Nation Will Reach To Change From 0230 J2 And Nation Will Reach To Change From 0230 J2 J2 End Subscribe 90 Subscribe J2 End Subscribe 90 Subscribe Try Na Benefits Loosening Airing Try Na Benefits Loosening Airing Element Select One Or Two You Can So That Element Select One Or Two You Can So That Value Hears Point To The Intake It Value Hears Point To The Intake It Not Let Go To Back Side Reaction One Addition Not Let Go To Back Side Reaction One Addition Waves Equal To Waves Equal To Waves Equal To Poison No Response Green Sabzi Panchvati Colors Point To That Free Indergarh Find The Length Of The Mystery Solve Informing Sabzi Follow 139 It's All Chicken And Will Be Friends Free Switzerland Seervi Changes Strange Land And Three So Let's Go Work Back side reaction and equation of Back side reaction and equation of Back side reaction and equation of vacancies shrunk 2012 hands where is vacancies shrunk 2012 hands where is equal to forces and subsequent matka equal to forces and subsequent matka responsive to the value in delhi are its responsive to the value in delhi are its history the means 16 element 6 history the means 16 element 6 forming in freezing subsequently three forming in freezing subsequently three elements and that you can see elements and that you can see that 1369 sona love you all and that 1369 sona love you all and that 1369 sona love you all and Others in No Way Increasing Chicken Planets to Switzerland Year Two for Lips to the Extra Fashion Show in a Side Reaction Bhauji Killed Three and Who Is Called Fool So in This Case with the Elements for Age Suzy Lee Forces on Sunscreen Subject Karj Point Ko For All Defense Todi School Was Already Skimming Assumptions Offline Free Mode Vacancy Warning And Force One Free Forever All Chicken Due To Zoom Zoom Lens For Holiday In The Difficult Point To The Index Of Chief Wali Forests Oye It's Ok This This This balance for all should be solved finally balance balance for all should be solved finally balance and depression length after all this addition and depression length after all this addition system that Note 4 100 or 125 to interest system that Note 4 100 or 125 to interest DP are requested to enter DP are requested to enter this point excise problem and nurse this point excise problem and nurse to the next size in rural sanitation by this to the next size in rural sanitation by this point to equal point to equal point to equal Reach From 0240 Equal To Zero Ujjwal 2012 Pimple To Four Slaps Previous Lok Sabha Equations With This One Is Equal To Watch And James To 20 For Celebration Select Me Redmi Y2 Price With Different Colors And Vikram Such Physical Profile Change School Par Divas Have Everything Seems Of Elements 147 Days When You Hear For The Indore Difficulty Value Here And Demerits Of Wallace Govardhan Excited Modification One Side Reaction This Rings Total To One And Equal To 50 This Particular K Switch Again Into Elements And For So Let's Let Me Rajeev Rate Subjects Were Wearing A Free End For This Lesson 4 Bread And Butter Quality Of Sperm In Vegetables Switch Of Clans 2014 This Vegetable Is Unheard Of Weekend It Is Necessary And The Planets Needle Scissors Is The Value Of The Day Piary Knowledge Ko Banyan Tree Element 3D Make records related to this 6 Make records related to this 6 Make records related to this 6 record finance record finance elements elements that ashwa great and for withdrawal from which that ashwa great and for withdrawal from which is not for me in reading surgical is not for me in reading surgical strike enters go to back side reaction strike enters go to back side reaction in a side reaction also f4 is equal to full is not smaller than for in a side reaction also f4 is equal to full is not smaller than for president for r president for r security security security Vegetables Soldier And To The Next First Become 12349 All Ingredients Only Manpreet Singh Subsequent And Adventures Complete And Hydration Finally After All This Edition Spread This Explosion Clear Now Late May Zinc Color That Joint NCW Trees To Share So Support also cheese Support also cheese Support also cheese repair if then inside maximum possible in repair if then inside maximum possible in physical evidence for any one should support physical evidence for any one should support 11516 subjects for and another session 11516 subjects for and another session according to the judge cheese C 149 302 most strongly and will give the maximum according to the judge cheese C 149 302 most strongly and will give the maximum garlic more people basic garlic more people basic principles hundred-one and a half hundred Vikram Solar principles hundred-one and a half hundred Vikram Solar question accused question accused question accused And Lag Questions Let Me Clear Govardhan Logic Pro Can See Can See What 's The First You For Elements For Add With Small S With His Two And Half Inch Come After Us And Uk 06 Bodhi Vriksha Airplane Come Here From This Is Vivek Oberoi And This Tractor Sorted By Which Way Can Make You Love One and Half Inch Width One and Half Inch Width One and Half Inch Width Minimum Volume Maximum Number of Giving Minimum Volume Maximum Number of Giving One to Two to Two to Two to Two Boys Subscribe Now 104 Diet Relations Will See Back Na Person Parameters to Compete with Amit Vikram Very Good Source Spell Check 512 Withdraw Develop This Into Cases in a Small Cases in a Small Cases in a Small Enterprises Difficult Friesland Opinion Enterprises Difficult Friesland Opinion Village Support System Options Vision with Faith Village Support System Options Vision with Faith and Fight for Pain During Inner Wheel and Fight for Pain During Inner Wheel Club InnerWheel is now having a relationship Club InnerWheel is now having a relationship with two and wearing tight Free See the with two and wearing tight Free See the Question Meaning Properly * * * * * * * That going inside to here follow Suji Kal 2012 That going inside to here follow Suji Kal 2012 112 2800 Hero BJP Are Properly Which 112 2800 Hero BJP Are Properly Which Continent And Electrification See Tension I Continent And Electrification See Tension I Want To See Them 9 6 And Interact With Them Want To See Them 9 6 And Interact With Them Properly Can Just Properly Can Just Subscribe To My YouTube Channel The Channel Subscribe To My YouTube Channel The Channel and and and Person When England Makes Sex with Six and Light Practical Another Innovative Sighting Let's Say with Spinach and Life Is the and All Over the World and Two Two Two Two So One Two One Two One Two Three Two Two Two Two Two Two Two Two Three example.com Should You Are I See Code Free This Rings Kumar Forensic Condition Him Loudly To The Height And Width Side So This Of This After Mast And Adding Another In Are In Mast And Adding Another In Are In Mast And Adding Another In Are In Love With The Significance Of Life But Love With The Significance Of Life But Inside Famous For Its Already Fallen In Love Inside Famous For Its Already Fallen In Love How Did Not Because Zindagi Peer Value 230 How Did Not Because Zindagi Peer Value 230 Rings Monitoring Luck Last Year England Rings Monitoring Luck Last Year England Tour And Height Free Which Were Seen Previously Tour And Height Free Which Were Seen Previously Soil And Having One Quick Tour Soil And Having One Quick Tour And back to back to in love story doctor And back to back to in love story doctor interview hai vaibhav cold days six interview hai vaibhav cold days six all cervix cancer value two three layer all cervix cancer value two three layer in peace and love suggestion value sperm donor in peace and love suggestion value sperm donor given two plus ministry said adding this afternoon given two plus ministry said adding this afternoon of polar region's of polar region's 10 mediums of engineering research just opposite 10 mediums of engineering research just opposite 10 mediums of engineering research just opposite Vatavriksh Example member Lal Singh and last hydration for a classic example Eye record for senior judge 250 66 distribution Eye record for senior judge 250 66 distribution camps present to give dollars Twitter The camps present to give dollars Twitter The Channel and subscribe the Possible Velvet Channel and subscribe the Possible Velvet Questions and Answers to life and finally Questions and Answers to life and finally Bigg Boss Maximum Free Bigg Boss Maximum Free Bigg Boss Maximum Free Solid CO2 subscribe and subscribe the Muddasar Very Simple Inch Plus Office Gift Muddasar Very Simple Inch Plus Office Gift Function Of Us Want To Know Automatically Short Function Of Us Want To Know Automatically Short And Adventures Of Birth Per For Annual And Adventures Of Birth Per For Annual Rainfall Utsav Term Us Look Into Equal To Rainfall Utsav Term Us Look Into Equal To Zero Electronic And Develop Dot Zero Electronic And Develop Dot Zero Electronic And Develop Dot And Half Inch Plus Pendu *Also Give You Will Have This To The Page To The Page If You Liked The Video Then Who Is With This Great Up And Also Will Give Smooth on Yellow Height and Smooth on Yellow Height and Smooth on Yellow Height and Laugh IS One Such This is the Height of the Laugh IS One Such This is the Height of the Lambs Paid the Height of the Year and Loves U Lambs Paid the Height of the Year and Loves U Don't Know To subscribe to the channel Don't Know To subscribe to the channel Russia Change the Value of the Country of the Russia Change the Value of the Country of the World Subscribe to the channel and G Plus plus one and more than half plus one and more than half volume maximum selected from easy volume maximum selected from easy sequence give maths elements and sequence give maths elements and elements of obscuritism up dot elements of obscuritism up dot big b dot net big b dot net a tent and light show i will run this and a tent and light show i will run this and its effects of working withdrawal it gives its effects of working withdrawal it gives no gratitude of this no gratitude of this i and i and i and develops in and we lighter sort of interest to begin ok so why have the given water mixed and definition of a plate mixing sheet against its surface 9th 9th 800 l x x | 2024-03-24 11:20:36 | 354 | #Leetcode 354. Russian Doll Envelopes || Code+ Explanation with examples |
|
43ruFMsU4mI | welcome back everyone we're gonna be solving Lee Code 151 reverse Awards in a solving Lee Code 151 reverse Awards in a string so we're given an input string s string so we're given an input string s we need to reverse the order of the we need to reverse the order of the words and a word is defined as a words and a word is defined as a sequence of non-space characters the sequence of non-space characters the words in s will be separated by at least words in s will be separated by at least one space one space so essentially what they want us to do so essentially what they want us to do is right they give us a string the sky is right they give us a string the sky is blue they want us to return blue is is blue they want us to return blue is the sky the sky and if we take a look at the follow-up and if we take a look at the follow-up question if the string data type is question if the string data type is mutable in your language can you solve mutable in your language can you solve it in place with all of one extra space it in place with all of one extra space uh as we know strings are immutable in uh as we know strings are immutable in Python so I won't be doing the follow-up Python so I won't be doing the follow-up question question uh python is my main language so there's uh python is my main language so there's no reason for me to be asked this no reason for me to be asked this follow-up question but if your language follow-up question but if your language does do it you know leave some comments does do it you know leave some comments down below and show me how you do in down below and show me how you do in your language of choice your language of choice all right so what we're going to do is all right so what we're going to do is we're going to create an array we're going to create an array and it will be equal to and it will be equal to uh s dot split right what is this going uh s dot split right what is this going to give us let's print this out all right so this gives us all of the all right so this gives us all of the words right in a list format okay so now words right in a list format okay so now what now we can just make a pointer what now we can just make a pointer right we'll point it to the very last right we'll point it to the very last word and then we'll just create a new word and then we'll just create a new string with the word at the pointer string with the word at the pointer position and then decrement our pointer position and then decrement our pointer every time we use the word right super every time we use the word right super simple simple so let's say so let's say uh we'll have a resulting array which we uh we'll have a resulting array which we will use to put the words in and we're will use to put the words in and we're going to have a pointer all right the going to have a pointer all right the pointer is going to be equal to the very pointer is going to be equal to the very last position in the array we just made last position in the array we just made so it'll be the length of so it'll be the length of array minus one now we are going to run array minus one now we are going to run a loop while this pointer is greater a loop while this pointer is greater than negative one we want to add the than negative one we want to add the word at the pointer position to our word at the pointer position to our resulting array so we'll say well resulting array so we'll say well pointer is greater than negative one pointer is greater than negative one we are going to say we are going to say um actually let's make it I'll make it um actually let's make it I'll make it more clear so the word that we're going more clear so the word that we're going to grab is going to be equal to to grab is going to be equal to array at the pointer position array at the pointer position and what are we going to do we are just and what are we going to do we are just going to append this word onto our going to append this word onto our resulting array so we'll say res that resulting array so we'll say res that append the word and then we can just append the word and then we can just decrement our pointer by one decrement our pointer by one and then let's before we return let's and then let's before we return let's print out what we have so we'll print print out what we have so we'll print res res and we see we get blue is sky the right and we see we get blue is sky the right that's what we expected uh the all the that's what we expected uh the all the words are in reverse order but how do we words are in reverse order but how do we return this well now we have to return a return this well now we have to return a string join right they want it in a string join right they want it in a string format string format so we will say we will return a string so we will say we will return a string join of our resulting array but each join of our resulting array but each word needs to be joined by a space right word needs to be joined by a space right so we add a space to our string join and so we add a space to our string join and we can just return and that should be it we can just return and that should be it so let's run this so let's run this perfect we pass all three test cases perfect we pass all three test cases we'll submit perfect it does run so time and space complexity time complexity is going to be o of n right we are looping through our array and grabbing all of the words touching them at least one time we're also creating a split array right this is going to be o of n this while loop is over n so now space complexity space complexity is going to be based on the length of our resulting array plus the length of the array we created with our split function so it will be array.length plus the resulting array dot length | 2024-03-21 13:10:15 | 151 | LeetCode 151 - Reverse Words in a String: A Microsoft Journey |
|
JdKYHXqxf9A | Hello gas welcome you me YouTube channel so today we are going to solve problem solve problem 373 fine pairs with small further problem what is 373 fine pairs with small further problem what is doing this is medium level doing this is medium level problem you are life you interior are problem you are life you interior are name one and you sorted in ascending order name one and you sorted in ascending order and Consists of one element from returned then how much will be made in it, there are returned then how much will be made in it, there are and that with 11, you with 11, 411 praise] how to make plus plus, it is done like this and vector. vector. vector. which is the index here, which is the index here, if we which is the index here, which is the index here, if we index both of them, then this short function will always be short, what will we do now, just now there total. type of store, it is of this type, so let's take it as mother, what happened to it, the it needs the one with this number, it will go inside the answer, which Is of vector and is of vector type Is of vector and is of vector type Is of vector and is of vector type become two, then we will check that the become two, then we will check that the number of feet we have made, if it is more number of feet we have made, if it is more then we can enter only two, otherwise only two have to be then we can enter only two, otherwise only two have to be returned here. returned here. returned here. if the value of the cake will be more than 3x, it can be made on two, one can become three and you can make three, so what will you do, then you will check that the amount that you have made should be limited to that, otherwise if there is extra, then it will If it is done, now we will run it and If it is done, now we will run it and If it is done, now we will run it and submit it, it will come to you, the why would we increase the time complexity here, why would we increase the time complexity here, like like how much will it take to shorten it, how much will be its length, how much will be its how much will it take to shorten it, how much will be its length, how much will be its legs, and then we are sorting it. legs, and then we are sorting it. Take total mother, if it has 3 size Take total mother, if it has 3 size relief, it has 3 size relief, it has 3 size relief, 3 * 3 = 9, relief, it has 3 size relief, it has 3 size relief, 3 * 3 = 9, total will be 95, why can we give it priority, why can we give it priority, how will we give it priority, then what will happen to it, If it will be in sort, then for the If it will be in sort, then for the If it will be in sort, then for the first time there will be a memory limit that whatever number of first time there will be a memory limit that whatever number of elements will remain on it, that much time will be required elements will remain on it, that much time will be required because the size of this will be because the size of this will be multiplied by the size of this, that will multiplied by the size of this, that will be the total number of elements, then be the total number of elements, then how will we optimize it? how will we optimize it? Let's first remove the vector that has been created for this. Now, how will we optimize it? So let's Now, how will we optimize it? So let's see here, what will we do to optimize it, first is the first is the element of this. Now why should we make it a priority? First, what do I need in this? If I want minimum, if I want minimum then what will I make in this [Music] How is it divided? To make mini, it is better to write so many times here. Whoever knows the short, It It It can be written, there is no need to write it again and again, let's can be written, there is no need to write it again and again, let's type first index to put it in Preetiko, then which is your type and which type is greater here? with this, give all this pulse, first give all this pulse, first give these with this, give all this pulse, first give all this pulse, first give these you do, what will you do this one who is the one with the answer, Give it zero, this one, Give it zero, this one, what else, what is the size of the priority, give it a greater zero, this is also possible, the priority has become the first zero, how can this one be here we have to top top of that if here we have to top top of that if here we have to top top of that if go to extract it, then it will come here because we are extracting it from the empty space, so this should also be checked, the meaning should time is gone this one, A went on this, now A went on this, now A went on this, now this has been done to you, if you put it in the direct answer, then answer dot answer where you will create vector answer dot post back, value will be back. first step, what will happen in the first step. first step, what will happen in the first step. This is yours being stored here, so these first three 30, these three will be inside it, if it is in hip, then what will come first in it, three three came three, what will be the difference between three, one and you, what will be the difference between three, one and you, what will be its index, what will be the value of index. what will be its index, what will be the value of index. what will be its index, what will be the value of index. IPA index was zero, what will happen if you are the same, we will put it in 12, now after flying, one has become less, it has happened this one, we will compare one with four. this one, we will compare one with four. this one, we will compare one with four. something will happen here, one, one plus one plus, something will happen here, one, one plus one plus, how much is 5, sorry, so what happened by putting six, now But what will But what will But what will be the seven and here the index is the first one, so how much is it, now which is the minimum among the three, 7 then 7 will again pop top, the corresponding name of seven is zero, how much is zero, your so here so here value of name one and six? Then again we were writing the answer, so now what has happened, it has popped, writing the answer, so now what has happened, it has popped, now what is less, now we now what is less, now we will also check the first one, so now to compare with it, If we get it done then now we will give its second If we get it done then now we will give its second If we get it done then now we will give its second index pulse, whatever it is, it should remain small, so if it is small then only if we push inside it, then why will we do it now it has reached six, now now it has reached six, now how much is the plus one going, now it how much is the plus one going, now it how much is the plus one going, now it do K plus one with one, it will be taken out, neither is this, nor is the name, K plus one, nor is your name, when should the name be from the studio side, because six plus one will go further also, there So only then we will So only then we will So only then we will push it inside, we are doing it with this one, push it inside, we are doing it with this one, then we are adding it inside it, if we add it to the second then we are adding it inside it, if we add it to the second one, then now this first one is one, then now this first one is not removed, so now it is reduced, so now we not removed, so now it is reduced, so now we will compare it with this one, If it is If it is If it is in sorted order, then whoever comes first, will come music] but the this one has this one has so much time complexity, so so much time complexity, so now when we want to go private in it this, now how much is the total in it, how many elements are there in it, how much is there in taking out the hip from the total, if there is n size and if we have to extract a value from it, To To To pop the time complexity means to bring it to the top, if we pop from it, then the top operation is done, its time is still there, we pop from it, then the top operation is done, its time is still there, as per the size of the people and as per the size of the login, the mines will as per the size of the people and as per the size of the login, the mines will fine, see you in the next video. fine, see you in the next video. fine, see you in the next video. | 2024-03-24 11:38:12 | 373 | Find K Pairs with Smallest Sums | Heap | Google |Leetcode Challenge |Leetcode 373 |Medium |
|
4fQw1DRDyZs | hey hey everybody this is larry this is day day 18 of the rico day challenge hit the 18 of the rico day challenge hit the like button here to subscribe and join like button here to subscribe and join me on discord let me know what you think me on discord let me know what you think about today's farms i'm back in new york about today's farms i'm back in new york i went to wedding actually it was a i went to wedding actually it was a beautiful wedding it was a beautiful day beautiful wedding it was a beautiful day uh and now i'm back home where i uh and now i'm back home where i probably should set up the ac probably should set up the ac but it is very hot let's put it that way but it is very hot let's put it that way in my room right now in my room right now um i mean i think it's like 80 degrees um i mean i think it's like 80 degrees outside outside fahrenheit for those of you with normal fahrenheit for those of you with normal time scales i think or temperature time scales i think or temperature scales i think it's like scales i think it's like 20s or something i don't know what what 20s or something i don't know what what is it they is it they have to see have to see is 27 degrees uh and my apartment is is 27 degrees uh and my apartment is inside is hotter so yeah anyway inside is hotter so yeah anyway with that said today's problem is prefix with that said today's problem is prefix and suffix search okay design a special and suffix search okay design a special dictionary with some words that are dictionary with some words that are searched by prefix and a suffix what searched by prefix and a suffix what does that mean does that mean so apple uh so apple uh so you have an f function that's a and e so you have an f function that's a and e so return zero so return zero [Music] so what do we turn to okay let's see so we have a word list okay that's fine we turn the index of the word in the dictionary which has prefix prefix and suffix suffix if they're more than one violin then return the largest um um yeah and each of these will be at most yeah and each of these will be at most 10 length i mean i imagine my first instinct i mean this is obviously a data structure farm uh or this is set up that way um and i for my first instinct is to have like a try right um a try for both the prefix and the suffix um of course it's still a pre you know a prefix try but for the suffix you would just uh process all the words on the other direction and then maybe do like an intersection of the sets or something like that um but i don't know if that's good i mean in theory that should like on average case will be okay right but but definitely you can construct cases where that is just not acceptable right so then in that case what do we do if like for example if like for example if if the two like for example if if the two intersection is like if i'm trying to think if i'm trying to think i mean this the average case would be i mean this the average case would be okay but the the worst case right is if okay but the the worst case right is if both of them contain say 7 500 both of them contain say 7 500 uh or yeah 7 500 uh words uh or yeah 7 500 uh words um and they don't intersect at all and um and they don't intersect at all and we do that like we do that like you know 15 000 times that's gonna be you know 15 000 times that's gonna be too slow right too slow right so can i do better hmm um definite prefix can i walk that dag i mean it'll still be like if you zigzag so you can't really walk the two-pointer algorithm or something like that um in a in a better way i mean maybe it's um like like i don't know if this is just one of i don't know if this is just one of those problems where you know maybe the those problems where you know maybe the like like how bad is the worst case like like how bad is the worst case right or maybe i'm right or maybe i'm missing something maybe maybe missing something maybe maybe can we abuse something with the word can we abuse something with the word length of ten in a good way are all the length of ten in a good way are all the words unique words unique see see i guess if they're not i guess if they're not [Music] [Music] i guess if they're not unique then you just keep track of the larger index anyway right because it doesn't make sense to um yeah but i don't know the way that i was uh i i don't know if i should figure out uh i i don't know if i should figure out this one for the average case or the this one for the average case or the worst case i think that's the the tricky worst case i think that's the the tricky part um [Music] i don't know if there's an easier way so i don't know if there's an easier way so maybe this is fine i don't know maybe this is fine i don't know um because my my thing is that like um because my my thing is that like let's say yeah my thing is that if let's say yeah my thing is that if jeff's let's say an ae case right let's jeff's let's say an ae case right let's say you have say you have i mean just like the set intersection i mean just like the set intersection it's gonna be very expensive if if none it's gonna be very expensive if if none of them matches but if it does match you of them matches but if it does match you under the biggest one so you do a linear under the biggest one so you do a linear walk walk but that's still but that's still like like the average case would be good but the the average case would be good but the worst case may be bad and you could keep worst case may be bad and you could keep on pumping the worst case on pumping the worst case um let's see i don't know i mean okay can i take advantage of the 10 in a way can i brute force oh can i save the can i brute force oh can i save the answers in a good way answers in a good way um i want to also just like if i can [Music] keep tr maybe i can keep track in a good way but i don't know about the timing no because i was thinking about way we're almost like a pre-filtering thing of um of like okay so yeah because just getting the a list of all these numbers and then removing them will already be too slow right like let's say you have um a 10 000 word length and then you kind of just you kind of uh yeah you have 10 000 you kind of uh yeah you have 10 000 words and then you maybe go down down a words and then you maybe go down down a tree with those 10 000 words and then tree with those 10 000 words and then remove them as you go right remove them as you go right but even that seems but even that seems too slow too slow [Music] [Music] can can we do intersection in a good way can can we do intersection in a good way with respect to that huh um well okay can we take the suffix can we take the suffix in a good place no i don't know [Music] i'm not convinced that at the the the i'm not convinced that at the the the double try ideas fast enough just double try ideas fast enough just because unless i'm missing something because unless i'm missing something but because this can have like a lot of but because this can have like a lot of words right words right um i guess um i guess like for example if we have like for example if we have like we can easily construct an example like we can easily construct an example where like this is the worst case so where like this is the worst case so then you have f of say a e even which is then you have f of say a e even which is the one of the examples but then you the one of the examples but then you have word style like a a e a or maybe even something now that this would be okay but just now that this would be okay but just something like you can even just do something like you can even just do something like a b uh a a a a b a c dot something like a b uh a a a a b a c dot dot dot like 10 000 of these like 10 000 of these right right um and then um um and then um and then maybe i mean i mean this is not and then maybe i mean i mean this is not even the worst case i guess okay you even the worst case i guess okay you have something like this maybe have something like this maybe and then you have something like and then you have something like you know uh e a e you know uh e a e well maybe b well maybe b and then c e d dot dot and then c e d dot dot 7 500 of these right so there'll be no 7 500 of these right so there'll be no intersection between these intersection between these and therefore it would take the full 7 and therefore it would take the full 7 500 500 um um per function call and each function cost per function call and each function cost 15 000 times so 15 000 times 75 000 is 15 000 times so 15 000 times 75 000 is not gonna be good enough right not gonna be good enough right um um so i don't really know how to do it in a so i don't really know how to do it in a better way to do like some sort of better way to do like some sort of intersection intersection without figuring without figuring um out um out like maybe like maybe i don't even uh i don't even uh like should i yodo like should i yodo like is this fast enough like is this fast enough no no no no hmm i guess one way we can do it is what is uh this times 100 right so to do 1.5 million 1.5 million times 10 is 15 million is that enough uh something like that maybe 30 million i guess maybe that's enough memory i guess we could pre-process all the possible for each word we can pre-process all the possible prefix and all the possible c suffix and then we can do def f of one the only thing i'm a little bit worried about is is that is that um so f so this will be fast enough the um so f so this will be fast enough the only thing that i worry about is about only thing that i worry about is about memory whether we have enough memory memory whether we have enough memory um to do it um to do it um um but um let's see right so there there are a hundred prefix hundred suffix so we do a hundred square well technically one to ten so i guess that is ten a hundred um so that's uh what is it 1.5 million and each of them may contain up to 20 characters so that's 30 million um and that's probably pretty okay 30 million characters with some overhead it should be okay okay let's try it that way a little bit sad that it took me that a little bit sad that it took me that long though to be honest to think about long though to be honest to think about it but there's just a lot of i was it but there's just a lot of i was trying to figure a way to do it without trying to figure a way to do it without this this thing but maybe that's just the way to thing but maybe that's just the way to do it i don't know do it i don't know let's let's give it a spin so that now let's let's give it a spin so that now for for word in words word in words uh maybe i don't need this actually uh maybe i don't need this actually but anyway but anyway self.lookup is to go to hash table um so self.lookup is to go to hash table um so then now then now key is equal to key is equal to let's say yeah um [Music] well and then for j in range of length of and then for j in range of length of word word right is it maybe plus one but also right is it maybe plus one but also starting from one starting from one so i is the sub or prefix and j is the so i is the sub or prefix and j is the suffix so then we have something like suffix so then we have something like um [Music] oh what is it from the first eye yeah maybe uh maybe something like this it doesn't really matter just some sort of maybe just space maybe this place is fine uh is that j now it's um negative j right let's print this out real quick because i'm always really bad with off by ones with these indexes so i think this is right but maybe i'm offline one a e a o e a b okay that looks okay so yeah okay so then now we can do something like sub dot look up of key is you go to index right i didn't actually do the enumerate i forgot um and this will overwrite with later one so i think this will give us the largest one so then now we have key is equal to also technically what i would recommend also technically what i would recommend is actually putting this in a function is actually putting this in a function but functions in python are expensive this is not so if you're doing production code definitely put in a function lead code is slow so um i'm the code is silly so uh yeah i mean yeah they don't have any optim uh it's just slow so that's what i'm doing this way so okay if key is in sub.lookup we turn uh uh i should say we turn negative one which is not true we return self.lookup of key this is zero indexed i guess so so let's give it a spin i mean this is a really easy thing to do let me see if i can well there's only one way all right let's just give a quick submit and see wow apparently in the past i've done it in many ways okay this time i did it i mean i solved it on the first try so keeping the streak alive at 809 days but much slower i don't know if they added more word or anything how did i do it previously let's find out oh let's go with complexity real quick i mean like i said this is o of um n one for each word times uh let's say l times uh uh or maybe p times p where p is the size of prefix suffix to curry right and then i use i didn't actually use as much memory as i worried about uh and then here this is just o one basically uh depending on how you say it or one in terms of lookup you can maybe say of n in terms of the size of the input and then look up it um but that's up to you i am i'm trying i'm curious how they did it last time definitely ate some things uh i did do it with try so how did i do it try oh so this is the thing where i did the set intersection the set intersection is going to be too slow i think i was very optimistic in in uh and i don't know why i did it this way except just like max but maybe i was just 2019 i was still learning python a little bit or like learning [Music] yeah i mean i i would say i was still learning python um yeah you would just get the max but i'm not surprised that that time limited and then what would i do uh and then i did some up what did some weird optimization but oh and then i did the thing where i moved one at a time but apparently there's some like weird thing going on i don't know uh and then i gotta accept it and ultimately by oh i still use huh so the try in the section thing works i wasn't sure that this was fast enough to be honest that's why i didn't um but i guess my past larry is is more confident about it it's the thing like i said right like we can construct cases where this is just too slow and then if you do that query like 15 000 times it's going to be too slow um but today i just wasn't maybe i self-doubt myself too much and i should yell no more what was the hint anyway oops uh what was the hint uh what was the hint oh oh that's basically what i end up doing but that's basically what i end up doing but that's not even a hint that's just like that's not even a hint that's just like telling you how to do it telling you how to do it uh how did i do it the second time uh how did i do it the second time second time oh i did do it second time oh i did do it [Music] [Music] well i did it the same idea but i did it well i did it the same idea but i did it with uh much slick no with uh much slick no yeah well i mean this is not a stuff yeah well i mean this is not a stuff seems like the second time i did i got seems like the second time i did i got lazy with the the tree and i just put lazy with the the tree and i just put everything in a set um but then it was everything in a set um but then it was the wrong answer and then time limited the wrong answer and then time limited so it was too slow so then i oh i did what i did today except i use a tuple instead is that better i don't even know but i got wrong answer what did i get oh i don't know why i did it this way oh i don't know why i did it this way but this is the wrong answer because i but this is the wrong answer because i um i reversed the word um i reversed the word uh maybe so i could write this a little uh maybe so i could write this a little bit better bit better wait what this is just silly i think it wait what this is just silly i think it was just like me being careless because was just like me being careless because this should be j at the very least um so this should be j at the very least um so there are a couple of errors there but there are a couple of errors there but then i autumn i think i just because the then i autumn i think i just because the inputs didn't test it so there you go inputs didn't test it so there you go and then suffix i and then suffix i reversed it so i reversed it twice so reversed it so i reversed it twice so it's a little bit silly actually um but it's a little bit silly actually um but basically it's the way that i did it basically it's the way that i did it today so maybe there is more input as today so maybe there is more input as well um well um maybe not i mean strings does take more maybe not i mean strings does take more time time to construct to construct but maybe not i don't even know but maybe not i don't even know [Music] [Music] anyway this is a very weird problem anyway this is a very weird problem because i think it because i think it i think this is uh one of those problems i think this is uh one of those problems where where the constraints don't really tell you the constraints don't really tell you the whole story it depends on the the whole story it depends on the distribution of the inputs which they distribution of the inputs which they don't really or there's no easy way to don't really or there's no easy way to tell tell because like i said um because like i said um i don't know i guess i deleted it but because you know you can probably break tle most cases if you just have something like your word dictionaries a a b a c a d no a e uh a f dot dot dot and then like just doesn't really matter what they are just anything that starts with a but 7 500 of them and then something that ends with say e and then also doesn't matter what they are um as long as you have 7 500 000 of them and none of them with with a prefix right and then you just run query f of a e 15 000 times and if you do it that way just with time limit because there's not nothing to do you have to do it essentially a full set intersection which is 75 100 times two um and [Music] and fifteen thousand times fifteen thousand square is gonna be too slow so which is why i hesitant um but i don't know sometimes you have to read minds or yolo and get a little lucky uh didn't do either today so whatever anyway that's all i have though i did get it on the first release time so i guess that's good anyway stay good stay healthy to get mental health i'll see | 2024-03-21 12:17:39 | 745 | 745. Prefix and Suffix Search - Day 18/30 Leetcode June Challenge |
|
wBfKV2hiep0 | hello so it is uh 19 June 2023 is lead code uh daily challenge it's a easy code uh daily challenge it's a easy level question is find the highest level question is find the highest attitude yeah so what's the question attitude yeah so what's the question stated there is a biker going on a road stated there is a biker going on a road trip the rotor consists of n plus one trip the rotor consists of n plus one points at different altitudes the biker points at different altitudes the biker starts his trip on point zero with starts his trip on point zero with altitude equals to zero you are given an altitude equals to zero you are given an integer array gain of length and where integer array gain of length and where gain of I is the net gain in altitude gain of I is the net gain in altitude between I and I plus 1 for uh index between I and I plus 1 for uh index ranges from 0 to n minus 1 both ranges from 0 to n minus 1 both inclusive return the is attitude of a inclusive return the is attitude of a point so basically from the problem point so basically from the problem statement it is clear that a gain of IE statement it is clear that a gain of IE is gonna be sum of the of that value is gonna be sum of the of that value which the value that is there in that I which the value that is there in that I that index and the previous Index right that index and the previous Index right while you are the previous index while you are the previous index so that's how it's going to go and so that's how it's going to go and that's the example the one also State that's the example the one also State States the same thing so if we calculate States the same thing so if we calculate the gain array and this is how the gain the gain array and this is how the gain array is going to look like because the array is going to look like because the initial gain is going to be 0 because we initial gain is going to be 0 because we are starting from uh because at some are starting from uh because at some point altitude with equation zero so point altitude with equation zero so this is how the initial attitude is this is how the initial attitude is going to be then the second uh first going to be then the second uh first started is going to be minus 5 because started is going to be minus 5 because that's the again at this point and then that's the again at this point and then when you move to the first index uh yeah when you move to the first index uh yeah when you move to the next index the gain when you move to the next index the gain is going to be the addition of that is going to be the addition of that index plus the previous index correct so index plus the previous index correct so that's what has been done so basically that's what has been done so basically um what is happening is we are um what is happening is we are calculating the prefix sum of the array calculating the prefix sum of the array uh we are calculating a prefix gain uh we are calculating a prefix gain array right the gain error is actually a array right the gain error is actually a prefix prefix uh of the array that is prefix sum of uh of the array that is prefix sum of the array that has been given to us so the array that has been given to us so when we if we could calculate it and we when we if we could calculate it and we could keep uh uh running some running could keep uh uh running some running marks marks as a as answer or finally if we could as a as answer or finally if we could uh maintain the maximum amount so that uh maintain the maximum amount so that we are getting at each and every index we are getting at each and every index that will be a running Max and your at that will be a running Max and your at final when the render traversal is done final when the render traversal is done if we return the answer and that's how if we return the answer and that's how and that's that would be the answer and and that's that would be the answer and the thing that we are an additional case the thing that we are an additional case attached is zero could also be the attached is zero could also be the answer answer so initially by setting up answer equals so initially by setting up answer equals to zero and running your uh to zero and running your uh running calculating the prefix running calculating the prefix this uh some of the gain array that has this uh some of the gain array that has been given to us and uh uh at runtime been given to us and uh uh at runtime calculating the maximum for each and calculating the maximum for each and every index that has been given to us every index that has been given to us calculating the calculating the getting the answer getting the answer correct so this prefix array could correct so this prefix array could actually be can you calculate by using actually be can you calculate by using an X carry also as there is so many an X carry also as there is so many connections even on the gain area that connections even on the gain area that has been given to us that is it could be has been given to us that is it could be modified also so we will actually modify modified also so we will actually modify this area this area to calculate the prefix uh sum for each to calculate the prefix uh sum for each and every index so initially we'll have and every index so initially we'll have an answer zero and this is what is going an answer zero and this is what is going to be written as answer could be 0 and to be written as answer could be 0 and then we'll calculate the then we'll calculate the size of the given array size of the given array and then we are going to travel Travis and then we are going to travel Travis from the first index because screen of I from the first index because screen of I is going to be gain of I plus the is going to be gain of I plus the previous index so we'll grab us from the previous index so we'll grab us from the first index so that there is no out of first index so that there is no out of boundaries or something like that so but boundaries or something like that so but the possibilities of answer being gain the possibilities of answer being gain of 0 is also also a exists right of 0 is also also a exists right so we'll make sure that we calculate it so we'll make sure that we calculate it separately and then now we rapid Ours separately and then now we rapid Ours from the first index all the way to the from the first index all the way to the last index and Performing this last index and Performing this particular operation that is gain of I particular operation that is gain of I will be addition of gain of I plus the will be addition of gain of I plus the previous gain that is gain of I minus 1 previous gain that is gain of I minus 1 and we'll update maximum answer also and we'll update maximum answer also that is that is yeah and that's how it's going to be yeah and that's how it's going to be done answer after this done answer after this foreign yeah so without discussing the foreign yeah so without discussing the diamond space complexity time complexity diamond space complexity time complexity is going to be order option because we is going to be order option because we are doing a single trouser space are doing a single trouser space complexity is going to be constant for complexity is going to be constant for the implementation that we have done uh the implementation that we have done uh if at all there is a constraint on the if at all there is a constraint on the given area to be not modified then you given area to be not modified then you have to say I can create a separate area have to say I can create a separate area for calculating uh for calculating uh the gain even that is not possible if the gain even that is not possible if even that is not needed we could just even that is not needed we could just perform the action with just two perform the action with just two variables because gain of I is actually variables because gain of I is actually depending on the previous index rate so depending on the previous index rate so we could have a previous well and then we could have a previous well and then the current well so previous value will the current well so previous value will uh get updated every time when we move uh get updated every time when we move uh to the uh new index and current will uh to the uh new index and current will be calculated and the next iteration be calculated and the next iteration when we come to the next iteration when we come to the next iteration previous value could be made as current previous value could be made as current value so that could be done like a sort value so that could be done like a sort of of yeah that could also be done and it's yeah that could also be done and it's calculating the answer in an easy way so calculating the answer in an easy way so I | 2024-03-20 17:53:35 | 1,732 | Leetcode 1732. Find the Highest Altitude | Daily Challenge Leetcode | Apple |
|
ih9aRYfPdxg | okay hi everyone so today we're going to swaminate code problem number and 3D swaminate code problem number and 3D challenge problem problem number three challenge problem problem number three to eight on demanding list to eight on demanding list so in this uh what we have to do is we so in this uh what we have to do is we have to just uh basically grow all the have to just uh basically grow all the elements or all the nodes at uh odd elements or all the nodes at uh odd indexes and all the notes of uh even indexes and all the notes of uh even indexes together indexes together and one more keynote over here is and one more keynote over here is the first index will be treated as a odd the first index will be treated as a odd index okay it should not you know you index okay it should not you know you should not think of it as a zero index should not think of it as a zero index element and mobile so the first index element and mobile so the first index will be treated as a odd and X will be treated as a odd and X and they have also given this constraint and they have also given this constraint that we must try to solve this problem that we must try to solve this problem with order of one extra space complexity with order of one extra space complexity and Order of end time context which and Order of end time context which means means we should not use any Extra Spaces to we should not use any Extra Spaces to throw the link list and we should try to throw the link list and we should try to uh you know solve the problem in a uh you know solve the problem in a single path single path okay so solution for this will be a very okay so solution for this will be a very simple solution in which what I'm going simple solution in which what I'm going to do is I'm gonna use two pointers to do is I'm gonna use two pointers first point to the point to the very first point to the point to the very first node which is an odd node like the first node which is an odd node like the first pointer will be used for uh you first pointer will be used for uh you know keeping a track of odd index values know keeping a track of odd index values or notes and second one will be used for or notes and second one will be used for the even indexes okay so I'm gonna the even indexes okay so I'm gonna initialize that the or going to be the initialize that the or going to be the first one and even point to the second first one and even point to the second and what I want to do is and what I want to do is incredibly if I want to create two incredibly if I want to create two separate linked lists separate linked lists for odd and even and at the last I just for odd and even and at the last I just want to point the next pointer of the want to point the next pointer of the last forward element or node to the last forward element or node to the event list event list okay so how we're going to do that is okay so how we're going to do that is for example my pointer is currently for example my pointer is currently pointed to 1 like the odd filter and the pointed to 1 like the odd filter and the even responding to the two okay what even responding to the two okay what I'll be doing is I'll be doing is odd dot next will be equal to what even odd dot next will be equal to what even dot next right dot next right so 1 and 3 will uh get together and so 1 and 3 will uh get together and similarly for even and of course like similarly for even and of course like I'll move my odd pointer and we can I'll move my odd pointer and we can simply say R is equal to odd dot name so simply say R is equal to odd dot name so now I want to be moved from 1 to 3. now I want to be moved from 1 to 3. similarly for SEC like the even pointer similarly for SEC like the even pointer my pointer was pointing to the two ways my pointer was pointing to the two ways of now but of now but uh after making you know all the changes uh after making you know all the changes in our pointer my odd pointer is three in our pointer my odd pointer is three right uh next of three is four so what right uh next of three is four so what I'm gonna write is I'm gonna write is even is equals to odd dot next even is equals to odd dot next okay so essentially I'm just uh changing okay so essentially I'm just uh changing the pointer of my event to the next of the pointer of my event to the next of odd and similarly we are going to update odd and similarly we are going to update the even pointer as well the even pointer as well so to do that Let's do let's start writing the question and first of all like you know this is a base condition or an H case condition for any linguist problem we should check if we even have a valid head Dot if it's a emptied linked list I just don't want to proceed further and I'll just simply return the head now as per explain I'm going to initialize my mod pointer to head and even pointer to head Dot next right now what I want to uh check is for example you know my even water is my the last point is uh or the after 0.2 the last point is uh or the after 0.2 which will be pointing to the last note which will be pointing to the last note for example if there is a single node for example if there is a single node only okay then there will be no even only okay then there will be no even want or node right want or node right or let's say we are moving ahead so our or let's say we are moving ahead so our node will always fall back off even node will always fall back off even right so what I'm going to do is go even right so what I'm going to do is go even like I'll check if my even node is valid like I'll check if my even node is valid yeah yeah even has one next Point that's only when even has one next Point that's only when you will be able to update your odd you will be able to update your odd pointer or linked list right pointer or linked list right and makes you know we discuss about this and makes you know we discuss about this condition what I'm going to do is r dot condition what I'm going to do is r dot next will now become even dot next next will now become even dot next and we're gonna update the power pointer and we're gonna update the power pointer similarly similarly even even dot next dot next will now become or dot next will now become or dot next and we will have data forward okay uh one more thing which I wanted like you know which I mentioned while describing the problem is I wanted to keep these uh sorted uh these odd and even lists separate so now we have the but to to unite them again we would need so basically this is a pointer to the so basically this is a pointer to the first node of the event list first node of the event list okay okay and at the last what we should do is and at the last what we should do is power dot next we will now point to power dot next we will now point to even point even point and now we can simply return our and now we can simply return our headquarters over here headquarters over here let's see uh if the test case is you let's see uh if the test case is you know it's passed know it's passed yep so test case it was passed yep so test case it was passed successfully let's submit the solution successfully let's submit the solution for rest okay so the submission uh you know so once you've got the solution got accepted successfully and I think we can optimize a bit Pro on this part on the solution but you know it got accepted so thanks everyone guys for watching the video and stay tuned for the upcoming ones thank | 2024-03-24 10:37:02 | 328 | Leetcode 328. Odd Even Linked List - Python Solution |
|
j_mQ_vRZyFY | from lead code and then solve it so I am picking a problem number 169 majority element so this problem is actually asked in Google Facebook and Amazon so let's go to lead code and see what exactly the problem States so if I take you to lead code majority element the problem says given an array of size n given an error numbers of size and return the majority element so let's read the description the majority element is an element that appears more than n by 2 times so if there is any element which appears more than half of the times it's considered to be a majority element and what we have to do is we have to return that particular element if and there is some more description given you may assume that the majority element always exists in an array so always there will be a there will be one element which will occur more than n by 2 times now if we just see the input so in this particular input you can see there are there is three two three but three has occurred twice so it's occurring more than half of the time so the output is 3. if I see another input you can see 2 has occurred four times and one has occurred three times since 2 has occurred more than half of the times output has to be now let's try solving this problem so now I have taken this array as an example now if You observe in this particular array there are seven elements so if there is any element which occurs more than seven by two times in this particular array that element can be considered to be the majority element and that has to be returned so if You observe this 8 has occurred four times so it has occurred more than seven by two times so definitely eight has to be the output so now let's see how we can approach towards the output so what is the logic that I would follow is I will pick any one element from this array and then other count the number of times that the element has occurred and if the number of times the element has occurred is greater than n by 2 I will return that if that's not the case I will check for another element so how to do this let's just Tempest so what I would do is in this particular array I will pick the first element so if I pick this first element I will Mark its index to be I so in the value of I is what 0. so I'll say I is equal to 0. next since I need to keep track of the count I need one more variable so I'll create one more variable named as count and at starting I will initialize the value to be 1 y 1 because I already found first occurrence of it next what is that I need to do is I need to check how many times it has occurred in the complete array since I picked this particular element in the zeroth index I need to check how many times 8 has occurred from index 1 till the last index so how do I do this definitely I need to check for this element is that equal to it next I need to check whether this is equal to it next I'll need to check whether this is equal to eight so basically I need to check for all the elements means I need to Traverse this so to Traverse this array I will pick one more variable and I'll name that variable to be J and it will start from index 1. now I have marked J to be index one next what I will do is I will check whether the element present in index J is that equal to the element present in index I no I won't do anything in case if it was true I will I would have increased the value of count next what I would do is I'll increase the value of J I'll check whether the element present in index J is equal to the element present in index I yes I'll increase the value of count the value of count becomes 2 and if You observe you have encountered it twice next I will increase the value of J I will check whether the element present in index J equal to the element present in index I no next I won't do anything I will go to the next index I'll check whether the element present in index J is equal to the element present in index I no I won't do anything next I will go to the next index that is index file is the element present in index J equal to the element present in index I yes so in this case I need to increase the value of count the value of count becomes 3. next again I will increase the value of J I'll check whether the element present in index 6 is that equal to the element present in index 0 that's index I yes it's equal I will increase the value of now if You observe the value of count has become 4 and if You observe the 8 has occurred four times so basically what I've done is I have traversed this particular array and checked whether the element present in index I is equal to the element present at index after doing this what I do is I will check whether the count value is greater than n by 2 times so how do I check I will simply write one if condition if count is greater than n but the length of the array divided by 2. if it is yes then I need to return a value and which is the value I need to return the value which has occurred this many number of times and which is that value that's nothing but 8. so how do I uh return it in a generic format so eight If You observe is present in index I so this is what you were checking for so what I need to return is I need to written a r of I so this is what I need to do now let's see this part now if you had observed the value of J actually started from index 1 and when till index 6. so how can I do I can simply write a for Loop where the value of J starts from I Value Plus 1 and then goes till length of this array inside this what I used to do I used to check whether the element present in index I is it equal to the element present in index J in case if it is true then I used to increase the value of count so I'll check that condition and increase the value of count so basically this is an algorithm but there is a problem in this algorithm the problem is this is not complete why it's not completed because in case if 8 was not the majority let's assume 5 was in this place and 8 was over here now the number of occurrences that you have got or the value of count that you would have got would have been one because you were checking for five now till the end you have not found the majority when you check this condition the condition is false so what is that you have to do simple you have to pick the next element and then check for the same so in case you have to pick for the next element don't you think you need to increase the value of I yes you need to increase the value of fine after that what should I do I need to check this element with all the other elements from index 2 to index X so basically again you are checking from index I plus 1 to this and for that I have already written the code over here in case if that's not the majority what is that I need to do I need to check for the next index so if I have to find for the next index again I have to increase the value of I and repeat the same operation if that's not the majority find the next index same way I need to go till the last so don't you think the same thing has to be repeated multiple number of times means I need to check the same thing for the value when the value of I is 0 next 1 next 2 next 3 in case if I don't find the majority so what I do is this whole code I'll be writing inside a loop and in that particular Loop the value of I would actually start from index 0 and go till the last index so how would I do that for I is equal to 0 to length of this particular array so this is an algorithm to find the majority element now let's go to lead code and write the code for this particular algorithm so now let's start writing code so if You observe there is a method named majority element it's accepting array named as nums so I will change that array name to be ar so that it's easy for me to type as well so I'll name it as AR and the return type is int so that's nothing but the element which has occurred majority of the times so basically what we did is we picked the uh picked one element at a time so what I need to do is I need to write one for Loop so I'll write for and I started from index 0. so the first element that I picked was from index 0 so I'll say int I is equal to 0. and in and I need to go till the last element so I will say I is less than a r dot length is less than a r dot length yes and in case if I don't find the element I need to go to the next element so basically I need to increase the value of I by 1 so I will say I plus plus I'll come inside this inside this what I need to do is since I'll pick the element present in index I now I need to keep track of its count so I need to create one variable count so I'll say int count is equal to I will initialize the value to be one so I will say count is equal to 1. next whichever element is present in ith index I need to check with all the other elements so I need to create one more Loop in within this so I'll say create one more Loop so I'll say for I'll name it as J int J is equal to now if You observe it should start from I plus 1 means from the next element so I'll say I Plus 1. and I need to check till the last uh element of the array so I will say J is less than a r dot length and then J plus plus and basically inside this what I am doing is I'm just checking if the element present in ith index equal to the element present in jet index so I will say if a r of I is equal to equal to a r of J so is a r of I equal to equal to yes now once I come out of this Loop it yes now once I come out of this Loop it means I have checked for the number of means I have checked for the number of times the element present in AR of I so times the element present in AR of I so what I would do is I'll check how many what I would do is I'll check how many what is the value of count is it greater what is the value of count is it greater than n by 2 how do I do that I will say than n by 2 how do I do that I will say if if value of count that's count value of count that's count is greater than is greater than n by 2 N is nothing but the number of n by 2 N is nothing but the number of elements present in this array are so elements present in this array are so I'll say a r dot length I'll say a r dot length divided by 2. yes if this is true then divided by 2. yes if this is true then it means to say the element present in it means to say the element present in index I is the majority element so I index I is the majority element so I need to return that element so I will need to return that element so I will say return say return the element present in AR of I so I'll the element present in AR of I so I'll say here of I and I'll do this say here of I and I'll do this and in case in case oh sorry they have and in case in case oh sorry they have told us very clearly you may assume that told us very clearly you may assume that the majority element always exist in an the majority element always exist in an array yes now what I do is I'll just run array yes now what I do is I'll just run this code once this code once so I'm running this code so it's so I'm running this code so it's checking so they're saying error missing checking so they're saying error missing return statement why it's showing me return statement why it's showing me this error is for a simple reason if I this error is for a simple reason if I just close this just close this so what has happened is I have written so what has happened is I have written if a return statement inside if if a return statement inside if condition let's assume the return condition let's assume the return statement never executes in that case statement never executes in that case there is no return statement outside the there is no return statement outside the loop so that's the problem so Java is loop so that's the problem so Java is saying you have to put one written saying you have to put one written statement outside the loop because you statement outside the loop because you have put this within if condition so I have put this within if condition so I will come out of the loop and simply I will come out of the loop and simply I will say return -1 will say return -1 I know for sure this is not going to I know for sure this is not going to execute but let's just put this now execute but let's just put this now we'll go and run the code so if I run the code yes it has been accepted so let's go and submit the code over here so if I submit the code it's still running so you can clearly see uh run time the milliseconds faster than 5 percent of java online submissions means I am faster than only five percent of the people so I am among the last five percent of the people means my solution is among the last five percent of the people why if you ask me because of its approach now if you ask me what is the time complexity of this approach the time complexity of this particular approach is Big O of n Square so this is not an efficient way of writing the code and in case if you go and write this particular code in Google or Facebook or Amazon they are definitely not going to shortlist you so we need to write a better approach or a better uh better solution which is better than big of n Square so is there a better solution yes there is which is that solution let's | 2024-03-21 14:01:44 | 169 | Find Majority Element ( LeetCode #169 ) Part-1 | FREE DSA Course in JAVA | Lecture 76 |
|
Evuj_jrnMFA | hey friends welcome back to my channel i'm here to do a hundred lethal i'm here to do a hundred lethal challenge challenge today's we have 118 pascal's triangle today's we have 118 pascal's triangle so for this question like this so for this question like this triangle demo looks giving a non triangle demo looks giving a non negative integers num rows generates negative integers num rows generates the first num rows of pascal's triangle the first num rows of pascal's triangle and it starts on one and then later and it starts on one and then later you another one one and one you another one one and one after one and one so it will be three after one and one so it will be three num row b3 num row b3 and f3 this middle one will add and f3 this middle one will add one and one just like a triangle one and one just like a triangle just keep adding each other but to solve this one i take some time but to solve this one i take some time to think about the to think about the method which is not really looking method which is not really looking like this i can show you in like this i can show you in here as a test so you start with one here as a test so you start with one so you do nothing because it's beginning so you do nothing because it's beginning the second row you still do nothing the second row you still do nothing you can see in here they have an empty area in here look wait for a second see here see you have the end and this is the thing that you need to feel and the rest of them on the side is all one so see the first top two rows you don't need to do anything but we start doing things in this area which is in row three how we do is we copy one and one from this row so it looks like this and so it looks like this and this two is equal to one plus one this two is equal to one plus one but you can think about uh the cases but you can think about uh the cases these two is at one and one here and these two is at one and one here and this one and one this one and one actually is moved to this area but we actually is moved to this area but we just add one in here just add one in here just to push back so to align them just to push back so to align them and this one is equal to current index and this one is equal to current index which is here which is here plus the next index plus the next index so you will get two so this one will be equal to two if this next one we'll have one two one or this original one and we have the plus one in the beginning so starting from this one the first number at this one is equal to one plus two one plus two actually is here which is one at is next number becomes three and in here at x two's next number is just one so become three in here so we only process a number between the first one and the last one then this is the solution and if we need to do n rows time until we reach the end of yeah and rows that's it for this logic comment this now we have to make a template this is our output template this is our output template and we need to use a list to keep track and we need to use a list to keep track of the current situation let's record two new we will loop and in here first we need to do first and in here first we need to do first thing we need to do thing we need to do is a curve we start with one every time we have a loop we will add one at index one so that currently curve is empty we have to put currently curve is empty we have to put one in here one in here so every time we have every row we go we so every time we have every row we go we start putting a one in the beginning for everything between the first one and the last one we need to process something which is this is this is everything between this is this is everything between ones and one and what we need to do is ones and one and what we need to do is set x equal to curve x equal to curve got x got x and x plus one and x plus one after that after you process that one after that after you process that one and you just simply and you just simply put it to the output to the output and that should collect all the possibility and in every row and the end we should return output as a okay it looks good let's submit it okay yeah it passed so yeah this is the solution so if you have any question please comment down and i will see you in the next video | 2024-03-21 11:00:34 | 118 | Leetcode 118 - Pascal's Triangle (Java, Solution Explained) |
|
_xyCXHzJ5U8 | 240 search a 2d matrix number two from liquid let's jump to the question and liquid let's jump to the question and write an efficient algorithm that write an efficient algorithm that searches for a value target in an m by n searches for a value target in an m by n integer matrix this matrix has the integer matrix this matrix has the following properties so first in first following properties so first in first each row are sorted in ascending from each row are sorted in ascending from left to right and each column are sorted left to right and each column are sorted in ascending from top to bottom so this in ascending from top to bottom so this is a sorted is a sorted matrix that we are going to have and we matrix that we are going to have and we have a target value that we need to look have a target value that we need to look for and if we can find the target value for and if we can find the target value in the matrix figure are going to return in the matrix figure are going to return true otherwise we are going to return true otherwise we are going to return false uh so the first thing that comes false uh so the first thing that comes to my mind is using a brute force we use to my mind is using a brute force we use two for loops and two for loops and iterate over every single item that we iterate over every single item that we have in this matrix but it's going to be have in this matrix but it's going to be the quadratic time complexity and the the quadratic time complexity and the other thing is we are not using the other thing is we are not using the properties that is given here to us and properties that is given here to us and which is like each row is sorted and which is like each row is sorted and each column is sorted so we should use each column is sorted so we should use this and for doing that what we can do this and for doing that what we can do we can uh you we can use two pointers we can uh you we can use two pointers one pointer is pointing at the bottom one pointer is pointing at the bottom row and one pointer is pointing at the row and one pointer is pointing at the first column the reason that we start first column the reason that we start from here not here is because like we from here not here is because like we are are you looking for a target value right so you looking for a target value right so if the target value if the target value is a smaller than these so we can easily is a smaller than these so we can easily eliminate this row right eliminate this row right but if the target if you start we start but if the target if you start we start from here if the target value is bigger from here if the target value is bigger than these than these um we don't know it can be any of these um we don't know it can be any of these rules so we cannot eliminate anything rules so we cannot eliminate anything but by starting from the bottom but by starting from the bottom it can help us to eliminate uh some of it can help us to eliminate uh some of the rows and the rows and hopefully have less iteration and uh so hopefully have less iteration and uh so let's go through the let's go through the code and see how we can do this so code and see how we can do this so the target value that we are looking for the target value that we are looking for is 12 and this is the matrix that is is 12 and this is the matrix that is given to us first thing we are going to given to us first thing we are going to um have the special cases if there is no um have the special cases if there is no matrix or like um we don't like the matrix or like um we don't like the length of rows or columns are zero so length of rows or columns are zero so we're gonna return false because there we're gonna return false because there is no matrix to look for a target and is no matrix to look for a target and then we are going to use two pointers then we are going to use two pointers one pointer is pointing at one pointer is pointing at [Music] [Music] the last row as you see here and one the last row as you see here and one pointer is pointing at the pointer is pointing at the first column as you see here and we use first column as you see here and we use a while loop and we decide how to um a a while loop and we decide how to um a small scope of search by the value that small scope of search by the value that we are we are pointing at so if the value that we are pointing at so if the value that we are pointing at is equal to target we're pointing at is equal to target we're just gonna return that this is the first just gonna return that this is the first if and the second condition says if this if and the second condition says if this value is bigger than the target which it value is bigger than the target which it is bigger than the target in this case is bigger than the target in this case 18 is bigger than 12. we're just gonna 18 is bigger than 12. we're just gonna like eliminate this row and we decrease like eliminate this row and we decrease um the row value from like let's say um the row value from like let's say this is zero one two three four from this is zero one two three four from four to three so we're gonna point at uh four to three so we're gonna point at uh this row and uh what we are going to do this row and uh what we are going to do uh we uh we go to check to see if row value is um go to check to see if row value is um bigger than zero a column value is bigger than zero a column value is smaller than the length of the matrix smaller than the length of the matrix and if it is we are going to check the and if it is we are going to check the value that we have here right now is um value that we have here right now is um equal to target which is not equal to equal to target which is not equal to target target so what they're going we are going to so what they're going we are going to check if the check if the at row 3 and column 0 the value that we at row 3 and column 0 the value that we have which is 10 is equal to 12 and it have which is 10 is equal to 12 and it is not or we're gonna see if 10 is is not or we're gonna see if 10 is bigger than 12 which is not so we are bigger than 12 which is not so we are going to add the column number here so going to add the column number here so now the column pointer is pointing at now the column pointer is pointing at this number this number and then we are going to check if 13 is and then we are going to check if 13 is equal which is not if it is bigger it is equal which is not if it is bigger it is bigger and if it is bigger we are going bigger and if it is bigger we are going to um to um decrease one from the row so we are decrease one from the row so we are going to row number two but the column going to row number two but the column number still is pointing at one as you number still is pointing at one as you see here see here and now we check two and um and now we check two and um index two and one and we see the value index two and one and we see the value is smaller so we're gonna add the column is smaller so we're gonna add the column so now column is pointing at um so now column is pointing at um index two and row index two so nine and index two and row index two so nine and nine is a smaller so still we're gonna nine is a smaller so still we're gonna like increase the column number so now like increase the column number so now the column number is going to be three the column number is going to be three and row is going to be two and we check and row is going to be two and we check this value if it is bigger yes it is this value if it is bigger yes it is bigger so what we're going to do we are bigger so what we're going to do we are going to decrease the going to decrease the row value so now it's going to be one row value so now it's going to be one and now we are going to check at row one and now we are going to check at row one and column three which is 12 and that's and column three which is 12 and that's the number that we were looking for so the number that we were looking for so it's equal to target and we are going to it's equal to target and we are going to return true and this is how we solve it return true and this is how we solve it and it's going to be there at worst case and it's going to be there at worst case it's going to be m it's going to be m plus n m is the number of rows and n is plus n m is the number of rows and n is a number of columns so we iterate over a number of columns so we iterate over every single item and the space every single item and the space complexity is going to be one because we complexity is going to be one because we are not using are not using any extra space thank you | 2024-03-22 11:39:15 | 240 | LeetCode Q 240: Search a 2D Matrix II |
|
hIQLVBeZe3Q | today we are looking at lead code number 261 261 it's called graph valid tree it's called graph valid tree all right so let's take a look at the all right so let's take a look at the prompt here given n nodes labeled from 0 prompt here given n nodes labeled from 0 to n to n minus 1 and a list of undirected edges minus 1 and a list of undirected edges each edge is a pair of nodes write a each edge is a pair of nodes write a function to check whether these edges function to check whether these edges make up make up a valid tree okay so we have example one a valid tree okay so we have example one n is five the edges are zero and one n is five the edges are zero and one zero and two zero three one and four zero and two zero three one and four the output is true example two and it's the output is true example two and it's five five the edges are zero one one and two two the edges are zero one one and two two and three one three one four and three one three one four okay we have a note here you can assume okay we have a note here you can assume that there's no duplicate edges that there's no duplicate edges since all edges are undirected and the since all edges are undirected and the same as 1 and 0 same as 1 and 0 thus will not appear together in edges thus will not appear together in edges okay so okay so right off the bat what we got to figure right off the bat what we got to figure out out is what is a tree is what is a tree what is the definition of a tree okay what is the definition of a tree okay and so the definition of a tree is is and so the definition of a tree is is that it is a graph that it is a graph but it cannot have cycles the only but it cannot have cycles the only difference between a tree and a graph is difference between a tree and a graph is that a tree does not have that a tree does not have cycles so first we got to fig we have to cycles so first we got to fig we have to convert these inputs convert these inputs into a graph okay we can do an adjacency into a graph okay we can do an adjacency matrix or an adjacency list matrix or an adjacency list i think if we do an adjacency list we i think if we do an adjacency list we can easily traverse this can easily traverse this this input and figure out if there's any this input and figure out if there's any cycles cycles in the input so that's number one in the input so that's number one number two is is that there cannot be number two is is that there cannot be more than one more than one region okay so let's region okay so let's let's kind of visualize this let's kind of visualize this if we have zero if we have zero let me use a different color here okay if we have zero and then we have one and then we have two and three and then we have four here this is not a valid tree okay because we do have we do have a tree here but we cannot have more than one region so this will not be valid likewise if it was just a connection from this one to this four this would be a valid tree okay but if we have a connection here between this two and three then we have a cycle here and that will not be a valid tree okay so what we want with this with and regions are less than there cannot be more than one region more than one region if we can have these two elements checked and the graph has no cycles and there's only one region then we can assume that our input is indeed a valid tree okay so let's let's jump into this and what we want to do here is right off the bat when we see this okay we're getting a list of edges and an input of n so we're getting an edge list we want to just first convert this convert this into an adjacency list that way we can just easily traverse this and we don't have to think too much about it okay so i'm going to just create a helper function here build adjacency list that takes in okay now i'm going to actually create my okay now i'm going to actually create my array that i'm going to use array that i'm going to use that's going to represent the adjacency that's going to represent the adjacency list from and then here we're going to do a length of n and we're going to set every element in the array in this adjacency list to an empty array and this is a brand new array that's mapped to its own specific place in memory okay we have length here and now what we're going to do is just iterate over and we're going to pull out the source and we're going to pull out the source and the destination of our and the destination of our of our edge of our edge so the index 0 is going to be our source so the index 0 is going to be our source and the index of 1 is going to be our and the index of 1 is going to be our destination we're just pulling those out destination we're just pulling those out here as we iterate here as we iterate over these edges right over here and over these edges right over here and we're just going to map that to we're just going to map that to our adjacency list and because this is an undirected graph we're going to mirror this so as we push in the destination of the source we have to mirror it at the destination we have to also push and then we just go ahead and return and then we just go ahead and return our adjacency list okay and so in the first part of this main function the first thing we're going to do is list list build adjacency list build adjacency list and and edges and and edges now for this main main function now for this main main function we have to create some variables to keep we have to create some variables to keep track of the nodes that we're visiting track of the nodes that we're visiting as we traverse so we're going to have a as we traverse so we're going to have a visited object set it to an empty object and we're going to also have a parent object we want to keep track of and then we need a region so we want to keep track of everything so we want to keep track of everything that we're visiting so we don't visit that we're visiting so we don't visit anything twice anything twice but we also want to keep track of the but we also want to keep track of the parent of every node that we're visiting parent of every node that we're visiting and the reason we want to do that is and the reason we want to do that is that is going to help us determine that is going to help us determine whether we have a cross edge and that's whether we have a cross edge and that's the key to this we have to figure out the key to this we have to figure out does this graph have a cross edge if does this graph have a cross edge if there's a cross there's a cross edge that means that there is a cycle edge that means that there is a cycle and and if you're still unclear about the if you're still unclear about the different edge classifications i highly different edge classifications i highly suggest suggest reading the chapter on graphs in reading the chapter on graphs in introduction to algorithms introduction to algorithms it's that giant book you can find it it's that giant book you can find it online online and there's a section in there for edge and there's a section in there for edge classifications you can have forward classifications you can have forward edges edges backward edges cross edges backward edges cross edges and it's really really important to know and it's really really important to know those different edges and those different edges and and how to how to figure out whether and how to how to figure out whether your graph has those or not your graph has those or not okay so we'll just create our main loop okay so we'll just create our main loop here equals zero next is less than you can see the list vertex plus plus okay and this is all like just basically off a very basic graph traversal template i'm not doing anything anything new here and if you look at a lot of my other videos i just follow the same template in the same pattern and it's good to have those in your back pocket because then when you see these problems you can really quickly solve them you don't have to think too much so here we can check then we want to go ahead and first we then we want to go ahead and first we want to go want to go ahead and increment the regions because ahead and increment the regions because that means that we have a region and now we want to check is there more than one region remember if there's more than one region then we do not have a tree and so we want to exit out of this so we can say if regions is greater than 1 return false and now we just have to check is we'll cycle vertex if there's a cycle from this vertex node that means that we we do not have a tree and we're going to also return false and then if we make it through this entire loop and there's no cycles and there's only one region then we can assume that our input is indeed a valid tree okay so now we just have one more function is we have to create this bfs cycle and we're just making a slight modification and we're adding this parent in there that's going to help us determine is b fs is b fs cycle this takes in a node cycle this takes in a node our adjacency list our adjacency list visited and our parent okay now remember anytime we're dealing with a breadth first search algorithm we want to use a queue okay so we're going to go ahead and create our queue and we'll go ahead and set that node that vertex as the as the element in the queue and now we want to create a while loop and while we want to keep on iterating over this cube and pulling nodes out of the queue while they're while we have elements in that queue so q.length while we have a q.length we're going to go ahead and pull out that node we're going to shift out that node okay we want to update our visited and we'll set that to true that way we don't repeat visited nodes that we've already been to and now we want to iterate over all the neighbors we're doing a breadth-first search so we want to check all the neighbors okay and now we want to check have we okay and now we want to check have we been to this neighbor before been to this neighbor before now we only want to go into this if we now we only want to go into this if we have not been into this neighbor so we have not been into this neighbor so we check check if visited of if visited of neighbor if it's false that means we neighbor if it's false that means we have not visited we want to update have not visited we want to update visited okay and now we want to update the parent is going to equal the ker node is going to equal the ker node and then we want to add that neighbor to and then we want to add that neighbor to our q okay now we need to check is there a cross edge okay and how do we do that well we have to check does the neighbor and the parent of the current node if they do not equal each other then we can assume that there is a cross edge so if parent of per node okay else we return okay else we return false and false and again this is the main part of it right again this is the main part of it right here this here this lets us know whether we have a cross lets us know whether we have a cross edge or not edge or not if this is true then we do have a cross if this is true then we do have a cross edge and we want to go ahead and return edge and we want to go ahead and return true okay that means that this bfs does true okay that means that this bfs does have indeed have a cycle and what i have indeed have a cycle and what i would recommend is that would recommend is that if you're not sure how this works step if you're not sure how this works step through the code through the code make a little chart draw it out each make a little chart draw it out each iteration by iteration iteration by iteration use a simple graph like the input you use a simple graph like the input you know three or four nodes know three or four nodes and go through each one to really give and go through each one to really give yourself an idea of how yourself an idea of how this line right here works okay so let's go ahead and run this and and we are good okay so that is valid tree i hope you enjoyed it and i | 2024-03-22 12:18:28 | 261 | LEETCODE 261 (JAVASCRIPT) | GRAPH VALID TREE |
|
UbyhOgBN834 | everyone welcome back and let's write some more neat code today so today let's some more neat code today so today let's solve the problem permutation in a solve the problem permutation in a string and there's actually two string and there's actually two solutions to this problem one is the 26 solutions to this problem one is the 26 times n solution and there's another times n solution and there's another solution that's actually just big o of n solution that's actually just big o of n now we know that a constant number here now we know that a constant number here doesn't actually affect the overall time doesn't actually affect the overall time complexity but that being said i'm still complexity but that being said i'm still going to focus on the slightly more going to focus on the slightly more optimal solution uh because it's a optimal solution uh because it's a little bit more difficult but it's also little bit more difficult but it's also interesting and it's a pattern that's interesting and it's a pattern that's actually used in other leak code actually used in other leak code problems as well so we're given two problems as well so we're given two strings s1 and s2 and all we want to do strings s1 and s2 and all we want to do is return true if the string s2 contains is return true if the string s2 contains a permutation of s1 and we return false a permutation of s1 and we return false if that's not the case now you can get if that's not the case now you can get bogged down and really confused with the bogged down and really confused with the explanation of this problem like explanation of this problem like focusing a ton on permutations but i'm focusing a ton on permutations but i'm going to try to simplify this for you going to try to simplify this for you immediately without going down too many immediately without going down too many rabbit holes and let's actually take a rabbit holes and let's actually take a look at this first example so we see look at this first example so we see that s1 is the target string that's what that s1 is the target string that's what we're trying to look for we're looking we're trying to look for we're looking for a permutation of this string for a permutation of this string somewhere inside of s2 can we find it somewhere inside of s2 can we find it now what does permutation mean well we now what does permutation mean well we could actually you know create a could actually you know create a permutation of the string which would be permutation of the string which would be really complex and annoying really complex and annoying but we see that over here there actually but we see that over here there actually is a substring of s2 and it's a is a substring of s2 and it's a permutation that matches s1 it's ba permutation that matches s1 it's ba right the exact same characters just in right the exact same characters just in a different order which is perfectly a different order which is perfectly fine now by the way a b itself fine now by the way a b itself technically counts as a permutation of technically counts as a permutation of itself so this string is also allowed itself so this string is also allowed but since you kind of see what we're but since you kind of see what we're really just looking for is is there a really just looking for is is there a substring of the exact same size so this substring of the exact same size so this is two characters so we have to look for is two characters so we have to look for a substring of two characters here right a substring of two characters here right we can't just take three characters and we can't just take three characters and say that that's the permutation but you say that that's the permutation but you know we're looking for a window same know we're looking for a window same size as this and it has to contain the size as this and it has to contain the exact same characters as s1 just maybe exact same characters as s1 just maybe in a different order now does that kind in a different order now does that kind of sound familiar to you well it's the of sound familiar to you well it's the same thing as looking for an anagram same thing as looking for an anagram right we're just looking for the exact right we're just looking for the exact same characters we don't care about what same characters we don't care about what order they're in right so it's looking order they're in right so it's looking for an anagram so we can actually use a for an anagram so we can actually use a typical sliding window technique we're typical sliding window technique we're going to look at every window in s2 going to look at every window in s2 that's the exact same size as s1 so in that's the exact same size as s1 so in this case length 2. so we're going to this case length 2. so we're going to look at the first two characters then look at the first two characters then the next two characters the next two etc the next two characters the next two etc etc until we find an exact match with s1 etc until we find an exact match with s1 now if we were actually comparing the now if we were actually comparing the exact characters that would be pretty exact characters that would be pretty annoying the time complexity in that annoying the time complexity in that case would let's say be n times m where case would let's say be n times m where n is the size of s2 m is the size of s1 n is the size of s2 m is the size of s1 because we're looking at every single because we're looking at every single window but we can do it a little bit window but we can do it a little bit better we can reduce it to be 26 times n better we can reduce it to be 26 times n if we use a hash map because actually in if we use a hash map because actually in this problem it's written all the way at this problem it's written all the way at the bottom of the description so it's the bottom of the description so it's not on screen but they tell us that all not on screen but they tell us that all the characters in both of the strings the characters in both of the strings are going to be limited to lowercase a are going to be limited to lowercase a through lowercase z so therefore the through lowercase z so therefore the size of our hashmap is going to be at size of our hashmap is going to be at most size 26. there's only 26 characters most size 26. there's only 26 characters so as we build that hash map we're so as we build that hash map we're actually going to have two hash maps actually going to have two hash maps we're going to have one hash map for s1 we're going to have one hash map for s1 which is going to stay the exact same which is going to stay the exact same we're also going to have a second hash we're also going to have a second hash map for s2 which is going to have the map for s2 which is going to have the characters of the current window that characters of the current window that we're at so every time we create a we're at so every time we create a window right each time we shift our window right each time we shift our window to the right we're only just window to the right we're only just adding one character and maybe removing adding one character and maybe removing the character that was on the left and the character that was on the left and then once we have those two hash maps then once we have those two hash maps we're going to compare them if they are we're going to compare them if they are equal which is a 26 operation right equal which is a 26 operation right there's only 26 characters and so that's there's only 26 characters and so that's where we get this time complexity from where we get this time complexity from but there actually is a better way this but there actually is a better way this solution is doable it's easy to code up solution is doable it's easy to code up and you can do so if you would like but and you can do so if you would like but i'm going to show you the slightly more i'm going to show you the slightly more optimal solution which is actually not optimal solution which is actually not even going to have this 26 it's just even going to have this 26 it's just gonna be big o of n so let's look at the gonna be big o of n so let's look at the big o of n solution and it's actually big o of n solution and it's actually similar to the previous solution we similar to the previous solution we discussed we're actually going to still discussed we're actually going to still have two hash maps one for s1 so as you have two hash maps one for s1 so as you can see we counted the occurrences of can see we counted the occurrences of each character we call it s1 count so we each character we call it s1 count so we have one a we have one b and one c so we have one a we have one b and one c so we filled our hash map with the same values filled our hash map with the same values and rs2 hash map is empty because first and rs2 hash map is empty because first we're going to set our window here and we're going to set our window here and then we're going to continue to shift it then we're going to continue to shift it by one each time but the difference here by one each time but the difference here is we're not actually going to be is we're not actually going to be comparing the two hash maps together we comparing the two hash maps together we won't need to because we're going to won't need to because we're going to keep track of one more variable we're keep track of one more variable we're going to call it matches going to call it matches we're basically going to have a little we're basically going to have a little shortcut initially this is going to be shortcut initially this is going to be set to zero i'll just create a box for set to zero i'll just create a box for it even though it's just going to be a it even though it's just going to be a single single value but we might be updating it to value but we might be updating it to other values but this matches variable other values but this matches variable is basically going to be a shortcut is basically going to be a shortcut that's going to allow us to not have to that's going to allow us to not have to compare the entire hash maps each time compare the entire hash maps each time which we know in the worst case could be which we know in the worst case could be a 26 operation having to look through a 26 operation having to look through every single character of the hashmaps every single character of the hashmaps because this matches variable is because this matches variable is actually gonna maintain the total number actually gonna maintain the total number of equal characters in each of these of equal characters in each of these hash maps and actually even though i hash maps and actually even though i didn't draw the entire didn't draw the entire map for s1 and s2 in this case because map for s1 and s2 in this case because actually we know that there's a through actually we know that there's a through z there's 26 characters and i didn't z there's 26 characters and i didn't actually draw the entire thing but we actually draw the entire thing but we are gonna are gonna you know fill in the values in the code you know fill in the values in the code because we know that the rest of the because we know that the rest of the characters in s1 are gonna be of count characters in s1 are gonna be of count zero right and matches is gonna tell us zero right and matches is gonna tell us the exact number of matches of each the exact number of matches of each character between the two hash maps so character between the two hash maps so we want to know does we want to know does the a count of s1 and of s2 match if it the a count of s1 and of s2 match if it does match then that's a plus one if it does match then that's a plus one if it doesn't match then that's not a plus one doesn't match then that's not a plus one right and we want to know the number of right and we want to know the number of matches for every single character and matches for every single character and we want to know that initially right it we want to know that initially right it could be 26 matches or it could be zero could be 26 matches or it could be zero matches right it could be any value in matches right it could be any value in between but once we have 26 matches that between but once we have 26 matches that means that for some window in s2 and by means that for some window in s2 and by looking at it we know that this is going looking at it we know that this is going to be the window we know that this to be the window we know that this window has 26 matches with this window window has 26 matches with this window because they both have a single a because they both have a single a character a single b character a single character a single b character a single c character and for the other remaining c character and for the other remaining 23 characters they have 23 characters they have they both have zero of those characters they both have zero of those characters so therefore they have 26 matches that's so therefore they have 26 matches that's what we care about and we can do that what we care about and we can do that with a single variable without having to with a single variable without having to look through the entire hashmap let me look through the entire hashmap let me show you the algorithm to do that it's show you the algorithm to do that it's pretty straightforward actually so first pretty straightforward actually so first thing we're going to do is actually just thing we're going to do is actually just look at the first three characters of s2 look at the first three characters of s2 and then fill up our hash map so we have and then fill up our hash map so we have a single b we have a single a and we a single b we have a single a and we have a single x now you can see that have a single x now you can see that this is what our hash maps actually look this is what our hash maps actually look like we have looked at the first three like we have looked at the first three characters and now what we're actually characters and now what we're actually going to do for the only time we are going to do for the only time we are actually going to iterate through both actually going to iterate through both of these hash maps comparing each of these hash maps comparing each character we actually do have to do that character we actually do have to do that at least one time but it's a single 26 at least one time but it's a single 26 operation so and then after that we'll operation so and then after that we'll only have to just iterate through this only have to just iterate through this string so the overall time complexity is string so the overall time complexity is going to be n plus 26 which we know is going to be n plus 26 which we know is going to be equal to big o of n uh it's going to be equal to big o of n uh it's it's definitely better than if we were it's definitely better than if we were just doing 26 times n okay so we're just doing 26 times n okay so we're gonna look at every character a they gonna look at every character a they both have one a they both have one b both have one a they both have one b s one has a single c s one has a single c but s two does not have any c's so but s two does not have any c's so therefore they have two matches a and b therefore they have two matches a and b but c is not a match then we're going to but c is not a match then we're going to look at all the other characters after c look at all the other characters after c and we're actually going to see that yes and we're actually going to see that yes there is a match there is a match right because they both have zero d's right because they both have zero d's they both have zero e's they have zero they both have zero e's they have zero f's etc etc but then we're going to get f's etc etc but then we're going to get to x okay to x okay this has a single x but s1 does not have this has a single x but s1 does not have any x's that's not a match but they both any x's that's not a match but they both have zero y's and zero z's so all in all have zero y's and zero z's so all in all they actually matched every single they actually matched every single character except for c and except for x character except for c and except for x those were the only characters they those were the only characters they didn't match so actually initially we didn't match so actually initially we have 24 matches next we're gonna look have 24 matches next we're gonna look we're gonna take our window which was we're gonna take our window which was like this and we're gonna shift it to like this and we're gonna shift it to the right by one when we shift it we're the right by one when we shift it we're obviously removing a character from the obviously removing a character from the s2 window we're removing a b now as we s2 window we're removing a b now as we make changes to the count we want to make changes to the count we want to know does it affect the number of know does it affect the number of matches so here we have one right which matches so here we have one right which was equal to what it was supposed to be was equal to what it was supposed to be in s1 as well but now we're now changing in s1 as well but now we're now changing it to a zero so therefore it's not it to a zero so therefore it's not matching with what it previously was matching with what it previously was matching with therefore our matches matching with therefore our matches total is actually going to be updated total is actually going to be updated now to be 23 we're decrementing it by now to be 23 we're decrementing it by one okay but we also added a character a one okay but we also added a character a y does this affect our matches was this y does this affect our matches was this a character we were looking for well a character we were looking for well let's increment our i by one and we see let's increment our i by one and we see that now it's one but what was the y that now it's one but what was the y value in s1's count it was equal to 0 so value in s1's count it was equal to 0 so now we actually created another mismatch now we actually created another mismatch so actually the total number of matches so actually the total number of matches is gonna be 22 now and now we're going is gonna be 22 now and now we're going to actually shift one more time so this to actually shift one more time so this a is no longer gonna be in our window a is no longer gonna be in our window now we're gonna have x y z in our window now we're gonna have x y z in our window so we remove the a a count is now gonna so we remove the a a count is now gonna be set to zero we created another be set to zero we created another mismatch so our matches count is now mismatch so our matches count is now gonna be 21 but we added a z so gonna be 21 but we added a z so our z count is one but the z count in s1 our z count is one but the z count in s1 is zero therefore we created another is zero therefore we created another mismatch so now our total number of mismatch so now our total number of matches is actually going to be 20. now matches is actually going to be 20. now let's shift our window one more time let's shift our window one more time let's chop off this x so x count is now let's chop off this x so x count is now going to be set to zero so let's update going to be set to zero so let's update that x count is now set to zero which is that x count is now set to zero which is good for us because s1's x count was good for us because s1's x count was also zero so therefore we can actually also zero so therefore we can actually increment our number of matches now increment our number of matches now right so let's uh set matches now equal right so let's uh set matches now equal to 21. we also added a character we to 21. we also added a character we added this a character at the top so added this a character at the top so let's actually increment the number of let's actually increment the number of a's we went from having zero a's to now a's we went from having zero a's to now having one a and that's what we were having one a and that's what we were looking for right because one a is also looking for right because one a is also found in s1 count so now we can found in s1 count so now we can increment our number of matches from 21 increment our number of matches from 21 to b22 we're getting closer to our goal to b22 we're getting closer to our goal and i'm gonna kind of fast forward the and i'm gonna kind of fast forward the remaining two spots clearly we're gonna remaining two spots clearly we're gonna see that the y gets chopped off and then see that the y gets chopped off and then we're gonna be two we're gonna add the b we're gonna be two we're gonna add the b character which is also what we wanted character which is also what we wanted to do right we have one b and we have to do right we have one b and we have zero y's so that brings us to be 24 zero y's so that brings us to be 24 matches and then we're gonna shift one matches and then we're gonna shift one more time uh to be at this last window more time uh to be at this last window we're gonna get rid of the z that we we're gonna get rid of the z that we that we didn't really need so now our that we didn't really need so now our number of z's is zero that's good that's number of z's is zero that's good that's exactly what we want and we added a c exactly what we want and we added a c character so now we have one c now we character so now we have one c now we have the exact number of matches we were have the exact number of matches we were looking for that our matches count is looking for that our matches count is going to be 26 whenever we get to 26 going to be 26 whenever we get to 26 matches that's our magic number we are matches that's our magic number we are going to go ahead and stop the algorithm going to go ahead and stop the algorithm and return true because all we're and return true because all we're looking for is does there exist a single looking for is does there exist a single permutation of this in s2 or in other permutation of this in s2 or in other words does there exist an anagram of s1 words does there exist an anagram of s1 and there does we found it we return and there does we found it we return true immediately and we can stop the true immediately and we can stop the algorithm that's the big o of end time algorithm that's the big o of end time algorithm now let's actually code it up algorithm now let's actually code it up okay now let's write the code but okay now let's write the code but there's just one little edge case we there's just one little edge case we actually have to look for that i didn't actually have to look for that i didn't talk about previously and that's if our talk about previously and that's if our s1 string is actually shorter or s1 string is actually shorter or actually rather longer than our s2 actually rather longer than our s2 string string which would make it impossible for us to which would make it impossible for us to find a permutation of s1 in s2 in that find a permutation of s1 in s2 in that case we can just return false case we can just return false immediately but after that we can get immediately but after that we can get into our standard algorithm even though into our standard algorithm even though i was talking about hashmaps we can i was talking about hashmaps we can actually implement these with arrays as actually implement these with arrays as well because we are getting fixed values well because we are getting fixed values uh lowercase a through lowercase z and uh lowercase a through lowercase z and we can convert those characters to be we can convert those characters to be uh integers and we can use those uh integers and we can use those integers as indices indexes of our two integers as indices indexes of our two arrays so initially i'm just going to arrays so initially i'm just going to set these to be 26 set these to be 26 numbers and each of those numbers is numbers and each of those numbers is just going to be a 0 for now uh we're just going to be a 0 for now uh we're going to go through every character in going to go through every character in s1 and we're gonna go so suppose s1 is s1 and we're gonna go so suppose s1 is maybe three characters long at the same maybe three characters long at the same time as we're going through s1 we're time as we're going through s1 we're also going to go through the first let's also going to go through the first let's say three characters of s2 so we're say three characters of s2 so we're going to initialize both of these hash going to initialize both of these hash maps at the same time so let's do that maps at the same time so let's do that now so the way we're going to convert now so the way we're going to convert these characters so in s1 we're going to these characters so in s1 we're going to get the character at the ith indexed and get the character at the ith indexed and we're going to use the ord function now we're going to use the ord function now depending on your language it might be a depending on your language it might be a different function all we're doing is different function all we're doing is getting the ascii value of this getting the ascii value of this character with our ord function and character with our ord function and we're going to subtract from it the we're going to subtract from it the ascii value of lowercase ascii value of lowercase lowercase a let's get this right and lowercase a let's get this right and this will map to an index this will map this will map to an index this will map to one of the 26 indexes and to this all to one of the 26 indexes and to this all we want to do is just add one to it and we want to do is just add one to it and i'm just going to go ahead and copy and i'm just going to go ahead and copy and paste this line and do the exact same paste this line and do the exact same thing for s2 we're gonna in s2 count uh thing for s2 we're gonna in s2 count uh we're going to update the count of this we're going to update the count of this character and just increment it by one character and just increment it by one so now before we actually get to our so now before we actually get to our sliding window portion don't forget we sliding window portion don't forget we actually have to initialize the number actually have to initialize the number of matches we're initially going to set of matches we're initially going to set it to zero but let's compare it to zero but let's compare each of these maps or arrays we know each of these maps or arrays we know that there's going to be 26 spots in the that there's going to be 26 spots in the array so we can actually just hard code array so we can actually just hard code that so now we're going to say that so now we're going to say to the number of matches we want to add to the number of matches we want to add one to it only if one to it only if s1 count at index i is equal to s2 count s1 count at index i is equal to s2 count at index i that's the only case where at index i that's the only case where we'd want to increment this by 1 but if we'd want to increment this by 1 but if that's not the case then we are not that's not the case then we are not going to increment it by one so we can going to increment it by one so we can just say else zero right so else just say else zero right so else incremented by zero which is the same as incremented by zero which is the same as not incrementing it at all let's put not incrementing it at all let's put parentheses here just to clean it up and parentheses here just to clean it up and now we can move on so now we're going to now we can move on so now we're going to do the sliding window portion we're to do the sliding window portion we're to initialize a left pointer to be at the initialize a left pointer to be at the beginning so at index uh beginning so at index uh 0. so then we're going to have our right 0. so then we're going to have our right pointer which is actually going to pointer which is actually going to iterate through every position in s2 iterate through every position in s2 but we know we don't actually have to but we know we don't actually have to start at the first position because we start at the first position because we already initialized our windows so we're already initialized our windows so we're actually going to start at the length of actually going to start at the length of 1 the length of s1 because this will 1 the length of s1 because this will start us at the next character that we start us at the next character that we left off at right and this and this left off at right and this and this range is actually non-inclusive so we range is actually non-inclusive so we stopped before we reached this index so stopped before we reached this index so now we're actually going to go to that now we're actually going to go to that index with our right pointer but index with our right pointer but remember what happens if matches is 26 remember what happens if matches is 26 shouldn't we return immediately yeah we shouldn't we return immediately yeah we can put a return statement outside of can put a return statement outside of this for loop but it'll be redundant so this for loop but it'll be redundant so we can actually put it as the first we can actually put it as the first statement inside of the for loop so statement inside of the for loop so basically if matches is equal to 26 then basically if matches is equal to 26 then we are returning true if that ever we are returning true if that ever happens we can immediately return true happens we can immediately return true no questions asked but if it's not the no questions asked but if it's not the case then we have to update the number case then we have to update the number of matches we know that we just visited of matches we know that we just visited a character at index r and this is the a character at index r and this is the part where you actually might have hoped part where you actually might have hoped that you used a hash map rather than an that you used a hash map rather than an array and that's fine if you want to array and that's fine if you want to rewrite the code that i'm about to write rewrite the code that i'm about to write using hash maps i think it's perfectly using hash maps i think it's perfectly fine but i feel like i usually overuse fine but i feel like i usually overuse hashmap so this time i actually wanted hashmap so this time i actually wanted to kind of show you guys the array to kind of show you guys the array solution even though it's a little bit solution even though it's a little bit more annoying because remember our more annoying because remember our character is not the key of our array we character is not the key of our array we have to map that character to an index have to map that character to an index and we can do that just like this so s2 and we can do that just like this so s2 at index r uh minus ord of lowercase a at index r uh minus ord of lowercase a so we're also going to take the ord of so we're also going to take the ord of this because that's how we're getting this because that's how we're getting the index of our count arrays so now we the index of our count arrays so now we can actually use this index but what are can actually use this index but what are we going to use it for well we know that we going to use it for well we know that this character is the character that was this character is the character that was just added to our uh window in our s2 just added to our uh window in our s2 string so we're gonna increment the string so we're gonna increment the count of this by one but now that we count of this by one but now that we just incremented the count of it by one just incremented the count of it by one it could be possible that now it exactly it could be possible that now it exactly equals the count in s1 so if that's the equals the count in s1 so if that's the case if now that we incremented this and case if now that we incremented this and now it finally equals exactly s1 count now it finally equals exactly s1 count at the same index at the same character at the same index at the same character then then we can increment our number of matches we can increment our number of matches by one but it's possible that also by by one but it's possible that also by incrementing this instead of making it incrementing this instead of making it exactly equal we made it too exactly equal we made it too large we made it exactly bigger than the large we made it exactly bigger than the target by one that's how you know we target by one that's how you know we have got to actually decrement the have got to actually decrement the number of matches so basically else if number of matches so basically else if s1 s1 count at the same index plus 1 is now count at the same index plus 1 is now exactly equal to s2 count at the index exactly equal to s2 count at the index and if this is the case that means they and if this is the case that means they were equal they were exactly equal but were equal they were exactly equal but we just incremented s2 count by one so we just incremented s2 count by one so now we made them unequal so then we now we made them unequal so then we actually have to decrement the number of actually have to decrement the number of matches by one okay and that's pretty matches by one okay and that's pretty much the entire algorithm but there's much the entire algorithm but there's one last thing and i'm just going to go one last thing and i'm just going to go ahead and actually copy and paste this ahead and actually copy and paste this entire block entire block because we're going to do the exact because we're going to do the exact opposite thing we know that we're adding opposite thing we know that we're adding a character to the right of our window a character to the right of our window but at index l at index left we removed but at index l at index left we removed a character so we're just going to a character so we're just going to replace this with the opposite case replace this with the opposite case right here i replace the r with an l and right here i replace the r with an l and here instead of incrementing the count here instead of incrementing the count we're going to decrement the count we're going to decrement the count because this is the character that we because this is the character that we just removed from the left side of our just removed from the left side of our window and here what we're going to say window and here what we're going to say this is actually going to stay the same this is actually going to stay the same if somehow by decrementing this we made if somehow by decrementing this we made the counts exactly equal then we're the counts exactly equal then we're going to increment our matches by 1. but going to increment our matches by 1. but if somehow by decrementing this value we if somehow by decrementing this value we changed it from being exactly equal to changed it from being exactly equal to now being too small meaning it's now now being too small meaning it's now going to be equal to s count s1 count going to be equal to s count s1 count minus 1. if we changed it from being minus 1. if we changed it from being exactly equal to now being slightly too exactly equal to now being slightly too small that's when we are going to small that's when we are going to decrement the number of matches right so decrement the number of matches right so we really didn't have to make too many we really didn't have to make too many changes to this block of code but that's changes to this block of code but that's actually the entire algorithm except we actually the entire algorithm except we know our right pointer is being know our right pointer is being incremented by one each time but we also incremented by one each time but we also want to make sure our left pointer is want to make sure our left pointer is being incremented by one each time as being incremented by one each time as well and after that we are done then well and after that we are done then finally we can return false well not finally we can return false well not quite because it's possible that after quite because it's possible that after our loop eggs are exited right the last our loop eggs are exited right the last iteration of our loop we didn't check iteration of our loop we didn't check after that if our matches were equal to after that if our matches were equal to 26 so instead we're actually going to 26 so instead we're actually going to return return does matches equal 26 so it's going to does matches equal 26 so it's going to return true if it does equal 26 it's return true if it does equal 26 it's going to return false if it doesn't going to return false if it doesn't equal 26 now let's run the code to make equal 26 now let's run the code to make sure that it works and on the left you sure that it works and on the left you can see that it does and it's pretty can see that it does and it's pretty efficient so i really hope that this was efficient so i really hope that this was helpful if it was please like and helpful if it was please like and subscribe it really supports the channel subscribe it really supports the channel a lot consider checking out my patreon a lot consider checking out my patreon where you can further support the where you can further support the channel and hopefully i'll see you channel and hopefully i'll see you pretty soon thanks for watching | 2024-03-20 11:42:36 | 567 | Permutation in String - Leetcode 567 - Python |
|
lnMjTXYLBLQ | okay so lead code practice time so there are two goals in this video the so there are two goals in this video the first one is to see first one is to see how to solve this problem uh find the how to solve this problem uh find the solution then you're going to do some solution then you're going to do some coding work coding work and the second one is to see how we and the second one is to see how we should behave in a real interview should behave in a real interview so let's get started so remember the so let's get started so remember the first thing first thing is to always try to understand the is to always try to understand the problem and ask some clarification problem and ask some clarification questions questions in case there isn't any there is in case there isn't any there is anything you don't understand anything you don't understand and also think about the ash cases so and also think about the ash cases so for this one let's see for this one let's see strobo grammatic uh strobo grammatic uh number two okay so a strobogrammatic number two okay so a strobogrammatic number is a number that looks number is a number that looks the same we rotated 180 degrees the same we rotated 180 degrees so look so okay so 180 degrees means so look so okay so 180 degrees means looked at upside down so find all looked at upside down so find all strobogrammatic numbers that strobogrammatic numbers that are of length n are of length n all right so i think i kind of all right so i think i kind of understand the problem understand the problem uh and i think the edge case i can uh and i think the edge case i can currently think about currently think about is n is equal to n is n is equal to n is equal to zero then what should we is equal to zero then what should we return return then i think a is equal to zero then we then i think a is equal to zero then we just return an empty just return an empty list so let's find the solution list so let's find the solution so how to solve this problem so first of so how to solve this problem so first of all all we need to see which numbers we need to see which numbers we can treat as uh we can treat as uh like a pair when we look upside down so like a pair when we look upside down so so for once we could have so for once we could have one when i look upside down one when i look upside down it is one so one for it nine is for six it is one so one for it nine is for six it is nine it is nine for nine it is six and four for nine it is six and four eight it is eight um if there's eight it is eight um if there's i'm trying to think if there's anything i'm trying to think if there's anything else uh i else uh i should take care of so it's what two should take care of so it's what two no three no four no three no four is no five six we have it is no five six we have it eight seven i don't think so seven eight seven i don't think so seven eight and nine all right so we have eight and nine all right so we have the i think we have the zero the i think we have the zero to 0 0 stuff so if it is 0 0 um so of course if n is equal to 1 we can have we will we could return one zero or eight so otherwise um if n is larger than one then we can not really have the zero to appear as the first digit but if n is equals to three then of course we can have something like one zero one so something like that uh so i'll say uh we will need to trade uh and when it's odd um and when n is equal to even so and it could be even or odd so this is something we need to think about and the other special thing i think is the zero stuff so you cannot put zero at the very beginning except n is equal to a one um yeah so i think that's it for yeah i think that's it um yeah sure so let's think about how to solve this problem so we have found all the cases i would say we could define a recursive function uh to find it like enumerate so for each bit okay so one let's say for n so we so we could we could define a recursive function like we knew more so for each bit we enumerate all the possibilities but for for each bit the the possibility if it is starting if it is the first first digits when a is larger than one then it could be one six nine or eight so that's a that's finite uh enumeration and uh so for example let's just give you an example let's say when n is equal to three so when you try to enumerate the first digit it could be either one or six or nine or eight so one is uh it could be one or it could be one or zero or eight so this zero or eight so this so and then when it is the last digit so and then when it is the last digit it really depends on what the first it really depends on what the first digit is digit is so it's like we first try to enumerate so it's like we first try to enumerate the possible the possible other possibilities for the first half other possibilities for the first half and if n is a odd number in the middle and if n is a odd number in the middle there are only three options there are only three options and for the rest half it it really and for the rest half it it really we we cannot do any any motion it is we we cannot do any any motion it is it is just based on the first half it is just based on the first half so i would say that's pretty much about so i would say that's pretty much about about it and if you want to about it and if you want to think about the time complexity think about the time complexity i would say roughly if we consider i would say roughly if we consider just um okay so if we think just um okay so if we think that each digit can have that each digit can have uh if we think each digit can have uh if we think each digit can have five but i mean it's a very rough five but i mean it's a very rough uh estimation if we have five uh estimation if we have five possibilities for first of the half possibilities for first of the half i would say the runtime is going to be i would say the runtime is going to be the possibility it's something like the possibility it's something like this um this um and to process each of the and to process each of the possibility it takes time a little bit possibility it takes time a little bit so so essentially the runtime will be essentially the runtime will be something like this again this is very something like this again this is very rough because it depends on rough because it depends on if any is equal even number or is an odd if any is equal even number or is an odd number number it it's um it's different it it's um it's different but in general i think this should be but in general i think this should be uh fairly correct uh fairly correct so the next part is about coding so so the next part is about coding so coding don't be too slow care about the coding don't be too slow care about the correctness correctness and also the readability and also the readability so let's get started and do some coding so let's get started and do some coding work um work um so um well if um n is equal to zero then i i'll say first of all create this thing let's say uh let's say straw and nums uh straw nums let's say yeah straw nuns has new linked lists all right so if n is equal to zero let me just return so if n is equal to one then stroll now let's now add a uh this says if this is the thing we could have one yeah so let's just uh zero yeah so let's just uh zero or one or eight then we just return the scroll numbers otherwise we need to define a helper find this dual strobo find this dual strobo okay find strobo grammatical okay find strobo grammatical so first of all we have we need to pass so first of all we have we need to pass the end and we pass the index as zero the end and we pass the index as zero and uh we also need to pass the and uh we also need to pass the straw nums to store it straw nums to store it uh yes i think uh yes i think yeah i think that's it and finally we yeah i think that's it and finally we returned the stroll returned the stroll now all right so let's try to implement now all right so let's try to implement the helper function the helper function let's say while this is let's say while this is a or load of the a or load of the the of the the of the function so this is idx and function so this is idx and this is um a list of the string uh what is that this string um this is uh let's just draw if if i dx is equal to if if i dx is equal to uh all right so we uh all right so we we also need to have like a time string we also need to have like a time string so this is temp um so if i dx is equal to zero uh we only have one six eight and nine the three options so we are going to say um cars car array all right so uh i think we need to all right so uh i think we need to define the the the the exit of this define the the the the exit of this recursive function first so if idx is equal to n then what we are going to do is we are going to have strong numbers dot add a temp and then we return so if um idx is equal to one then we have several different options so array array cars is equal to cars is equal to the first one is one plus the first one is one plus x eight and uh nine so we are going to go through the cars um see in cars and uh you're gonna say fine find strobo grammatic and this is and this is okay so idx is equal to zero then it should be that so this is idx plus one and then this says so this is 10 plus uh so this is 10 plus uh c and this is troll nums um and if idx is smaller than n divided by 2 and then this is like this is this should be returned so if it is smaller than this so let's say if it is four and minus by in divided by two is two so it is you have zero and one uh like this okay so if i did this we have different options car cars are like you could have zero it could definitely include zero uh so what if it is uh so what if it is five so if it is five five so if it is five so five divided by two is two so we only so five divided by two is two so we only have zero and one there okay have zero and one there okay so this it's zero one six eight and nine so this it's zero one six eight and nine so we actually could have this so we actually could have this all right so if um all right so if um n is a odd number and um so if n is a odd number and we are actually at there so i dx is equal to uh so it if it is five so if it is five we when we are at two then it is that uh so one sorry so when n is equal to uh so one sorry so when n is equal to three three then divide by two is one then divide by two is one so we have so we have all right so one all right all right so one all right so one and divide it so when n so one and divide it so when n is a odd number and idx is is a odd number and idx is equal to and divide by 2 so that's the time all right so i think i should have it okay so when this uh hose that means it is a metal so we have how many options do we have we have the zero one and yeah so otherwise it yeah so otherwise it is it is time for us to find the is it is time for us to find the it is the second half for the string so it is the second half for the string so we need to find we need to find the corresponding the corresponding character from the first half so character from the first half so so for example when n is equal to five so for example when n is equal to five uh we have zero one two three four when uh we have zero one two three four when we are trying to enumerate the the we are trying to enumerate the the the character at index three we need to the character at index three we need to try to try to look at the character at index one so um we are going to see uh we are going to so car c is equal to so car c is equal to uh tam dot car uh tam dot car at which is n minus at which is n minus uh index and then minus one so this is a character we are looking at and we are going to switch c all right so it doesn't have the all right so it doesn't have the just use f so if c is equal to just use f so if c is equal to uh so if it is equal to uh so if it is equal to 1 then we need to find the strobo grammatic and the time plus one so else if let's still use which i think um otherwise it's just uh two yeah case uh just find the dramatic and then the break break it and the four case uh one and six for ks6 um we need to do something like this would be nine um so actually we could have a hash map um which could be it's a map car character car character enter um that is equal to car map is equal new uh hash map so this one let's say we are going to have car mapped output uh this is one and one and what else so we have and uh eight to eight and uh eight to eight and the knight to six so you're just going to call flying strobo chromatic tamp plus car map tamp plus car map dock at c dock at c alright so alright so yes i think that should be pretty much yes i think that should be pretty much it it and uh remember after you're done with and uh remember after you're done with coding it's not coding it's not done done you still need to do some done done you still need to do some testing so testing so the way to do testing is uh if it is not the way to do testing is uh if it is not a runnable platform a runnable platform uh you should go through the task case uh you should go through the task case manually explain how this piece manually explain how this piece is going to work on top of it and also is going to work on top of it and also at the same time at the same time um explain at the same time do some um explain at the same time do some sanity check on the sanity check on the logic otherwise if it is runnable i logic otherwise if it is runnable i think think you could just make use of the console you could just make use of the console to do some testing let's see to do some testing let's see if okay so if it is if okay so if it is oh okay okay so if it's two it's okay if it's okay so if it's two it's okay if it's three three is it okay okay so it's is it okay okay so it's if it's one it's okay i think okay if it's one it's okay i think okay yeah so i think it should be fairly yeah so i think it should be fairly good regarding uh regarding it good regarding uh regarding it regarding this piece of code so let's regarding this piece of code so let's give it a submission give it a submission all right so it says wrong answer so why all right so it says wrong answer so why it is a wrong it is a wrong answer answer oh so if we we forgot to put the zero oh so if we we forgot to put the zero zero stuff here zero stuff here that's essentially why that's essentially why we are so if it is four we are so if it is four then let's just run it yeah so we forgot to put the zero zero into the map so let's do a submission for it again okay so now it's all good so uh regarding the test case setup i would say definitely instead of uh when n is equal to zero because it's special y is equal to one it's also a special thing when n is equal to a odd number and even number so that's essentially what the task is i would set up uh in my in my in my uh in my test cases okay so that's it for this coding question uh if you have any uh question about this coding puzzle about this solution please um leave some comments below if you find it pretty helpful please help subscribe to this channel and i'll | 2024-03-22 11:48:34 | 247 | Facebook Coding Interview Question | Leetcode 247 | Strobogrammatic Number II |
|
mtTzQJkt2b8 | hey what's going on everybody so today we are going to solve we are going to solve one of the coolest problem remove one of the coolest problem remove duplicates from socialist so this duplicates from socialist so this problem is quite good problem is quite good so if you see the like and dislike they so if you see the like and dislike they show this problem is quite good all show this problem is quite good all right so what we have to do is right so what we have to do is basically simply like if you remember basically simply like if you remember the last problem which we did is which the last problem which we did is which is is remove a duplicate from an array it's remove a duplicate from an array it's similar to like that similar to like that but uh right now we have the list so we but uh right now we have the list so we have to have to perform something in this it's not too perform something in this it's not too hard i will show you this is quite hard i will show you this is quite simple simple the logic which i will show you is quite the logic which i will show you is quite simple all right so simple all right so what we are going to do is i will what we are going to do is i will something do like this for example if something do like this for example if uh we find if if i if right now i am on uh we find if if i if right now i am on this one this one this node and i find the next node is this node and i find the next node is similar then i will simply similar then i will simply mark my next node will be this one so i mark my next node will be this one so i will i will not will i will not go on this one now now so this is my go on this one now now so this is my next node okay next node okay so same thing will happen like uh if i so same thing will happen like uh if i will show you for the will show you for the uh big example then a good example so uh big example then a good example so if you look at this example this way if you look at this example this way all right so if you look at this example all right so if you look at this example then we have uh i'm on over here so i then we have uh i'm on over here so i see like this one is similar so i will see like this one is similar so i will just simply go over there just simply go over there all right then right now i am on here so all right then right now i am on here so i will uh i will uh say is this similar no it's not similar say is this similar no it's not similar so i will simply move over here so i will simply move over here all right now i will say is this similar all right now i will say is this similar yeah it is similar so yeah it is similar so i don't want to go anywhere so i will i don't want to go anywhere so i will just end up over here so my the final just end up over here so my the final one is one two three one is one two three all right guys so i hope this thing uh all right guys so i hope this thing uh makes some sense makes some sense so i will just let me just code it so so i will just let me just code it so you can you can get to know like what i want to say all get to know like what i want to say all right so just let me right over here uh right so just let me right over here uh i will scare from on this note i will i will scare from on this note i will say say as a list and this is my pointing me to as a list and this is my pointing me to the head right now this is my initial the head right now this is my initial stage so stage so it is pointing to head so i will say it is pointing to head so i will say like while like while list is not equal to null till then the list is not equal to null till then the root will root will run all right and uh in this let me run all right and uh in this let me create one base condition first so the create one base condition first so the base condition will be base condition will be like for example if list like for example if list dot next equals to null dot next equals to null like if my next like if i'm in the end like if my next like if i'm in the end and and like after that nothing is over there like after that nothing is over there then i will simply break it then i will simply break it right there is no sense to uh go any right there is no sense to uh go any further like that because further like that because otherwise it will go out of the boundary otherwise it will go out of the boundary now i will communicate one if condition now i will communicate one if condition if list dot if list dot uh i will say like if this dot next uh i will say like if this dot next dot val is equal to dot val is equal to list dot well which we are looking for list dot well which we are looking for like or like you can like or like you can write in the reverse it doesn't matter write in the reverse it doesn't matter all right so like uh all right so like uh what what i write over here is i will what what i write over here is i will say like i'll just i will explain say like i'll just i will explain in the driver so if this is the in the driver so if this is the condition then condition then i will say list dot next i will say list dot next will be though next so how we we remove this thing because like we are not removing we are just keep skipping that that part all right else if if uh the next value which you are looking is not similar with the one which we are standing then we will simply say like okay that will be one next so we don't have to skip that so i will say just as uh list door uh list equal to list load next and in the end i will just write to my head all right guys so just let me give a quick run then i will uh show you like what i have written my code if you don't understand till now all right guys so okay so what i written over here is so i just write this is my base condition okay so once i reach in the end once i reach over here i will just simply break it alright guys so now what what i have done over here is i'll say like if for example my this well is uh similar to this well then i will just gonna skip this so that's what i did i said like my next one my my the next list will be this one so dot next door next means you just keep escaping this one that's all what we have did so i hope this makes some sense to you so let me just give a submission and uh this question is quite simple to understand this is not too hard anything all right guys so if you have still any problem then do just let me know in my comment section let me just give a submit button all right so it's working very good all right guys thank you for watching this video i will see you in the next one | 2024-03-20 12:26:57 | 83 | LEETCODE - 83 || Remove Duplicates from Sorted List || Easy Solution |
|
sCoTgMCzBoI | hey hey everybody this is Larry this is day 30th of the July leco day challenge day 30th of the July leco day challenge 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 problem what you think about today's problem word subsets word subsets hmm cool uh yeah hit the like button and hmm cool uh yeah hit the like button and subscribe man I am up shape and mentally subscribe man I am up shape and mentally I think I reset that but yeah one thing I think I reset that but yeah one thing I've been doing just I've been spamming I've been doing just I've been spamming this as well but uh I've been doing an this as well but uh I've been doing an extra problem every day so you wanna if extra problem every day so you wanna if you feel like these problems are too you feel like these problems are too easy you know do an extra problem with easy you know do an extra problem with me some of them might some of those me some of them might some of those Farms are easy too but Farms are easy too but um for me it's just about doing a new um for me it's just about doing a new apartment for example I probably yeah I apartment for example I probably yeah I would have done a lot of these Farms so would have done a lot of these Farms so I'm trying to do one that I haven't seen I'm trying to do one that I haven't seen before just for a little bit more extra before just for a little bit more extra practice if you will practice if you will um I don't remember these apartments um I don't remember these apartments though so we'll see how that goes uh you though so we'll see how that goes uh you know maybe on a subconscious level know maybe on a subconscious level anyway anyway today's problem is 9 16 word subset today's problem is 9 16 word subset you're given two string arrays words one you're given two string arrays words one and words two B is a subset of string a and words two B is a subset of string a if every word in every letter and B of if every word in every letter and B of cursor okay so it so we want to see if cursor okay so it so we want to see if words words uh every string and B outwards have uh every string and B outwards have multiple okay multiple okay so basically we want to see for words so basically we want to see for words two if they say E and O then uh Facebook two if they say E and O then uh Facebook has g d n o Google as you know and has g d n o Google as you know and because you know okay because you know okay um I could return the thing in any order um I could return the thing in any order uh okay so that means that yeah I I don't know that we need to do anything that uh that you know optimal but let's start with something more naive first right um and just write our skeleton n is 10 to the fifth so I so we cannot do it you know n times F type thing because that'll be too slow so let's let's think about this a little bit um every letter and this is a subset is a little bit of a phrasing uh all strings and red ones are unique okay and what's two what is which two oh they only gave examples of one nighter which is kind of a crappy example to be honest because you know just explain it but this is a subset of warrior but not of world okay so you can have multiple um um I think so the first thing that we can I think so the first thing that we can do for example is that for each do for example is that for each word word in words one we go okay is this word in words one we go okay is this word Universal and the way that this Universal and the way that this Universal is just by like you know word Universal is just by like you know word two maybe in words two and then you do two maybe in words two and then you do that dot dot and again of course this is that dot dot and again of course this is gonna be too slow because this is n gonna be too slow because this is n times M or however you want to say it times M or however you want to say it um but however you want to say it the um but however you want to say it the way you say it is that this is too slow way you say it is that this is too slow can I do a little bit of a filter I was can I do a little bit of a filter I was um um and I think there are things that oh oh and I think there are things that oh oh way actually way actually so the length of these things are 10. so the length of these things are 10. right right what does that mean what does that mean all right all right um I mean that allow us to make one optimization right which is that does have to be in the same order this does have to be in the same order this this is not the same order thing okay so this is not the same order thing okay so which means that for example which means that for example yeah yeah um okay that's good because then now we um okay that's good because then now we can normalize the string a little bit if can normalize the string a little bit if nothing else nothing else um the timing is a little bit tight because I was going to do something like 2 to the 10 because they're only 10 characters you can pre-process everything you know two to the 10 kind of way each which uh each letter you know possible and not possible um of course that's gonna be two to ten is uh one thousand so that's a Thousand Times Ten to the fourth is going to be a little bit slow um 10 to the 7 is probably honestly in but then you're going to put in a hash table and a hash table even though it's over one it's it's a it it's an old one that adds up uh it probably is actually login but in any case so okay um so those are the two things that I'm thinking of immediately what can I do to filter it all strings um um well so we can pre we definitely want to pre-process words too I mean we can do very minimal things with respect to with respect to um with respect let me think about this for a second um I was thinking about something like yeah we definitely could to could pre-process words too but I was just thinking maybe um okay these mediums are kind of tricky okay these mediums are kind of tricky one day maybe I'm just not thinking one day maybe I'm just not thinking right uh okay so the first thing that right uh okay so the first thing that you would do is still like sort these or you would do is still like sort these or the normal or normalize these but then the normal or normalize these but then what do you do after normalizing them what do you do after normalizing them I mean for these with two words it's I mean for these with two words it's kind of kind of you know straightforward okay or you know straightforward okay or whatever whatever but let's see time is sweets remember string a and word Step One is universal if for every string in b b is a subset of a no I'm not talking about I still think this this wording is so awkward foreign oh wait I'm thinking okay oh wait I'm thinking okay I think one thing I was trying to think I think one thing I was trying to think is still thinking about this as is still thinking about this as independent but the thing to do is that independent but the thing to do is that because it has to be for every set not because it has to be for every set not every string that means that every string that means that um yeah that means okay I am just being um yeah that means okay I am just being dumb then dumb then um that means that we can build out the um that means that we can build out the every uh almost like at the intersection every uh almost like at the intersection of order for inverts two and the of order for inverts two and the intersection of all the uh wow I'm just intersection of all the uh wow I'm just really slow today really slow today um yeah and then in this section of what um yeah and then in this section of what the words and were which two is just the words and were which two is just going to be something like uh so then going to be something like uh so then now we can normal we can normalize the now we can normal we can normalize the intersection of each word wow I'm intersection of each word wow I'm I'm like a little bit I'm like a little bit I I don't I wouldn't want to say I I I don't I wouldn't want to say I misread this poem but I'm not thinking misread this poem but I'm not thinking about this pump uh at all right uh about this pump uh at all right uh but yeah um because here the idea is but yeah um because here the idea is that okay if it's satisfied this word that okay if it's satisfied this word how does it satisfy each word right how does it satisfy each word right meaning that if we break it down it is meaning that if we break it down it is you know if you want to say it in a you know if you want to say it in a sentence maybe you might have something sentence maybe you might have something like like now that's it was two and this these are now that's it was two and this these are terrible examples the terrible uh of terrible examples the terrible uh of like ABC uh a a a a d e or something like ABC uh a a a a d e or something like that well in that case like that well in that case to satisfy both this and this you'll you to satisfy both this and this you'll you can break it down saying that can break it down saying that um the the each word has to have one a um the the each word has to have one a one B one C and and three a One D one e one B one C and and three a One D one e right and Etc right and Etc um um and of course if you think about it and of course if you think about it these things are end anyway like within these things are end anyway like within the same word you have these n the same word you have these n operations if you will of requirements operations if you will of requirements and as a result and some of these you and as a result and some of these you can clearly merge because for example 3A can clearly merge because for example 3A 1A you know uh merges into three a 1A you know uh merges into three a because the three supersedes a superset because the three supersedes a superset a bit if you will uh one is a subset of a bit if you will uh one is a subset of the three a I guess so yeah and then the three a I guess so yeah and then here then we can do here then we can do um maybe someone like uh um maybe someone like uh uh uh uh yeah Max as you go to collections.com and then here for someone like this right someone like this right and that'll give us the intersection of and that'll give us the intersection of all the requirements that we actually all the requirements that we actually want I been struggling a lot with want I been struggling a lot with reading lately reading lately and then now we can ask if this word is and then now we can ask if this word is universal by just looking this up really universal by just looking this up really quickly which is quickly which is um yeah um yeah uh which is okay seriously uh which is okay seriously again I'm using calendar again I'm using calendar but you can just put everything in the but you can just put everything in the hash table is what this is or uh yeah hash table is what this is or uh yeah look up hash table uh character by look up hash table uh character by characters what this is asking so yeah characters what this is asking so yeah okay and see that Keys okay and see that Keys um um if this is we if we have fewer characters then we're no longer good so good is going to force break if good then we put in the answer uh okay wow I don't know I totally misread this I don't know I totally misread this formula formula uh okay this is very well uh okay this is very well oh oh we need to compare it with Max not Max we need to compare it with Max not Max the keys in Max not C because the answer the keys in Max not C because the answer the reason why that was wrong is uh is the reason why that was wrong is uh is because I'm sloppy but also because it because I'm sloppy but also because it was missing keys that was missing keys that um for example if an a is not in the um for example if an a is not in the word we would not do this comparison word we would not do this comparison which is obviously wrong because yeah which is obviously wrong because yeah um let's give it a submit cool and a little bit faster this time I wonder what I changed uh oh I guess this is the same color oh I mean we just set intersection actually I should have maybe done it that way too but but maybe it's a little bit slower I don't know um this is going to be linear ish time linear space uh oh wait sorry linear time at Alpha space um linear because for every character in word one we look at it once uh well this this part is the word one and this is part L2 um and and this is at most o of L which is the length of the word and that's going to be all of uh well in this case is 10 but even if you don't bound it it's going to be at most 26 week um or whatever because you know that's the size of the alphabet so this is n plus L um for that reason uh but still I guess n times l in um yeah maybe n times L but linear in the size of the input because we look at each character exactly once really and then maybe a little bit and over Alpha space for for the counters um and technically refer it away afterwards so depending on how you define space because obviously the way we actually code it is we allocate new memory but if you really want you could just you know do like a C that reset or something or clear maybe I don't know something like that right um but it's fine or you could just do a for Loop through it um cool that's all I have with this one let me know what you think stay good stay healthy to good mental health weekend is here uh you know hope you enjoy it stay good stay healthy take your mental health I'll see you later and take care remember I have one more question so | 2024-03-25 10:55:16 | 916 | 916. Word Subsets - Day 30/31 Leetcode July Challenge |
|
5W_oDRGUyoM | hey guys in this tip in this video i'll be going over delete node in a binary be going over delete node in a binary search tree search tree so basically this problem gives you a so basically this problem gives you a binary search tree binary search tree um and uh um and uh it wants you to delete a node with a it wants you to delete a node with a target value target value so um if the value here is three so um if the value here is three they want you to delete it and you can they want you to delete it and you can either move two either move two up into its place or four up into its up into its place or four up into its place place um as long as it's maintains the binary um as long as it's maintains the binary search tree search tree uh like where all the elements to the uh like where all the elements to the left left of a node all the nodes to the left of of a node all the nodes to the left of the node are less than it and all the the node are less than it and all the nodes to the right of it are greater nodes to the right of it are greater and uh yeah it wants you to solve it and uh yeah it wants you to solve it with with runtime with respect to height of the runtime with respect to height of the tree and tree and so yeah i'm pretty sure the problem is so yeah i'm pretty sure the problem is fairly simple to understand fairly simple to understand so yeah so let's get into the solution so yeah so let's get into the solution so essentially what you want to do is so essentially what you want to do is you just want to search through the you just want to search through the binary search tree as normal binary search tree as normal because let's say you have like some because let's say you have like some numbers here numbers here um like it doesn't actually matter but um like it doesn't actually matter but uh let's just say we're looking for like uh let's just say we're looking for like three we look at our three we look at our overall root of the tree and we say oh overall root of the tree and we say oh if three is less than five so we know we if three is less than five so we know we want to look over here want to look over here i'm in this direction um and then we i'm in this direction um and then we go to the left guy and we see if um go to the left guy and we see if um that guy's equal to three and so that guy's equal to three and so of course um you won't be going over all of course um you won't be going over all the nodes in the tree just the the nodes in the tree just the through the height of it so that's just through the height of it so that's just like standard um like standard um usage of a binary search tree the more usage of a binary search tree the more interesting part is what happens interesting part is what happens when we actually find the node we want when we actually find the node we want to delete to delete and um so basically what happens when we and um so basically what happens when we find find three over here um and we want to delete three over here um and we want to delete it it so you there's two ways to really do it so you there's two ways to really do it you could shift you could shift the right guy up in there or the left the right guy up in there or the left guy up in there um guy up in there um in my solution i shift the left guy it's in my solution i shift the left guy it's pretty arbitrary though pretty arbitrary though um so basically what you know um so basically what you know that um all the values that um all the values in this in this the right guy here in this in this the right guy here in this right guy they'll be larger than in this right guy they'll be larger than um um the largest value in this left guy so the largest value in this left guy so basically um if we start at this left basically um if we start at this left guy here guy here we can just keep on taking the right we can just keep on taking the right like it doesn't matter what's on the like it doesn't matter what's on the left side we don't really care about left side we don't really care about that that we just keep on going right right and we just keep on going right right and right because we'll know that's biggest right because we'll know that's biggest and then whenever and then whenever we reach the end there's nothing on this we reach the end there's nothing on this notes pointing to notes pointing to whenever we end of it we know this is whenever we end of it we know this is like the largest value like the largest value in the left subtree here and then in the left subtree here and then basically we can just grab this right basically we can just grab this right guy guy we know it's larger than all the guys in we know it's larger than all the guys in this left subtree so this left subtree so we can just tack it on to the end here and point this guys right to uh this right guy here because then we know hey look at this node everything to its right is greater than that which is true and then we after we go all the way down this right thing and tack this thing on to the end um then what we can do is we can just uh point this guy like have this pointer uh point to this guy instead of this three so then that effectively removes three from it and still keeps as a binary search tree and yes let's just get into how to implement this um yeah so by far and away the easiest way to implement this is recursively using um like an exchange x type of scenario where um yeah i'll just step through this logic here so of course if there is no you just um don't worry about it so essentially this is the only important part okay uh well this is the most important part so this is the part where you um traverse through the tree to find the note that you node that you want to delete so if our value is greater than the key we know that we should look at nodes less than it so we um run delete node and just go to the left of it and we whatever this values returns we'll point that to that left so it's like a like an x change x type of algorithm and then you go to root.right and then you run delete node and pass in that and then uh basically uh this part this will basically recursively go through the tree until you find the node node that you want to delete because it'll just um like it'll just walk through this binary search tree until you find the node with the value that you want and once you see that value like let's say you pass in delete node root dot left and you go to this side here so five you're looking for three you go to the left because you want a smaller number you find three so then what you want to do is you enter this case um what you do is first of all so this part here is the logic where this this uh like the left guy of it so uh like the left guy of it so if we find three here the left guy if we find three here the left guy is two and then we'll want to keep on is two and then we'll want to keep on going right to find the largest number going right to find the largest number to attach this four to the right of that to attach this four to the right of that so uh what if we find three so uh what if we find three um here we get the left guy of it and um here we get the left guy of it and here we also get the left guy of it um here we also get the left guy of it um just so i grabbed this guy just so i can just so i grabbed this guy just so i can return it and so return it and so then you keep on going to the right then you keep on going to the right after that after that and then um so and then um so this moves um this guy this moves um this guy ml he'll start here and he'll keep on ml he'll start here and he'll keep on going to the right going to the right and so eventually ml will be this guy and so eventually ml will be this guy and then and then um then we'll make that guy's right um then we'll make that guy's right equal to this right guy so we'll point equal to this right guy so we'll point this guy for this this guy for this this guy's right child will be this guy this guy's right child will be this guy so it'll also carry over whatever this so it'll also carry over whatever this guy has guy has in his children and in his children and then we just return this left guy uh then we just return this left guy uh we'll return this guy and then we'll return this guy and then um we'll like we'll make this guy here um we'll like we'll make this guy here instead of pointing that this guy will instead of pointing that this guy will just be pointing to this guy because we just be pointing to this guy because we returned him returned him because um when you do hear the left because um when you do hear the left equals delete node equals delete node um when this thing runs and um when this thing runs and it'll return um this guy this guy's left it'll return um this guy this guy's left pointer pointer instead of pointing to this guy it'll instead of pointing to this guy it'll point to this guy and so point to this guy and so then that's basically just the answer then that's basically just the answer and you return and you return the starting route that you were given the starting route that you were given because because yeah and that's about it so yeah and that's about it so uh yeah we'll submit this uh yeah we'll submit this um yeah and this is the fastest um yeah and this is the fastest possible runtime because you're just possible runtime because you're just going through the height of the tree so going through the height of the tree so um yeah it um yeah it you don't even need to look at all the you don't even need to look at all the nodes in the tree you just need to nodes in the tree you just need to um go all the way down to the bottom of um go all the way down to the bottom of it it and uh yeah so that's about it for the and uh yeah so that's about it for the video video thanks for watching and i'll be back thanks for watching and i'll be back with another video tomorrow | 2024-03-22 12:57:52 | 450 | Delete Node in a BST [Leetcode 450, medium] |
|
vLs6ZMiPtv8 | hello friends today less of their combination some problem lessees diamond combination some problem lessees diamond first given set of candidate numbers first given set of candidate numbers Kinder's without duplicates and their Kinder's without duplicates and their target number target find all unique target number target find all unique combinations intended where the combinations intended where the candidate numbers sums to target the candidate numbers sums to target the same repeated number may be chosen from same repeated number may be chosen from candidates unlimited number of times all candidates unlimited number of times all numbers including target will be numbers including target will be positive integers a solution cell must positive integers a solution cell must not contain duplicate combinations not contain duplicate combinations combinations so as this problem only combinations so as this problem only have positive integers so we can try to have positive integers so we can try to sum up keep some older numbers but a sum up keep some older numbers but a wench wench should we stop then we need to find the should we stop then we need to find the base case the best case should be when base case the best case should be when we sum up like this to multiple times we sum up like this to multiple times then if some is exceeded then and hug it then if some is exceeded then and hug it we will stop and try to add their Nexus we will stop and try to add their Nexus 3 and keep doing this this problem is a 3 and keep doing this this problem is a classical problem using backtracking to classical problem using backtracking to solve it hmm we should notice that so solve it hmm we should notice that so this Candice numbers are actually a set this Candice numbers are actually a set they're done have duplicates so when we they're done have duplicates so when we are try to choose one number and the do are try to choose one number and the do the recursion there keep searching the recursion there keep searching you should err steals start fronds or you should err steals start fronds or current a number and though we won't use current a number and though we won't use we just needed to remove the last we just needed to remove the last element in their temporary list so element in their temporary list so basically we will use backtrack but basically we will use backtrack but there is some detail we needed to not there is some detail we needed to not pay attention to so let's of it we need pay attention to so let's of it we need a list a list Adobe result array list there we will Adobe result array list there we will call our help function panel just to call our help function panel just to return this result return this result so let's see how to implement disease to so let's see how to implement disease to help function okay we will the first help function okay we will the first parameter will be the results list and parameter will be the results list and we also needed a temporary list we also we also needed a temporary list we also need the candidate candidates and there need the candidate candidates and there are targets are targets also we need an index which means the also we need an index which means the current current starting next four days search so what starting next four days search so what will this case be when their target less will this case be when their target less or equal than zero we should have or equal than zero we should have stopped because we will not use another stopped because we will not use another variable to record those accumulates the variable to record those accumulates the sum we were just - from this target so sum we were just - from this target so it's less oh it was in zero this is the it's less oh it was in zero this is the best case if the target you go to zero best case if the target you go to zero we should our ad this chamber listen to we should our ad this chamber listen to our results but we don't we cannot just our results but we don't we cannot just add the temporaries because it's a add the temporaries because it's a reference which means when X and the can reference which means when X and the can release the changes the results are release the changes the results are placed will also change so we just need placed will also change so we just need a snapshot of the current attempt a snapshot of the current attempt released and their return so this is the released and their return so this is the recursion part the I will start from the recursion part the I will start from the index I less than their candidate can index I less than their candidate can the third stalin's the third stalin's I plus plus we just add that the current I plus plus we just add that the current I into their temporary list and do the I into their temporary list and do the recursion see we start from the result recursion see we start from the result the temporary and their candidates the the temporary and their candidates the target will sub sub structure these target will sub sub structure these candidates can leaders I and their this candidates can leaders I and their this index will also be I because we can you index will also be I because we can you see the multiple times and we remove we see the multiple times and we remove we remove the a remove the a Laster element size minus one okay Oh Laster element size minus one okay Oh minus one so let's fill this part there minus one so let's fill this part there will be the result new arrays and there will be the result new arrays and there will be the candidates and the target will be the candidates and the target who will be target and the starting net who will be target and the starting net will be zero so okay thank you for will be zero so okay thank you for watching see you next time Oh | 2024-03-20 09:07:56 | 39 | LeetCode 39. Combination Sum Explanation and Solution |
|
lRGoZyjkZ3U | hey welcome to this video we're going to solve the code problem 136 solve the code problem 136 single number which is pretty easy to single number which is pretty easy to solve it'll give you an array of numbers solve it'll give you an array of numbers and you have to return which number and you have to return which number appears just once so in this second appears just once so in this second example example 4 is the only number that appears just 4 is the only number that appears just once so we return the number 4. once so we return the number 4. now even though this problem is really now even though this problem is really easy to solve i think the technique easy to solve i think the technique you use to solve this problem is you use to solve this problem is incredibly reusable and you're going to incredibly reusable and you're going to use it a lot to solve other leap code use it a lot to solve other leap code prompts prompts so this is like a good foundation so this is like a good foundation problem to know how to solve to solve problem to know how to solve to solve future problems future problems and of course if you like this kind of and of course if you like this kind of content be sure to like comment content be sure to like comment subscribe so subscribe so more free content comes out and with more free content comes out and with that being said let's get started that being said let's get started so i'll go to my code editor i'll say so i'll go to my code editor i'll say cons ht for hash table is equal to an cons ht for hash table is equal to an empty javascript object and what this empty javascript object and what this hash table will do hash table will do is create an account of how many times is create an account of how many times something appears so let's say the something appears so let's say the number thousand appears number thousand appears four times our hash table will store four times our hash table will store that the number three that the number three appears i don't know 2200 times right appears i don't know 2200 times right of course we can also use this to say of course we can also use this to say how many times a string appears like how many times a string appears like maybe hello world maybe hello world etc but for this problem we're just etc but for this problem we're just counting number times a number appears counting number times a number appears so let's do this for now so let's do this for now and now we have to fill this hash table and now we have to fill this hash table up with a tally right up with a tally right i'm going to use a for of loop so i'll i'm going to use a for of loop so i'll say four say four const num you can call this variable const num you can call this variable whatever you want i'll call it num whatever you want i'll call it num for const num of nums right because for const num of nums right because we're going through the input array we're going through the input array called nums called nums i'll say const or not cons i'll say h i'll say const or not cons i'll say h t num is equal to h t num is equal to h t num plus 1 or t num plus 1 or one and literally this single line of one and literally this single line of code will create a code will create a tally count of this so what's going on tally count of this so what's going on here well let's say here well let's say our num here is a thousand right well our num here is a thousand right well then we're gonna increase the count from then we're gonna increase the count from four to five so that's what this chunk four to five so that's what this chunk of of this chunk of code does but what about this chunk of code does but what about this or one operator this or one operator now let's say a new number appears that now let's say a new number appears that we've never seen before like the number we've never seen before like the number one three three seven right one three three seven right well if it's the first time that one well if it's the first time that one three three seven appears three three seven appears ht ht num which is asking does number ht ht num which is asking does number one three three seven appear in this one three three seven appear in this hash table object well it doesn't right hash table object well it doesn't right there's no one three three seven in here there's no one three three seven in here so this chunk will evaluate to false or so this chunk will evaluate to false or undefined or like a false value undefined or like a false value and the or operator it says if whatever and the or operator it says if whatever to the left of it to the left of it evaluates to untruthfully or false we'll evaluates to untruthfully or false we'll use where's on the right hand side use where's on the right hand side so now htnum will be equal so now htnum will be equal to one so let's say up this is the first to one so let's say up this is the first time that one three three seven appears time that one three three seven appears make it the number one because this is make it the number one because this is the first time it appears the first time it appears and we see one three three seven again and we see one three three seven again this evaluates to true and we only run this evaluates to true and we only run this code and we increase it by one this code and we increase it by one to two so this for loop here to two so this for loop here creates this tally count and now we'll creates this tally count and now we'll just say just say four i'll use a for in loop which if we four i'll use a for in loop which if we check the documentation check the documentation is a really easy way to loop over the is a really easy way to loop over the keys and values of a keys and values of a javascript object and our hash table is javascript object and our hash table is a well javascript object a well javascript object so i'll use a for in loop so i'll just so i'll use a for in loop so i'll just call it for key call it for key const key but you can call it whatever const key but you can call it whatever you want the use property i'll just use you want the use property i'll just use key key for const key in hash table for const key in hash table i'll say if hash table key i'll say if hash table key right so this value here is equal to one right so this value here is equal to one then i'll say return key then i'll say return key so i'll copy this head over to leap code so i'll copy this head over to leap code and let's submit okay and let's submit okay cool so we passed and before we go over cool so we passed and before we go over the time and space complexity the time and space complexity if you like this kind of content i also if you like this kind of content i also have paid content on my website of have paid content on my website of kaeducation.com kaeducation.com where i go over more complex lead code where i go over more complex lead code prompts and we also go over data prompts and we also go over data structures too which is pretty structures too which is pretty foundational if you want to pass an foundational if you want to pass an interview now that being said let's go interview now that being said let's go over the uh time space complexity over the uh time space complexity so time complexity is of n we loop so time complexity is of n we loop through the input array through the input array right so right here this for loop goes right so right here this for loop goes over every element in the input array over every element in the input array of n and space complexities of n of n and space complexities of n from our hash table right we use this from our hash table right we use this hash table hash table and while we fill it up with values and and while we fill it up with values and worst case scenario worst case scenario of that and that should be it for this of that and that should be it for this video and i'll see you guys in future video and i'll see you guys in future videos | 2024-03-21 12:11:09 | 136 | Solving LeetCode 136 in JavaScript (Single Number) |
|
AWC0suagMMo | hey hello there today we're looking at this lead coding challenge questions this lead coding challenge questions insert delete get Rendon in constant insert delete get Rendon in constant time we need to design a data structure time we need to design a data structure that supports the following operations that supports the following operations in average constant time the suite in average constant time the suite different operations are insert we try different operations are insert we try to insert a value into the set if it's to insert a value into the set if it's not already in there so if we just not already in there so if we just literally use a set this operation is literally use a set this operation is constant already the second operations constant already the second operations to remove an element from the set if to remove an element from the set if it's indeed present again if we use a it's indeed present again if we use a set the membership checking and remove set the membership checking and remove as they all gonna be in constant time so as they all gonna be in constant time so if the set actually satisfy the first if the set actually satisfy the first two the third one is to do this get two the third one is to do this get render we need to return a rendering render we need to return a rendering element around the current set of element around the current set of elements each element must have the same elements each element must have the same probability of being returned this one probability of being returned this one is not so easy this set but it will be is not so easy this set but it will be super super easy you with array because super super easy you with array because I really have index access to the I really have index access to the elements on that so if it's just note elements on that so if it's just note down the number of elements on the array down the number of elements on the array let's say that we have six element we let's say that we have six element we just saw a die if it's number one we just saw a die if it's number one we just returned the first element on the just returned the first element on the array 1 we can we can use the number array 1 we can we can use the number that the random number generator as the that the random number generator as the index access our to the to the bottom index access our to the to the bottom so with array we can support that the so with array we can support that the third operation in constant time but for third operation in constant time but for array the insert and remove is going to array the insert and remove is going to be a linear time because we have to be a linear time because we have to first do a linear scan so already try to first do a linear scan so already try to find the value so so for that reason find the value so so for that reason we're gonna try to fuse this two data we're gonna try to fuse this two data structure together to basically support structure together to basically support each other so that the they combine they each other so that the they combine they can support all three operations and can support all three operations and constant constant so obviously the set here just by so obviously the set here just by yourself is not able to bridge this to yourself is not able to bridge this to data structure so we're going to use data structure so we're going to use something that really similar to set something that really similar to set which is going to be hashmaps you know which is going to be hashmaps you know the keys in the hash map it's sort of the keys in the hash map it's sort of like a set but the value the key value like a set but the value the key value relationship can help to link the hash relationship can help to link the hash set to the link list so the the the key set to the link list so the the the key on the hash map is going to be the on the hash map is going to be the actual values because we had to do the actual values because we had to do the duplication checks or those kind of duplication checks or those kind of things so the values of the key and the things so the values of the key and the key is sorry the key is the value the key is sorry the key is the value the key on the hash map is the value we try key on the hash map is the value we try to throw at it and the value associated to throw at it and the value associated with that key it's kind of complicated with that key it's kind of complicated is the is going to be the index on that is the is going to be the index on that Ray so that if we indeed in need to Ray so that if we indeed in need to remove something from the set we can remove something from the set we can simply easily remove that from the hash simply easily remove that from the hash map but for the linked list we have to map but for the linked list we have to grab that index and do something to grab that index and do something to remove it you know in constant time so remove it you know in constant time so actually we're not gonna be really to actually we're not gonna be really to remove it because if we really remove it remove it because if we really remove it we're going to do another concatenation we're going to do another concatenation with the right-hand side shift every with the right-hand side shift every elements towards left by one so instead elements towards left by one so instead of doing this actual hard delete we're of doing this actual hard delete we're gonna swap that element or is the tail gonna swap that element or is the tail element on the right the the real last element on the right the the real last element on the right and since that this element on the right and since that this swap it you could be doing constant ID swap it you could be doing constant ID but after the swap we have to update the but after the swap we have to update the hash map as well so that next time we're hash map as well so that next time we're looking for the tournament it's no looking for the tournament it's no longer there but it's in this particular longer there but it's in this particular previous deleted elements position so we previous deleted elements position so we need to basically have the hash map and need to basically have the hash map and the linked list and the array sorry in the linked list and the array sorry in sync with each other so any operation we sync with each other so any operation we have to update those by full again get have to update those by full again get rendon it's going to totally operate it rendon it's going to totally operate it on the on the on the array yeah so that's pretty much on the array yeah so that's pretty much it it I don't think I need to really draw I don't think I need to really draw pictures that's a pretty simple so go I pictures that's a pretty simple so go I got a hashmap got a hashmap and I just getting lazy lazy today so and I just getting lazy lazy today so variable name is terrible so it's this variable name is terrible so it's this Python here again benefits it just Python here again benefits it just append elements to the end and the we append elements to the end and the we don't need to keep track of the number don't need to keep track of the number of elements it just called the size the of elements it just called the size the list here is basically a array and the list here is basically a array and the linked list hybrids and it's pretty linked list hybrids and it's pretty handy the hashmap it's a dictionary they handy the hashmap it's a dictionary they are all empty in the beginning that's are all empty in the beginning that's improved documentation a little bit so improved documentation a little bit so for insert we we can have first do the for insert we we can have first do the check check let's see that I'll get rendered first let's see that I'll get rendered first because it's I think it's easiest amount because it's I think it's easiest amount all so we just Brandon randomly choose all so we just Brandon randomly choose the number from the list from the Python the number from the list from the Python list so that's okay Brendan in constant list so that's okay Brendan in constant time insert we do the checking oh here time insert we do the checking oh here we also need to return the boolean we also need to return the boolean indicator whether this operation indicator whether this operation succeeded or not so if what is in the in succeeded or not so if what is in the in the hash map that means we wouldn't the hash map that means we wouldn't really do the insert we return false really do the insert we return false otherwise we'll do some actual work and otherwise we'll do some actual work and the return true the insert is going to the return true the insert is going to be we can append on this valley to the be we can append on this valley to the end of the link the list here Python end of the link the list here Python list or for array is just going to list or for array is just going to replace the ends of value very last replace the ends of value very last location with this replace the whatever that random value is this value and update the hashmap so that the next time you want to check whether do we have this value if we do have that where is it on the array this is gonna tell you that I thought that this particular location here so and given that this insertion moment is going to be the tail at the end of the elements on the array so that's insert and then we do the remove first thing first is to check whether we have actually have this value so if it's actually on there we need to do is to do a swap and then to update yeah so let's create an earlier here create a reference so that I don't want to type itself over and over again so what are we gonna do let me actually just draw a picture so let's say that we are doing the lead of not value of four we have something that's tell about six on the yeah something like this the noted there yeah something like this the noted there is the stuff on the hashmap the key is the stuff on the hashmap the key value pair are the key on the hashmap value pair are the key on the hashmap the it's pointing to the index where the it's pointing to the index where this number four located in the array this number four located in the array and we got the other one that's pointing and we got the other one that's pointing towards that element the six is the TEL towards that element the six is the TEL element so to to actually perform this element so to to actually perform this like there are so many little text box like there are so many little text box here oh geez what anyway just forget about that one if we actually wanted to remove this for what we would do is to drifting today so we will do a swap not really swap but just copy would be fine so we copy the lost elements Valeo to are here and have six two points here so that's that's what we do after that we just remove this node with this link and remove the very end ah come on yeah so that's that's what we do we copy the last tail elements Vario towards this division location and have the last that the key for the last value points to this new location then delete delete this and also delete the rare loss the body so that's that's what we do here in the deletion so it so the array here at the ball here this so the array here at the ball here this is this is the this is what this is this is this is the this is what this is this this location the value up to this this location the value up to this location we change that to that thing that's the last last elements on the on our list you will be the ends elements if you keep track off a number so that's a that's this this by doing this assignment that we changed we moved to six would copy the six to this but the particular location the second thing we need to do is to update the value for the key value pairs with the key insta six over there so it will be and the you know the original so this is the link as associate with this thought six we're gonna put that into this location this location is we can find the index by looking up the volume and yeah and then we're just gonna remove the useless stuff right now so yeah so that's that's it we copied the last elements value to this location the deletion location and then we update the hash map so the the value that's pointing to the original tail is now pointing at this deletion position and we pop the last element from the list also delete this key value association in the hash map alright so that looks right one two one two does it really should be something like does it really should be something like two we have the Rendon set we insert one two we have the Rendon set we insert one we remove two because it's not there we remove two because it's not there it's not gonna do anything we insert two it's not gonna do anything we insert two so we have one two we get Rendon we get so we have one two we get Rendon we get one so we will get Rendon and then we one so we will get Rendon and then we remove one we answer to the only thing remove one we answer to the only thing that's there is to what we call get that's there is to what we call get Rendon we should be able to return to Rendon we should be able to return to why I'm not returning to okay let's see why I'm not returning to okay let's see [Music] and the true forces right right true true false true true false true true false true false true or true false true the the true forces for right but that the valley will actually be returned as did I mess up somewhere okay I think it's the insertion that's okay I think it's the insertion that's that's problem if I just insert one that's problem if I just insert one thing the rare first thing I append this thing the rare first thing I append this so the list have become size one and the so the list have become size one and the lens is going to be one then the index lens is going to be one then the index does messed up okay to do want to yeah does messed up okay to do want to yeah this looks right now as submitters all this looks right now as submitters all right oh yeah I messed up with this step right oh yeah I messed up with this step so I have to create this Association so I have to create this Association first then to the update and and do this first then to the update and and do this okay I should be more careful but anyway okay I should be more careful but anyway that's that's this question | 2024-03-24 11:50:02 | 380 | Leetcode 380 Insert Delete GetRandom O(1) |
|
WF9KY4Q2a_I | Hello hello guys welcome brother video daily follow problem in it online correction problem in it online correction tree which aims and objective of this content does tree which aims and objective of this content does fit for as a result of written test for example connected to two to two to 9 tree tree tree nov23 that which that which that which Difficult Note Such Cycle In This Case Vanshu Connect This Is It Dozen Reminder Cycle Pred God This Problem You How To Remove The Best Wishes Mosted 238 Remove Discretion Commentary Pansap's Election This You Can Group Also Remove The 123 123 123 123 love you love you to remove the last witch makes it a point to to remove the last witch makes it a point to solve problem question ok me too you free me question ok me too you free me connected to food divine one witch connected to connected to food divine one witch connected to kurla from it twist vada president minute kurla from it twist vada president minute reducers side this cycle reports reducers side this cycle reports from one you can come from one you can come from one you can come no tension no someone will come back to remove from you can not come back to you you can not come back to you can only can only be used for the be used for the candidates and candidates can be the words of various problems in problems in the the lost in lost in lost in the Order in the Giver Who is Applying for a Date Su Play Beloved Festival City Interview and Wide and Lots and When You Make Corrections and to Make the Order of Law and Order in Which to Make the Order of Law and Order in Which Is the Best Love You you love you love you two two two two two two two two two two baikunth vote soft lips teacher graphical baikunth vote soft lips teacher graphical representation and will see what they are representation and will see what they are doing ok suryavansh connected to right ok doing ok suryavansh connected to right ok so initially top separate and tourist so initially top separate and tourist places two elements places two elements places two elements drop connected fennel liberation loot within 10 minutes okay or watch the video connected two three one candidate from country to country from this one candidate from country to country from this is not from being is not from being connected okay so basically graph one connected okay so basically graph one To three and set aside from this To three and set aside from this pushkar dies in na carolina selection of same areas you want to the latest connect 3434 and pattern 123 overall development in patna bihar correction print serial to near forest hotspot of the same thing for Your Your Your 12345 Latest 1414 You Already Have One Two Three Four Connected To India Against Corruption From 124 A Long And Even 1234 So Definitely Subscribe E Agree With U Back Side To Zaveri To Manoj Gautam Today Cycle To School Do CAN BE REPRESENTED AS A REPRESENTATIVE AND 12345 12345 EDDY Austrian Airlines Loss Return Return Of The Day Madam Sundha Okay All On The Side Half Inch Dia Element Honda Motors Jingle All The Note Website Website Website All The Paranoid Sudhir Way All No Different From What Do You Okay What You All The Paranoid Sudhir Way All No Different From What Do You Okay What You Want To You Are Going Want To You Are Going To Process Fast Subscribe To Latest Dad To Process Fast Subscribe To Latest Dad 121 121 121 121 121 Basically To You Are You Will Go Towards This Offspring Pickup The Parents To Give Anything For Having Give Anything For Having Give Anything For Having No Differences Of One Or Two For Simplicity No Differences Of One Or Two For Simplicity And And 182 182 Subscribe Now To To To To To To To To To To To To To To To To Parents 1.30 Parents Units Parents 1.30 Parents Units Sudhish Kumar And Different Parents Means The Sudhish Kumar And Different Parents Means The Difference Parents Laker Representatives Difference Parents Laker Representatives S Part S Part S Part President Over Into Three Do It 323 323 Subscribe Subscribe To Saudi Arabia * Stop Attack Train To Saudi Arabia * Stop Attack Train Begusarai To The Year In Different From Begusarai To The Year In Different From Inside A Small Cycle Of Wheat From Inside A Small Cycle Of Wheat From Notice To Live Whole Life But This Notice To Live Whole Life But This Correction Correction Correction Corrections Worldwide Collection Awake And Independent Of This Wonderful School Festival Notes For Exam Note 4 K Bheda Notes For All Chuttu Na For Parents Also Welcomes One Of This Land In The Is The What Meaning Of The Word Connected Meaning Of The Word Connected 4.11 More Quality Connected Pooranmal And Already Quality Connected Pooranmal And Already Connection Records Where Are In The Same Connection Records Where Are In The Same Parents OK Notification Ball Cycle OK Parents OK Notification Ball Cycle OK OK OK Twitter The Video then the Page the Page if if you liked The you liked The Video Video then the Page Video then subscribe to the Page if you liked The Rule 10 You 345 Okay Darling Say Part of the Friends Friends Okay Thank You 12345 But It's 2121 12345 Subscribe The Water Brings Up To Way Strict Taste Will Change It's Thoughts Part Too Taste Will Change It's Thoughts Part Too Taste Will Change It's Thoughts Part Too Different It Will Help You They Students Have Fun With Different It Will Help You They Students Have Fun With Acids And They Make A Great Ones Upon It's Acids And They Make A Great Ones Upon It's Real The Forest Which Will Give It's Okay Real The Forest Which Will Give It's Okay So It's Better To Choose Which Would Request That E Support You So It's Better To Choose Which Would Request That E Support You Want To Find Different Want To Find Different Facebook Facebook Facebook Pants Off White Widow Admission Process and Want to Find the President of HSU Travel Through Which They Will Take Off Its Husband Travel Through This Will Take You Three Steps for Its Soldiers Will Give Better Time Give Better Time Give Better Time Give Better Time Complexity Now Another Issue Travel Through This Complexity Now Another Issue Travel Through This Website Will Take Steps To Reach Is The Website Will Take Steps To Reach Is The President President Dance For Kids Four States Should Not Be Too Dance For Kids Four States Should Not Be Too Basic Which No Decide Left Side To Basic Which No Decide Left Side To Grand Vision No Decide Loop And Left Side Grand Vision No Decide Loop And Left Side Results Included In The Ashwagandha Height Results Included In The Ashwagandha Height Results Included In The Ashwagandha Height the Note Weight Should Remain Same and You Can Find It Should Recite Maxims and Try Doom Notes Problem and Try Doom Notes Problem Late for Rich Late for Rich Man Subscribe mid-2012 Good Plus Serial Gift From One Officer This Potato Boil More than 120 It's Amazing Love Front Of Front Of giver is I late to dare given there side effects pizza bread given to withdraw from this element 231 don't forget to subscribe element to and parental already tagged element to and parental already tagged that you can simply do been curved under current that you can simply do been curved under current acidity acidity Ki problem ko simple simple simple simple and finally you all the best shubhendu subscribe baith pati fearless soul simply aapke detail flashlights ki for for elements trying to subscribe subscribe top top in the middle of the aggressive aapke ki porn site rating Pendent in final elegant different Pendent in final elegant different Pendent in final elegant different civil defense department but this civil defense department but this time you tried to find the length of time you tried to find the length of department for fluid notes23 What is department for fluid notes23 What is the rate of wave the rate of wave fight Shri 420 1617 subscribe this Video Please hua hai hua hai ki undeclared and fire i ki undeclared and fire i know that in date of high school pass idol miss you a subsidized rates amused to see what will be the end morning here morning here is that being given and Vijay achi tan left is that being given and Vijay achi tan left side good to 10000 that Mukesh working side and latest update is updated on switch working fine ok no less previous switch working fine ok no less previous incremental optimization project simple incremental optimization project simple elements in place of define the term elements in place of define the term cream and assist you can have tried to your cream and assist you can have tried to your voice over to rent from within their lives voice over to rent from within their lives in future in future in future Land Of Every Element Is Mantra Kauleshwari One Elementary But When You Come In Treatments Algorithm Changes What Is The Me The Me The Back Subscribe Play List Ko Bajao Hu Is The Singer Smaller Height Complete The Set Hai One so you are to connect One so you are to connect One so you are to connect p2p force intelligence to subscribe to subscribe to the Page if you liked The Video then subscribe to the Page if you liked The subscribe to the Page Apni Bluetooth Idles But Improvement Trust Suream Of Speed2 OK Built In Vid U So now cash withdrawal should be understood that C Gas Service simple that Spiderman series is working side Bluetooth | 2024-03-20 16:07:43 | 684 | Redudant Conenction Leetcode Disjoint Set Union by Rank Explanation + Code C++ |
|
wvsEGZFSkjc | Hello Hello Everybody Welcome To My Channel It's All The Problem Ministry Platform The Problem Ministry Platform No.1 500 Design Effects Upon Receiving No.1 500 Design Effects Upon Receiving Minimum Element In Time For This Post Is Minimum Element In Time For This Post Is Limited To Remove Element On Top Top Limited To Remove Element On Top Top Top Element Minimum Elements In The Top Element Minimum Elements In The Recent Example Subscribe - 21000 Channel Recent Example Subscribe - 21000 Channel Free Leg Free Leg Free Leg first year erring district - to will be only water day or three left call the great man to minimum wishing all three elements - free software to return - than any porn in form will remove the three for absolutely top 10 Tourist NGO And Easy 10 Tourist NGO And Easy 10 Tourist NGO And Easy Call The Great Main Fuel Now Only To Our Call The Great Main Fuel Now Only To Our Minimum World Top 10 - 2 - 200 Will Minimum World Top 10 - 2 - 200 Will Implement The Channel Subscribe Not Only Not Implement The Channel Subscribe Not Only Not Distract You Don't Like Subscribe And Distract You Don't Like Subscribe And Share Vighn Tractor Minister For The Share Vighn Tractor Minister For The Post Of Top Live To Post Of Top Live To Attempting Or Starting Attempting Or Starting Attempting Or Starting you can wash today interview weather use this tax like library and the language in wealth tax or not doing them in effect 100 list start the first session with rising in library language subscribe our video hai vo subscribe normal operation operation and colleges in english Medium School Sports Minister Will Just Need To Every Step Question What Is Mean Stack What Will U Will Complete Three Elements From The Minister PK Element Absolutely Minimum And Current Elements Of Water Current Element And Chief Minister Ajay AP PK Element Is The Year So Let's Element Attack It On Medium Minimum Uniform Vanity Van Will Simply Like It And Elements Of Minimum 200 NS 200 Will Check Minimum Between - 26 - - - - - - Up To 20 Minutes From Subscribe Now To The Last Impression From Subscribe Now To The Last Impression Wooden Get Minute This Is - Two Way Will Send You Can Simply Implement Like My Video And Quality And Subscribe Now Don't See The Story This Time Like Subscribe Like This And Subscribe And Subscribe Do Not Wick Do Not Wick Do Not Wick events to sources say any thing you can find a solution but you want to do you want to the time minimum for solving in the creative works so well check every time is the current b is b is b is dip last minimum and updated and how it will dip last minimum and updated and how it will work so let's a distance initially it is som minimum is work so let's a distance initially it is som minimum is infinitive Who initially Who initially Who initially minimum element is this guide which hair infinitely minimum element is this guide which hair infinitely so and after that will update soon after this so and after that will update soon after this condition will oo everything will also adds condition will oo everything will also adds vaccine 98100 - - - 29 vaccine 98100 - - - 29 202 Bihar to insert blast minimum which 202 Bihar to insert blast minimum which will Id believe - to hair and when will the will Id believe - to hair and when will the element subscription Minimum distance from all evil elements Like Comment The Next To Me Quinn - To 9 Chapter Note Water Element Object Will Send - Not To Implementation Again In 2019 Subscribe Tweet Including School Staff And That And HIS LIFE VERY * ATTENTION HIS LIFE VERY * ATTENTION HIS LIFE VERY * ATTENTION CONSTRUCTOR MINISTER WITH FESTIVAL VYA IS CONSTRUCTOR MINISTER WITH FESTIVAL VYA IS DISTRICT WITH NEW STOCK MEMBER DISTRICT WITH NEW STOCK MEMBER CONSTRUCTOR PARTS DON'T KNOW YOU CONSTRUCTOR PARTS DON'T KNOW YOU WILL BE AMAZED SUBSCRIBE AND WILL NOT BE MAINTAINED WILL BE AMAZED SUBSCRIBE AND WILL NOT BE MAINTAINED AND UPDATED WITH POPULATION WILL BE ID PORN AND UPDATED WITH POPULATION WILL BE ID PORN KI AND TOP BUSINESS RETURN COMING IN STAGE DOT KI AND TOP BUSINESS RETURN COMING IN STAGE DOT ELEMENT ELEMENT In the assembly written in this he has also been written member implementation using vansh sexual member implementation using vansh sexual potency this code vikram point potency this code vikram point 200 his painting sometime aayenge this letter ko 200 his painting sometime aayenge this letter ko tarzan is type spelling life in a hai tarzan is type spelling life in a hai honey singh s9 plus you directly lets honey singh s9 plus you directly lets be confident amavas solution sizzling 100 be confident amavas solution sizzling 100 Babes Hot Operation In Wave And Storing Babes Hot Operation In Wave And Storing Subscribe Now To You Will Create A Subscribe Now To You Will Create A 200 Hair Will Create Three Variables Which 200 Hair Will Create Three Variables Which One Is Valentina Type Dividend Minimum Is One Is Valentina Type Dividend Minimum Is Stubborn Nodal Point For Next Notice Stubborn Nodal Point For Next Notice Like And Subscribe Initially Will Like And Subscribe Initially Will Start At No Additional With A New Chapter Of Class Math Explain Explain You are doing Math Explain Explain You are doing Math Explain Explain You are doing subscribe class 9 in which will work subscribe class 9 in which will work properly and which point to do subscribe properly and which point to do subscribe mode of internet mode of internet shravan ji node node which is later shravan ji node node which is later software will update date of birth and death 220 filmy desh ka 12512 valueab start minister also mean And this let me start Next this college And this let me start Next this college And this let me start Next this college nursing staff distinction changes reference nursing staff distinction changes reference next member constructor tender notice no next member constructor tender notice no evidence for private node subscribe evidence for private node subscribe minister will push subscribe channel help you help me Chinese slice held within you node help you help me Chinese slice held within you node of x9 body minimum value will check of x9 body minimum value will check of x9 body minimum value will check for him in the current person subscribe population will update play list operation population will update play list operation turn on the in come turn on the in come dot busy busy busy busy dot minerals subscribe to 210 will be compile judge take this compile and submit this expel access salts understand this Example with new Udayveer Singh 900 to 1000 is this point internal in the West Indies simply channel subscribe my channel like this which will love you two billion from this point to video like subscribe do not merge minimum - your hair neck mb to basis of this kind of bahujan mb to basis of this kind of bahujan increase in the state from his own this is increase in the state from his own this is solution without dresses with solutions also agree like solution without dresses with solutions also agree like for notification thanks for for notification thanks for watching a | 2024-03-21 13:25:30 | 155 | min stack | min stack leetcode | leetcode 155 | 2 stacl | 1 stack | no stack solutions |
|
CYQjRhISVv4 | hi friends welcome back today we are going to year record problem is 30 finding viewers active minutes on ka surya mandir lock for users actions only good and teacher's lock represented by today end year people where is a lock come is Set user with Set user with Set user with ID is performed and action add them in ID is performed and action add them in time after multiple users can perform execution time after multiple users can perform execution and sleep and single user can and sleep and single user can go for multiple options in 10 minutes the user go for multiple options in 10 minutes the user active minutes gives user-defined active minutes gives user-defined number of units minutes in which usage for number of units minutes in which usage for Deduction Liquid Minute Can Only Be Counted Deduction Liquid Minute Can Only Be Counted 151 Multiple Options Updated On You Are To Calculate One 151 Multiple Options Updated On You Are To Calculate One Indicated Answer Option Size K Indicated Answer Option Size K Sach That Point 6 And Lies Between One K Sach That Point 6 And Lies Between One K Inclusive Answer Is The Number Of Viewers To Inclusive Answer Is The Number Of Viewers To You A Em Quite Check Return Se Are Answers You A Em Quite Check Return Se Are Answers Describe with answer a is going to be starting with wonders why still alive when India got here and India got here and this arrangement lock six year notes and what answer is this arrangement lock six year notes and what answer is expected from porn let expected from porn let subscribe and have given and find some to commissioner SIM to commissioner SIM to commissioner SIM As You Can See The Output Air It's With Wave In The Sense The One Is When User Active Minute One Writes Objective Minute 1213 Day Four Day 5 Near Detroit 125 Is Given Two Years And Have Given All The Activity Of Law gives it's 8etude ring Law gives it's 8etude ring Law gives it's 8etude ring so so you know a what they are going to your you know a what they are going to your support well then calculate the support well then calculate the and user active minutes for example user and user active minutes for example user ID shift from one user ID to 0.50 kamo 510 comodo soft users who have made certain actions on second minute minute That in five minutes and 5 minutes That in five minutes and 5 minutes That in five minutes and 5 minutes if in duplication time just text only vansh if in duplication time just text only vansh you can take up and fascist hair to you can take up and fascist hair to per abuse activity minute isro to avoid you know how to handle the per abuse activity minute isro to avoid you know how to handle the duplication duplication share fennel user ID one's user ID zero you can see share fennel user ID one's user ID zero you can see Into Comma Five Into Comma Five Solid c14 User ID One Wear Singh Activity Solid c14 User ID One Wear Singh Activity admin2 Hand Minute 300 That's Why You For admin2 Hand Minute 300 That's Why You For User ID One Will Have Set Up To Only Is Here A Software Going To Solve This Problem By Using His Map Software Going To Solve This Problem By Using His Map Website The Giver Winter Website The Giver Winter And Its User And Its User And Its User interior and apps special here this is the question minutes for example user ID zero for example user ID zero will have actions on two coma five year rights and two come 500 600 800 550 duplicate it will handle it will only Have One Interview Ajit Seth And IF You Look At The Use Vansh User ID Vidhvansh Porn Bittu And Three Years Will Have Set To Just Have A Year So Let's Just Have A Great Year To Come Atri And Will Have To Written In The Like Usages r-day Like Usages r-day Like Usages r-day Arvind Tuesday Active Minutes When You Can See Arvind Tuesday Active Minutes When You Can See Users Who Have User Active Users Who Have User Active Minutes Two Rights of Michigan Minute 8 Minutes Minutes Two Rights of Michigan Minute 8 Minutes Service Portal 2 Minutes See Ujjwal Active Service Portal 2 Minutes See Ujjwal Active Similar User ID One is Also Active for Similar User ID One is Also Active for Two Minutes Which is the Second Minute and Two Minutes Which is the Second Minute and Third Third Third Soegi Sugar Syrup Effigy Group Name With All User Activity Minute Student Will Have To Use A Share Point To That 512 Enter Only Two Father For The Second Item Girl Picture Is Very Best Actually Shoulder Shul Printout Food And For Entries 304 pimple other is no Entries 304 pimple other is no Entries 304 pimple other is no user app from active minutes ago when your user app from active minutes ago when your right nose or active minutes 1345 plight hui right nose or active minutes 1345 plight hui winters who hair show the same logic winters who hair show the same logic point implemented festival point implemented festival air ingredient implemented servi air ingredient implemented servi short of villagers define the recent short of villagers define the recent visitors were going to you know how to visitors were going to you know how to Other member answer is a edit while Other member answer is a edit while elements with a verse and will find the map elements with a verse and will find the map wear appropriate we of key interior and value wear appropriate we of key interior and value from this top funders dry this video giving to from this top funders dry this video giving to capture user ID share and has stopped in capture user ID share and has stopped in teachers men's wear going to capture the teachers men's wear going to capture the user user user Users Active Force Second Minute Third Minutes OA Give Winners Other Software Into-Do Through The Like Share And We Are Going To Capture User ID And Minute Clear And Will Make Us Top Into User ID This user is User ID This user is User ID This user is not dare will just create now new here not dare will just create now new here state and will head for which day is state and will head for which day is active and will examine the entry into river map active and will examine the entry into river map containing entry for the user ID shoulder specified dare containing entry for the user ID shoulder specified dare devils retrieve the devils retrieve the state from the map and wherever you state from the map and wherever you Minute par and will again put the map of the Minute par and will again put the map of the entry back into the map heard and map entry back into the map heard and map ready day and Bihar police arrested to the ready day and Bihar police arrested to the map using a grater and they will get the map using a grater and they will get the entry of interior and safe in teacher a key entry of interior and safe in teacher a key and boy jewelery interest and boy jewelery interest and boy jewelery interest size of the self just size of the set will give us a how many minutes lettuce were active for example here here in Dishaon one in this case users active for 2 minutes side so let's get here and sincerity only Exam Hui Hai Business Exam Hui Hai Business Exam Hui Hai Business Tracking Vansh So Edit Arrangement Character Tracking Vansh So Edit Arrangement Character Result BCom Result SUC The Results Result BCom Result SUC The Results Starting From Starting From One Actually Mins User Activity Minute This One Actually Mins User Activity Minute This One Heres And That's Why You Have To One Heres And That's Why You Have To Subtract 1Share Yes And Will End In Just One Result So The implementation of to the two examples The implementation of to the two examples and a systematic and it's Mexico that and a systematic and it's Mexico that allergic works only examples of allergic works only examples of 108 giving us the correct answer so 108 giving us the correct answer so STRs on the discussion see the two is coming year STRs on the discussion see the two is coming year default it's like and default it's like and to activity for like to activity to activity for like to activity minutes minutes minutes Correct Result Español Discussion Should That This Research Solution God Accepted So This Is The Way Can That This Research Solution God Accepted So This Is The Way Can Solve All The Finding That Uses Solve All The Finding That Uses Active Minutes And Its Problem 1817 On Active Minutes And Its Problem 1817 On Dilip Code Wikinews Them Samay Pendra Set To Dilip Code Wikinews Them Samay Pendra Set To Solve This Problem Solve This Problem IF IF IF You Like My Solution Please subscribe The A New Problem Solution A New Problem Solution Notification I Don't Like The Notification I Don't Like The Poster Its Solutions To Problems Related Interview Questions And Answers You Are Interested In This Material | 2024-03-22 17:15:49 | 1,817 | LeetCode 1817 Finding the Users Active Minutes - Java Solution Using HashMap |
|
LjvC0wmKI7U | hey hey everybody this is Larry this is me doing an extra prom on December 1st me doing an extra prom on December 1st about about 2022 I don't know if I have to think 2022 I don't know if I have to think about the year but about the year but um all right let's do a medium one today um all right let's do a medium one today because I'm kind of just warming up for because I'm kind of just warming up for the Advent of code let me know if you're the Advent of code let me know if you're doing the admin of code if you don't doing the admin of code if you don't know what it is just Google admin of know what it is just Google admin of code I guess code I guess um okay so yeah let's and now that I um okay so yeah let's and now that I premium it I might do a premium one so I premium it I might do a premium one so I my apologies if you don't have premium my apologies if you don't have premium but you could you know we could all look but you could you know we could all look at it together is this how this is at it together is this how this is actually not a premium one is it because actually not a premium one is it because I don't see a I don't see a premium logo I don't know if that's true premium logo I don't know if that's true so I don't know but let me know uh if it so I don't know but let me know uh if it is but anyway so today's bonus question is but anyway so today's bonus question from Larry is 1361 validate binary tree from Larry is 1361 validate binary tree notes so you have n binary tree notes notes so you have n binary tree notes I'm zero than one you have a left child I'm zero than one you have a left child I why we don't show if only all given I why we don't show if only all given note from exactly one valid binary tree note from exactly one valid binary tree okay so what does this mean okay so what does this mean um okay so we have to figure out um what does it mean to be a binary tree note that the notes have already okay note that the notes have already okay fine fine um but the wood always true zero um but the wood always true zero I guess not in this case I guess not in this case um and you can have a case where um and you can have a case where um I guess just three but copy this case um I guess just three but copy this case where where um um yeah negative one negative one and then yeah negative one negative one and then that should be yeah okay fine that should return true right okay I just want to make sure so then now first of all we have to find the root of the problem get it but um yeah so what does it go negative one four um index left right and enumerate left child my child let me make sure that I'm I'm recording okay uh okay so then if left um is equal to negative one and white is equal to negative one then root is equal to index um maybe um what I mean is that if root is equal to negative one whoops temperature is equal to index otherwise we have two roots and then you want to return Force right wait don't mess that up no yeah huh wait I did mess that up because negative one negative one means that yes so it means that it is a leaf not that it has no child so I messed that up okay uh let me actually put in the test case to um confirm what I said before so this is actually zero then confirmed that this is still true okay um oh I just needs to be a sip okay so this is still true I just want to make sure that that's the case okay I think I messed up with the root um root is basically the one where there's no in degree right so we just have to maybe measure the in degree as well then um as you go to zero times N I like big ends and not lie um so yeah so okay let's rephrase this one so then in degree of left in command by one and degree of Right Where I'm on okay we didn't actually need index on this one forget um so let's take it out so we will need it again so yeah uh oh I had to do some checks on uh oh I had to do some checks on negative one actually but I but negative one actually but I but otherwise this is mostly good otherwise this is mostly good other than the tough cases uh this is other than the tough cases uh this is other than the special case this is other than the special case this is almost good almost good uh okay so then now we just for uh okay so then now we just for um for index in range of n right so if um for index in range of n right so if in degree of index is equal to zero then in degree of index is equal to zero then root is equal to index root is equal to index if if root is equal to negative one else return Force right meaning that we have two Roots okay so then now we have this rule then we just have to go um go down the tree right just a defrost search so yeah I mean I don't think that's bad so yeah just traversal um yeah and and here we can just do you um yeah and and here we can just do you know current node and and parents maybe know current node and and parents maybe or parent or parent um and then basically a Traverse like a um and then basically a Traverse like a Spell correctly Spell correctly um left of node node Traverse right no no wait something like this um except for basically um you can go backwards but if you have seen the the know that you're going and that's no bueno so let's kind of set it that way so basically we have a scene array um and you can pass it and be like I don't know it doesn't really matter times and right um and Damage Reverse um and Damage Reverse negative one I guess we don't need the negative one I guess we don't need the pound in that case I thought maybe we pound in that case I thought maybe we could prevent it from going upwards but could prevent it from going upwards but it may just have a like a three node it may just have a like a three node psycho or something like this right so psycho or something like this right so we just have to make sure that this we just have to make sure that this there's no uh no thing so yeah so if there's no uh no thing so yeah so if scene of left of scene of left of foreign then we return force or something like um um yeah yeah if if not not then we return first then we return first um I guess we could have combined into um I guess we could have combined into one statement let's do that alone copy and paste you know otherwise this is good so let me just return this maybe um it's not quite yet I think that's mostly right but can you have multiple I guess notes could be off by themselves I guess notes could be off by themselves right so I think that's the other one right so I think that's the other one um that's what I mean by so and or seem um that's what I mean by so and or seem so if we've seen everything then that so if we've seen everything then that should be good I think a scene of love should be good I think a scene of love no just another no left child whoops look n is 10 to the fourth it might not be the oh well no that's I mean oh well no that's I mean I I don't know that this is good enough I I don't know that this is good enough but it still this is still very well but it still this is still very well um because we forgot to um because we forgot to um um we forgot to set the scene thing okay so this is wrong still but um let's so I this is returning Force do I have a so I this is returning Force do I have a typo anywhere let's see I misunderstood it zero one two foreign [Music] why did I do it this way didn't I oh I mean so the answer is that I thought we I thought I checked for this did I checked for it somehow maybe I guess I checked for here instead whoops I just forgot to check for negative one okay so let's give it a submit uh it looks good um this is linear time linear space we look at every node once both in the traversal I mean that's just how traversos you know generally go I don't even complicate it so it looks every node once linear space because of the scene away and I think also the in degree away and of course this is linear we just look at each node once I was quick on that um so yeah um yeah linear time linear space that's all I have with this one so let me know what you think um yeah if you don't have enough good luck uh otherwise uh also just good luck in general I hope y'all have a great rest of the December so yeah come hang out with me stay good stay healthy to good mental health I'll see y'all later | 2024-03-21 00:38:29 | 1,361 | 1361. Validate Binary Tree Nodes (Leetcode Medium) |
|
fMU8gydbURU | all right let's talk about partition label label so your given string of lowercase so your given string of lowercase english later is given english later is given so you need to return so you need to return the partition so for this a b a b the partition so for this a b a b c b a c a right c b a c a right the string the partition string the string the partition string is at most as possible so let each is at most as possible so let each letter appear letter appear in at most one time so in this case in at most one time so in this case every letter inside the inside a every letter inside the inside a string appear in at most one time string appear in at most one time and then in this string it's at most one and then in this string it's at most one time time which means there is no actual d e f g which means there is no actual d e f g on other sides right so in this example on other sides right so in this example we can see we can see i can make sure i keep updating my i can make sure i keep updating my character character position so if a write a position so if a write a appears at 0 but a appears at appears at 0 but a appears at 2 so i update the a to 2 so i update the a to the position 2. so if a the position 2. so if a hit the position 8 i know everything hit the position 8 i know everything is already inside the substring so i can is already inside the substring so i can put the insert into my list put the insert into my list so the idea is this i have a so the idea is this i have a counting rate and then in this container counting rate and then in this container array i and then i store the char c for this char at and i and then count c minus a and this time we equal to i right position right so a character a minus a would be zero zero equal to zero but with character a again it would you would become two right now let's do the integer list new array list for the answer and we need this option right because we cut into partition right so ins that we can start from zero that would be it so in i equal to zero that would be it so in i equal to zero so i need so i need to loop through again to loop through again so i need to see if n so i need to see if n at least puts at this character if n at at least puts at this character if n at least character least character is actually the length of the itself is actually the length of the itself all the position i found so say it's the all the position i found so say it's the chart at chart at high minus a where everything high minus a where everything should be inside the count should be inside the count counting array right so for the example counting array right so for the example a a minus a 0 right and we already know the last character inside a is 8 right is is uh is eight from zero to eight and then is nine so we know the last one the last character it appears in this substring is eight so if i equal to n right we can just add the length of it itself so a minus zero plus one right and then we we need to increment and we need to um change the value for star so it's m plus one we are no longer need this character so we're starting from new character which is d so d is the position you we want we want to use and what else we just return this right and i don't have typo right all right pretty good so let's talk all right pretty good so let's talk about talk about time and space about talk about time and space space is all of 26 should be constant space is all of 26 should be constant all of one and you just add shouldn't be all of one and you just add shouldn't be a problem a problem time out of n in time out of n in for for this loop because you are traversing every single character in the screen and this is as well so all the fun because there's nothing inside the loop when you traversing choppers in the length of the s right so you just keep changing the count which is your n and then to see if i equal to the value which is the maximum for the character you found if that is you just add | 2024-03-21 16:01:39 | 763 | LeetCode 763 | Partition Labels | Counting Array | Java |
|
IyG1JrD3lQ8 | lead code 1854 maximum population year so the question is say that you'll be so the question is say that you'll be given uh an array which is nothing but a given uh an array which is nothing but a log of people log of people who uh were born and the year they were who uh were born and the year they were they died in so this array is something they died in so this array is something like this so it gives details about each like this so it gives details about each person say a person say a person person took birth in took birth in 1993 and died in 1999 okay so that would be the first person the second person would be say 2000 and died in 1998 and died in 1998 and died in 20 12 and say the fourth person is 20 20 12 and died in 12 and died in 20 23 okay so this is an example that 20 23 okay so this is an example that will be provided to us we have to figure will be provided to us we have to figure out what was what was the year where the out what was what was the year where the population was maximum right population was maximum right so what I'll do is this seems to be in so what I'll do is this seems to be in sorted array as of now but no it is not sorted array as of now but no it is not sorted there's 2,000 year there's 1998 sorted there's 2,000 year there's 1998 here yeah so this is how the input is here yeah so this is how the input is going to be I need to find the year in going to be I need to find the year in which the population was maximum so how which the population was maximum so how could I figure out so looking at this could I figure out so looking at this array what I can say is array what I can say is 1993 the population was 1993 the population was one then one then until uh until uh 1998 the population increased to 1998 the population increased to two right so 1993 the population was two right so 1993 the population was 1 1998 the population increased to two 1 1998 the population increased to two 1999 it decreased back to one because 1999 it decreased back to one because the first person died here right then 2000 year 2000 it increased Again by one right 2000 10 it in died and died and then then in 2012 this person who was born in 1998 that died right so 2012 it reduced to zero but then 2012 another person took birth okay so the population in 2013 was 1 okay oh sorry 2012 was back to one because one person died and one person took birth so it did not change at all and then 2023 is when it came down to zero so which is the first year where population was the highest it was in 1998 right there are two years where the population was highest but we need to return the first year first time the population was highest so 1998 this is the year and end right so if we see what did we end right so if we see what did we do we do we sorted this all the values by the sorted this all the values by the year and then continued figuring how year and then continued figuring how many many people uh continued updating the people uh continued updating the population and checking the population population and checking the population and returning the max year where the and returning the max year where the population was maximum this is exactly population was maximum this is exactly what we can do in code as well right so what we can do in code as well right so what we can do is we what we can do is we can I can create can I can create a create a create a AR okay I can name it a AR okay I can name it BD okay births and deaths so BD would include uh triple the tle would include what would it include let's see so for every log in logs first of all I'll create an array of births so tle will include log index zero because Zer is where they talk about the tell about the year in which the person was born so we'll take the birth year and set it to one because we'll be increasing by one so I'm setting the second value by to be this another array which will include this another array which will include the debts so the debts so for log in for log in logs and here what I'll set is I'll set logs and here what I'll set is I'll set it up CLE with log of index one which it up CLE with log of index one which gives me the year of death and the value gives me the year of death and the value would be minus one because I would be would be minus one because I would be reducing my population by minus reducing my population by minus one so now I'm creating an array such one so now I'm creating an array such that BD is the ARR says that it has got that BD is the ARR says that it has got Tes where there is your mentioned and Tes where there is your mentioned and there is + one and minus one mentioned there is + one and minus one mentioned for birth and for birth and death this the length of BT would be death this the length of BT would be double of L LS because in logs in each double of L LS because in logs in each record we are getting birth and death record we are getting birth and death both while in BD we are separating out both while in BD we are separating out one record would either have birth or one record would either have birth or either have death right so after this either have death right so after this what I'll do is I'll sort BT okay so what I'll do is I'll sort BT okay so sort PD what will it do it will sort PD sort PD what will it do it will sort PD by the first element which is the by the first element which is the year and if there is any conflict in the year and if there is any conflict in the year in the first element it will check year in the first element it will check for second element for second element right so second element will either be right so second element will either be minus1 or + one so it will take the minus1 or + one so it will take the depth value first which is depth value first which is minus1 and minus1 and then after it plays the birth value then after it plays the birth value which is+ one that is exactly what we which is+ one that is exactly what we want to be able to figure out want to be able to figure out the uh the uh the maximum population at each year okay the maximum population at each year okay so now what I'll do is I'll so now what I'll do is I'll initialize Max initialize Max population to be population to be zero I'll initialize current zero I'll initialize current population to be population to be zero and I can go for uh for each login for BD for login BD can check the current population so can check the current population so current population will be I'll update current population will be I'll update the current population first current the current population first current population would be population would be log index it would be I would log index it would be I would add uh log at index one okay so either + add uh log at index one okay so either + one or minus one will be added to one or minus one will be added to current population current population right and if current right and if current population is greater than Max population is greater than Max population then it will update Max population then it will update Max population with current population with current population and I also maintain a population and I also maintain a variable called variable called year which will store the max max year year which will store the max max year so whenever Max population is updated so whenever Max population is updated I'll update here with I'll update here with the current year so current year would the current year so current year would be log at index zero be log at index zero right so that means when the for Loop is right so that means when the for Loop is complete and it has gone through each complete and it has gone through each element it would have got Max population element it would have got Max population and the year in which that Max and the year in which that Max population was that'll return the population was that'll return the year and that's it let's run this and see and that work for the test cases and that worked 15 milliseconds better and that worked 15 milliseconds better than 98% of solutions that's how you than 98% of solutions that's how you solve this solve this problem 1854 maximum population years problem 1854 maximum population years see you in the next video | 2024-03-25 10:53:45 | 1,854 | Leetcode 1854. Maximum Population Year |
|
Uj3eqf31t5k | [Music] what's going on everybody zane here back what's going on everybody zane here back with another video for this one we've with another video for this one we've got question number 202 which is happy got question number 202 which is happy number on lead code so we need to write number on lead code so we need to write some algorithm to determine whether or some algorithm to determine whether or not a number that we're given is happy not a number that we're given is happy a happy number is essentially going to a happy number is essentially going to be be its numbers like if there was a number its numbers like if there was a number one nine its numbers one and nine one nine its numbers one and nine if we just square those two numbers and if we just square those two numbers and then add them together then add them together if that will eventually get to a point if that will eventually get to a point where it'll endlessly loop or it'll end where it'll endlessly loop or it'll end it a one it a one so here's what i mean if we look at this so here's what i mean if we look at this example of 19 example of 19 we've got one and nine so if we do one we've got one and nine so if we do one squared plus nine squared that'll be 82. squared plus nine squared that'll be 82. that's our next number so our next that's our next number so our next number after that would be eight squared number after that would be eight squared plus two squared which is sixty-eight plus two squared which is sixty-eight then six squared plus eight squared then six squared plus eight squared hundred and then finally we've got one hundred and then finally we've got one zero zero so one squared will be one zero zero so one squared will be one plus zero zero squared and plus zero zero squared and zero squared again zero squared again it'll be one so that'll eventually get it'll be one so that'll eventually get to a point where the value where the sum to a point where the value where the sum will speed stuck at one will speed stuck at one then the other example here is where n then the other example here is where n is equal to 2 so is equal to 2 so 2 sum is going to be 2 2 squared is 2 sum is going to be 2 2 squared is going to be going to be 4 then 4 squared it'll just continuously 4 then 4 squared it'll just continuously go increase and it'll it'll stop at go increase and it'll it'll stop at obviously the maximum value here but uh obviously the maximum value here but uh that's what they mean by endlessly in that's what they mean by endlessly in the cycle the cycle so how are we going to tackle this well so how are we going to tackle this well we actually kind of got the answer here we actually kind of got the answer here the first step is to really get the next the first step is to really get the next number number so in order to get the next number we so in order to get the next number we can actually create a helper function can actually create a helper function for that and for me for that and for me i can i can i'm actually happy that i i can i can i'm actually happy that i said helper function because before said helper function because before i was a little uh confused as to when i was a little uh confused as to when people said helper function ah damn i people said helper function ah damn i don't know what a helper function is or don't know what a helper function is or but essentially you're creating another but essentially you're creating another method another function that will do method another function that will do something for you without having to something for you without having to constantly copy the same amount of code constantly copy the same amount of code here so i can do something here then do here so i can do something here then do something again something again and again and again and again but and again and again and again but instead of doing that i could just instead of doing that i could just create create a function to do something a function to do something that can be called once that can be called once so so instead of us calling it a thousand instead of us calling it a thousand times we'll create a function times we'll create a function that will do something for us so let's that will do something for us so let's create a function to first create a function to first before we even deal with if it's happy before we even deal with if it's happy or not let's figure out how can we get or not let's figure out how can we get the next number the next number so i'll create another function here so i'll create another function here private and we're gonna return an int private and we're gonna return an int get next number get next number and this is going to take in some number and this is going to take in some number now what exactly do we need to do to get now what exactly do we need to do to get the next number the next number well we need to first take the well we need to first take the last digit last digit and and well it wouldn't necessarily be the last well it wouldn't necessarily be the last digit but we'll get all the digits and digit but we'll get all the digits and we'll add it to sum we'll add it to sum to some sum so to some sum so let's just create a sum variable and let's just create a sum variable and initialize it to zero initialize it to zero and we'll say that while we need to run and we'll say that while we need to run a while loop so whilst the number is a while loop so whilst the number is greater than zero we need to greater than zero we need to continuously do something so we wanted continuously do something so we wanted to continuously run in through this to continuously run in through this while loop while loop until we get to a point where the number until we get to a point where the number is now zero so that means we've got our is now zero so that means we've got our got our sum or got our value whatever got our sum or got our value whatever so in order to get the digit on the far so in order to get the digit on the far right right we should know that to get that digit we should know that to get that digit it would just be the number mod 10. it would just be the number mod 10. so now that is our number on the right so now that is our number on the right side side now in order to eliminate that number we now in order to eliminate that number we could just say num is just going to could just say num is just going to equal num divided by 10. equal num divided by 10. so now that number has been so now that number has been accounted for accounted for and has now been removed and we could do and has now been removed and we could do now is now is we can add our we can add our number two number two or our sum is going to equal our digit or our sum is going to equal our digit times digit so what we're doing here is times digit so what we're doing here is we're extracting the digit we're extracting the digit we're then removing it from our numbers we're then removing it from our numbers num num and then we're adding it we're setting and then we're adding it we're setting it to our sum and i think what we need to actually do here is we're going to add these so we don't want to just set it to some and then once that is summed up it'll continuously run through this and then we'll get to a point where we could just return our sum now this is going to get our next digit so now up here how can we tackle whether or not something is happy so first off what we need to do is we need to establish what we're going to use to solve this so when it comes to endlessly looping or a cycle or doing something constantly until we get to a point where things are done that's always a while loop for me so while something do something so in this while loop we want to make sure that n is not going to be one so while n does not equal one and what else well we need to think about what values we can store in some data structure to account for it either being endless or if it was already accounted for so what we could do is we can actually create a set so let me create that first and it should make sense afterwards i'm going to make a new hash set here and i'm going to say that while end does not equal 1 otherwise we break out of this loop and the set does not contain the number then we can continuously loop through which is going to be now we'll add the value of n here and now n has been added to our set now once that's been added what we could do now is we'll grab the next number so we can just do get next number n and we'll say that n is going to equal that next number and then continuously go through so this is what i meant by doing one function otherwise we'd have to copy all this and put this here which is a little bit messy and then we'll continuously have it get the next number get the next number add it to our set get the next number and as long as it's not in the set that means that it's infinitely looping and as long as n does not equal one that means it will never get to a one now if it does get to a one then okay then it's happy so just return n equals so let's run this see what we get so let's run this see what we get and submit and submit that's it that's it so let me recap real quick so let me recap real quick so our first step was to get the next so our first step was to get the next number we're not even dealing with number we're not even dealing with whether or not it's happy whether or not it's happy our next number is essentially going to our next number is essentially going to be a while loop we that we be a while loop we that we constantly perform constantly perform we'll extract the digit using the we'll extract the digit using the modulus modulus we'll now set number to be num divided we'll now set number to be num divided by 10 so that we've already accounted by 10 so that we've already accounted for that digit on the right side so now for that digit on the right side so now we can just remove it from the right we can just remove it from the right side side and then we'll say that the sum is going and then we'll say that the sum is going to be whatever digit is squared to be whatever digit is squared because that's how we get our next because that's how we get our next number we'll take the digit square it number we'll take the digit square it plus take the digit square it plus take the digit square it once we do that sorry i lost my audio there once we do that we'll add it to our sum and then we'll return our sum at the very bottom once we've done that then all we need to do now is account for two things the number is going to be happy if it's going to be endlessly looping or if it ends in one so as long as n does not equal one we can run a while loop and as long as the set does not contain the value we'll add the number to our set and then we'll get the next number and continuously iterate as long as it's not in the set and n does not equal one that means it'll continuously loop or if it ever jumps out return whether or not n is equal to one anyways guys that's it for this one if you have any questions comments feedback please let me know in the comments below otherwise hit that like and subscribe button show me some love and i'll see you in the next one peace [Music] | 2024-03-22 09:43:59 | 202 | 202. Happy Number - (Leetcode - Linked List) |
|
I9lj1JgHuNA | all right so let's talk about the sum of all of then sub array so you're giving a all of then sub array so you're giving a real positive integer array and real positive integer array and calculate the sum of all possible all calculate the sum of all possible all length separates so you have to return length separates so you have to return the sum of all of them sub array of the sum of all of them sub array of array so this question consisted pretty array so this question consisted pretty hard so i'm going to give this guy hard so i'm going to give this guy credit so this is a legend and credit so this is a legend and let's just dive into the example so let's just dive into the example so uh this is the array one two three four uh this is the array one two three four five so five so he actually actually um give us the he actually actually um give us the answer already so how many times one answer already so how many times one represent this is actually five times represent this is actually five times right and eight times for two nine times right and eight times for two nine times four three eight times again for four four three eight times again for four five times four five times four five right so this is k equal to i plus five right so this is k equal to i plus one times m minus i one times m minus i but somehow the off the often should be but somehow the off the often should be one three four five four three right let one three four five four three right let me just uh value three so one one uh one me just uh value three so one one uh one itself is actually length of one which itself is actually length of one which is all all length one two three is all all length one two three and then one two three four five which and then one two three four five which is three is three uh three times four integer one uh three times four integer one and how about two two okay two and how about two two okay two uh uh for lengthwise is actually one for lengthwise is actually one and then uh for one two three there's and then uh for one two three there's another one so it's two two three four another one so it's two two three four is another one which is is another one which is uh three uh three and one two three four five which is and one two three four five which is four right so you have all length is four right so you have all length is actually equal to actually equal to uh k plus one divided by two right so uh k plus one divided by two right so you actually determine uh what determine you actually determine uh what determine your uh your uh k k if k is actually if k is actually uh uh multiply two is actually equal to one multiply two is actually equal to one then you have to implement your fonts if then you have to implement your fonts if not not then you basically just return then you basically just return the even length right the even length right so this one so this one it's actually okay so this one's it's actually okay so this one's actually the same four and four so let actually the same four and four so let me say another one me say another one about five so about five so uh index two uh index three so in this uh index two uh index three so in this three you have to take five another four three you have to take five another four right so this is because what one two right so this is because what one two okay three the length of one is one okay three the length of one is one one two three is another one two three one two three is another one two three four another one so it's actually one four another one so it's actually one two three two three and three four five four and three four five four one two three four five is five right so one two three four five is five right so you have to take five instead you have to take five instead so let me just call it you'll be able to so let me just call it you'll be able to follow along so you have the return follow along so you have the return value which is original i'm gonna just value which is original i'm gonna just resort right now so i need what i need resort right now so i need what i need next for sure i plus plus so i will have to have the i will have to have one in this k equal to i plus one times n minus one uh a minus i right so this is actually representing one it's actually representing in star equal to i plus one almost n equal to so uh this will be pretty much it right so uh this will be pretty much it right so i also need to have a k okay so i also need to have a k okay repeating star time chain repeating star time chain right right so i will have to have a counter so i will have to have a counter so this is going to be my cons bounce so this is going to be my cons bounce represent plus or minus divided by two represent plus or minus divided by two right so i would definitely get my uh right so i would definitely get my uh even lens count for sure right so i have even lens count for sure right so i have average four for this one and four for average four for this one and four for this one but in this case in the off this one but in this case in the off index it's actually i have to implement index it's actually i have to implement by one this is because by one this is because uh due to the math right so uh due to the math right so it doesn't matter so if k mod 2 is at it doesn't matter so if k mod 2 is at equal to one equal to one times increment right com plus plus the times increment right com plus plus the return value is actually plus equal to return value is actually plus equal to count based on the cons count based on the cons multiply multiply the array i the array i so this will give me what so in this one so this will give me what so in this one in this example integer one you will in this example integer one you will represent how many times you represent represent how many times you represent three times right three times right so plus three so plus three plus and then four times two which is 8 plus and then four times two which is 8 5 times 3 is 15 right so this will be 5 times 3 is 15 right so this will be the answer the answer and this is pure math so if you don't and this is pure math so if you don't understand this is definitely fine understand this is definitely fine so uh so uh cannot find okay this is k sorry this is cannot find okay this is k sorry this is k right all right so let's all right so let's talk about time and space space is going talk about time and space space is going to be constant time is going to be all to be constant time is going to be all of n and represent end of the array and of n and represent end of the array and this is the question for the uh this is this is the question for the uh this is the solution for this question and i the solution for this question and i will see you next time bye | 2024-03-21 14:42:38 | 1,588 | LeetCode 1588 | Sum of All Odd Length Subarrays | Math | Java |
|
YMbMNTotp-8 | hey what's up guys uh this is chung here so so this time bitcoin number 1889 this time bitcoin number 1889 minimum space wasted from packaging minimum space wasted from packaging right right okay so you're giving like un packages okay so you're giving like un packages and and and you're trying to pull to place in and you're trying to pull to place in the in some boxes right so one package the in some boxes right so one package per box and then we you have like per box and then we you have like m suppliers and each produce different m suppliers and each produce different size of size of boxes okay and boxes okay and obviously a package can only be placed obviously a package can only be placed in a box if the size of the package is in a box if the size of the package is less or small or less than or equal to less or small or less than or equal to the size of the the size of the of the box and the package the package size are given as an integer array right so that's why you know the suppliers are given like as a 2d integer right so for each of the suppliers we have a list of boxes that supplier can provide and you want to choose a single supplier right and use the boxes from them such that the total wasted space is minimized right so the total wasted space is the sum of the space wasted in all the boxes right so basically there's a it's a difference between the actual size and the package size and then you summarize everything together okay so you just need to return the minimum total wasted space right by choosing the box suppliers optimally if it's not in if it's impossible to fit all the box packages right you simply return minus one okay and then you do a modular in the end so for example this one we have we have three packages with size two three and five and then we have two suppliers uh who will supply provide these two kind of different sizes right and so the optimal choose is the first the first one basically we choose the first one and then we use we use size four for for the first two we use size four for for the first two packages and then we use size eight packages and then we use size eight box for this for the last package that's box for this for the last package that's why the answer is six why the answer is six right and then yeah so here are some right and then yeah so here are some constraints right so the boxes and the constraints right so the boxes and the the packages they're both 10 to the the packages they're both 10 to the power of 5 power of 5 right and there are some like other right and there are some like other constraints here so obviously this constraints here so obviously this problem is that you know obviously we problem is that you know obviously we need to try to check need to try to check each boxes each supplier each boxes each supplier right but you know since we right but you know since we have 10 to the power of 5 have 10 to the power of 5 packages and we have packages and we have this many suppliers so suppliers is also this many suppliers so suppliers is also gonna gonna gonna be uh this many gonna be uh this many right and for each of the supplier you right and for each of the supplier you know for each of the supplier we could know for each of the supplier we could also have like 10 to the power of five also have like 10 to the power of five different size of boxes right so at the different size of boxes right so at the beginning beginning i was like you know there's no way we i was like you know there's no way we can check this one can check this one without causing the time tle without causing the time tle right because in total we have 10 to the right because in total we have 10 to the power of 5 power of 5 boxes of suppliers and then we have boxes of suppliers and then we have three suppliers we can have like 10 to three suppliers we can have like 10 to the power of five the power of five sizes right the box box sizes so there's sizes right the box box sizes so there's no way we can no way we can we can do it regardless and then i saw we can do it regardless and then i saw this one this one actually see actually see so basically the total the total sum the so basically the total the total sum the total different total different sizes of all box sizes across all the sizes of all box sizes across all the suppliers suppliers are also within 10 to the power of 5. right then what does this one mean it means that you know all we need to do is we just need to reduce this dislike n times n to somehow to unlog in right and then we can solve we can pass so how can we if uh so how can we if uh more efficiently find the check each of more efficiently find the check each of the boxes the boxes if we can config config if we can config config can put the uh some packages in into the can put the uh some packages in into the box right i mean obviously if we have some packages right for some packages we want to use the smallest box that can fit in this package right because we want to minimize the waste the total wasted space so which means let's say we have a package two three and five right if we have some boxes let's say if we have box three and the five this is the box right so for the package one obviously we want to use three right and then for three we also want to use three and then for five because three cannot hold 5 that's why we have to right so i mean now it's i think it's right so i mean now it's i think it's kind of we we can certainly do a binary search in this case right because assuming let's say we store the packages from the smallest to the biggest and then for each of the supplier we also sort the boxes from the smallest to the biggest and then we for each of the box side we can simply do a binary search right so for the binary search you know for example if we have three here right uh we do a binary search here and then for three if by just looking uh look at those kind of ladder uh the numbers we know for box three we can put two boxes into it which is this two right and then we with the with this two here you know we can simply calculate the uh the total waste right so since we have two boxes here you know the total of these two boxes size is five right and then for to use two size three boxes we have we have six that's why the the waist will be six minus five right and then after this one you know and then we can move to the we can move to the to the second one the second boxes for the second boxes here you know we need uh we're gonna we will we'll see five here right that's why we'll get the five in get the five the last package into the so in order to efficiently calculate to so in order to efficiently calculate to make this make this this thing work you know one thing is this thing work you know one thing is that you know that you know it could have like some several uh it could have like some several uh packages packages right so these are packages maybe for right so these are packages maybe for the first the first boxes you know we can uh put in the boxes you know we can uh put in the first two first two right and then for the second packages right and then for the second packages maybe it maybe it can conclude uh the next three can conclude uh the next three packages and then for the last one and packages and then for the last one and then for that for the next then for that for the next box size we can put the last two right as you guys can see here so we will need to get some of somehow the the range sum right which means we need to use a presump right pre-sum out of it and then besides the pre-sum we also need to maintain like a pre prefix pre index because you know you know for example at for this kind of box right we need to get the pre-index which is this one and then then we'll have to we'll have the current index which is this one so if we use a pre the current index subtract the previous index we get the get how many packages the current box can handle right so that's how we get this this six here and that's we can also use this kind of these two indexes to quickly get the the pre-sum of this of the total size of for this kind of packages and then whenever the index reached the end we know okay we have uh put all the packages in into the right so that's basically the idea right so that's basically the idea and we do a sort we do a presump and and we do a sort we do a presump and then we use binary search then we use binary search okay and one more thing is that so when okay and one more thing is that so when we use a binary search we use a binary search you know we want to use binary uh bisect you know we want to use binary uh bisect write write in python because let's say for three in python because let's say for three here right so for three here right so for three because for e even if it's the same size because for e even if it's the same size of the boxes we we of the boxes we we still want to include that packages still want to include that packages right that's why you know when whenever right that's why you know when whenever there's a there's the same value there's a there's the same value of the box size we want to use we want of the box size we want to use we want to move it to the right that's why we to move it to the right that's why we use a bisect right use a bisect right otherwise you know we'll get this one otherwise you know we'll get this one we'll it will exclude this three we'll it will exclude this three which is wrong right for this side three which is wrong right for this side three box box um yeah i think that's pretty much it is um yeah i think that's pretty much it is right right so first we sort the packages okay so first we sort the packages okay dot sort uh and then dot sort uh and then we have a pre-sum right so this time i use the uh the array type basically you know to prefix with zero and then for the length of the packages okay we do a length of the packages and then for packages in we do pre-sum dot append we do pre-sum dot append okay and then pre-sum dot minus uh okay and then pre-sum dot minus uh minus one plus p right that's how we do minus one plus p right that's how we do with the presump and yeah and then we we just need to you need to check the uh each box right you need to check the uh each box right so for each box so for each box in boxes right which means which means in boxes right which means which means is the supplier right we sort is the supplier right we sort we stored the all the box size we stored the all the box size we can simply do a quick check basically we can simply do a quick check basically you know you know if if the the biggest box if if the the biggest box is still smaller than the package then is still smaller than the package then then the biggest packages right that then the biggest packages right that means that means that this supplier cannot handle all the this supplier cannot handle all the packages packages that's why we can simply continue right that's why we can simply continue right so this is like simple so this is like simple check but i yeah i think this one will check but i yeah i think this one will not affect the final not affect the final time complexity and then we have the time complexity and then we have the pre-index pre-index equal to zero and then we have our equal to zero and then we have our cost right work cost right work cost means weighs you know but i use cost means weighs you know but i use cost cost zero right and then for size inbox okay and then we and then for size inbox okay and then we have a have a index it's going to be a bisect index it's going to be a bisect right right bisect right we search the right right bisect right we search the packages packages and then we we do the current size okay so so now we have two indexes right so we can have like the total uh the total size so the total size the the current box can handle is what is a pre-sum of index minus the pre-sum of pre index okay so here you know so that's why i use zero here because you know with the you know since we we have this kind of you know since we we have this kind of uh uh p a c k p a c k h p a c k p a c k h a so whenever we prefix this zero at the so whenever we prefix this zero at the beginning so beginning so when we are trying to get the uh when we are trying to get the uh the prefix sum right so let's say we the prefix sum right so let's say we want to we want to get the prefix sum of want to we want to get the prefix sum of this part so how do we calculate that this part so how do we calculate that we're going to use the we're going to use the index of here of this one index of here of this one minus the index of this one minus the index of this one right that's how that's why we need to right that's how that's why we need to move the index forward by one move the index forward by one right and this this kind of uh right and this this kind of uh bisect right this one is bisect right this one is exactly the index we're looking for right because if this one is like two three and three right and if our if our the the box size is three that's that it means that you know we'll get index of this one because we use a bisect right right that's exactly the index index we're looking for here okay and the pre-index is exactly the one of the previous one which is this one right and for in terms of the prefix zero here you know it means that you know at the beginning right the beginning let's say if we have like proof this is of the part this is a this is the first the first index right so we have index right here okay that's index and the prefix is zero because in this case we need the because in this case we need the the prefix of this one the prefix of this one right which is the uh yeah which is the right which is the uh yeah which is the uh uh which is empty which is zero right which is empty which is zero right that's why you know uh we you will use that's why you know uh we you will use the zero as a as the at the starting the zero as a as the at the starting point yeah actually i think one also works because this this is one right so prefix zero and prefix one there they're both one uh they're they're both zero uh okay cool so that's how we get the total size right that's the the total size of the of the packages the current box can handle right and then and then the cost the cost will be what the cost will be total package total count total package total count so the total count is what is simply the so the total count is what is simply the index minus the pre-index index minus the pre-index right so that's the uh that's the total right so that's the uh that's the total packages packages count that the current box can handle count that the current box can handle and then the cost will be what will be and then the cost will be what will be this kind of uh this kind of uh the size right times the count right so the size right times the count right so that's the uh that's the uh the box the total space when we use the box the total space when we use and then subtract the total the total and then subtract the total the total package size package size and that's that's the cost right and that's that's the cost right and then we have a we have we can do an and then we have a we have we can do an early break basically if the index early break basically if the index is equal to n it means that okay we is equal to n it means that okay we have already covered all the packages have already covered all the packages we can simply break right and then don't we can simply break right and then don't forget to update the pre-index with the forget to update the pre-index with the current index current index okay right and then here we do our okay right and then here we do our answer going to be a minimum answer going to be a minimum of answer.cost right that's it right so in the end we do answer do a modular okay do we have our modular here no we mod it's going to be the 10 to the power mod it's going to be the 10 to the power of nine plus seven of nine plus seven okay so here we have a mod okay so here we have a mod if the answer smaller than system if the answer smaller than system max size right house minus one yeah i think that's it so if i run the okay all right so at least it passed okay all right so at least it passed right right um so one thing to be careful is that um so one thing to be careful is that you know you know uh i mean during in during the contest i uh i mean during in during the contest i was was i was doing something like this so uh i i was doing something like this so uh i was doing like this i think yeah then we'll get the the wrong answer i i believe okay so i have to do the modular in the okay so i have to do the modular in the end i think end i think yeah i think that's for some reason i yeah i think that's for some reason i think that's the uh think that's the uh that's the the modular thing right so basically we have to do the modulars in the end so so that is when the module will not affect the uh and will not affect the the logic to get the minimum um so yeah and for the time complexity um so yeah and for the time complexity right so this one uh actually we already right so this one uh actually we already have like unlock in here right have like unlock in here right to store the packages and here to store the packages and here for the boxes okay for the boxes okay so for the boxes you know we the since so for the boxes you know we the since the total the total the total size of the box size is 10 to the total size of the box size is 10 to the power of five that that's why you the power of five that that's why you know know this two four loop here this two two this two four loop here this two two four loop here four loop here will be uh will be a in total right will be uh will be a in total right where n is the where n is the 10 to the power of five and for each of 10 to the power of five and for each of the the inside the photo here we have a binary inside the photo here we have a binary binary search which is unlocked binary search which is unlocked right that's why the total time right that's why the total time complexity for this one is complexity for this one is also unlocked that's why this one can also unlocked that's why this one can pass and yep i think that's it right at least that's what i did right during the contest so basically a sort plus a binary binary search and a sort plus a binary binary search and so we sorted by package at the beginning so we sorted by package at the beginning and for each box we'll also sort from and for each box we'll also sort from smallest to the biggest smallest to the biggest right and then for each of those the right and then for each of those the boxes we do a bisect write binary search boxes we do a bisect write binary search right right and then we maintain like the previous and then we maintain like the previous index and also index and also use this prefix sum to help us quickly use this prefix sum to help us quickly get get the total package size and then the the the total package size and then the the count count right and then we calculate the cost and right and then we calculate the cost and then then there you go uh there you go uh yeah i think that's it for this problem yeah i think that's it for this problem and thank you for watching this video and thank you for watching this video guys and stay tuned guys and stay tuned see you guys soon bye | 2024-03-25 12:01:34 | 1,889 | LeetCode 1889. Minimum Space Wasted From Packaging |
|
mh0XMn-UdK0 | I am Ashok Hello friends blind 725 new day and today problem number five is born day and today problem number five is born in Shagun's words for adultery easy problem the in Shagun's words for adultery easy problem the previous one BCE and this is so small that previous one BCE and this is so small that means we have been a lot of workers too so this is for means we have been a lot of workers too so this is for and this phone is that route of ours. and this phone is that route of ours. and this phone is that route of ours. remain the same, just add other things, then those notes on the left will be controlled on the right, so remember that two was here, so it has gone here, you have to make it 90, basically you will switch it off and the children below one two. Child 143 341 To subscribe, the first thing we do is now school, not war, then we have to return that we will start the net, like I told you, what do we do to get it, Then there is the one Then there is the one Then there is the one in which I am cleaning the left and right, in which I am cleaning the left and right, so I will tighten the route, so I will tighten the route, okay, and of course, dot right, okay, and of course, dot right, our tempo will go, the thing is clear, now our tempo will go, the thing is clear, now we just have to call this function, inverter, we just have to call this function, inverter, Dot Something Something Let me copy this Dot Something Something Let me copy this that Electrolyte will run both, then in India then this also has to be taken care of, just working on the Electrolyte note will not help, you will have to pay attention to both, okay now that we have started this, I have seen that I will do the final vitamin, let's I have seen that I will do the final vitamin, let's check the route, I have a safe tour, let's submit. In 2020, I had earlier said that it is okay, so I will not miss the class today, the code was there, we will talk about the rest later and It is good that Sehwag is following the test, It is good that Sehwag is following the test, It is good that Sehwag is following the test, see you see you in the next video. | 2024-03-22 11:02:31 | 226 | Leetcode 226. Invert Binary Tree. Python (Very Easy) |
|
1IDNM-zBXH0 | hey hey everybody this is larry this is the 10th day of the june niko the 10th day of the june niko daily challenge hit the like button hit daily challenge hit the like button hit the subscribe button join me on discord the subscribe button join me on discord let me know what you think about today's let me know what you think about today's problem uh i problem uh i my ac is still booking it in case you're my ac is still booking it in case you're curious and wondering curious and wondering uh but i did figure i put on the t-shirt uh but i did figure i put on the t-shirt you know it's still you know it's still uh well okay it's only 77 degrees uh well okay it's only 77 degrees outside today but it's still pretty outside today but it's still pretty uh warm inside uh uh warm inside uh anyway okay so i usually start this live anyway okay so i usually start this live um so if it's a little bit slow fast um so if it's a little bit slow fast forward or watch another video or forward or watch another video or whatever you need to do whatever you need to do uh i believe in you okay today's problem uh i believe in you okay today's problem is my calendar one is my calendar one um i feel like this is like one of those um i feel like this is like one of those movies that movies that they're already ambitious and they they they're already ambitious and they they um um you know you don't even know if it's you know you don't even know if it's going to be a good problem but they going to be a good problem but they already already have like three sequels coming what are have like three sequels coming what are you doing just like you know make sure you doing just like you know make sure it's good first it's good first anyway uh implement a my calendar class anyway uh implement a my calendar class to store your friends and your new to store your friends and your new friends friends and can be additive added event can i and can be additive added event can i cause a book double booking okay so you cause a book double booking okay so you have an open interval have an open interval uh so it's a real number is it real uh so it's a real number is it real it seems like these are all ins unless it seems like these are all ins unless i'm like confused i'm like confused about it okay so double booking happens when they have not empty intersection um so effectively this is inclusive but n minus one so that's a little bit awkward i don't know maybe it's fine anyway for each chord to return true if the fan can be added otherwise return first and do not return okay so this is this seems pretty straightforward basically you have um um a list of events and then you're trying to what it is that you find in it right uh what it is that you find in it right uh and actually just and actually just i know that there are a couple of i know that there are a couple of solutions for this for sure uh solutions for this for sure uh okay well the okay well the the really basic one is noting that uh the really basic one is noting that uh the number book the test cases is a the number book the test cases is a thousand thousand and to be honest if this was a a contest and to be honest if this was a a contest or something and this or something and this is like a um you know a second problem is like a um you know a second problem or easy problem relatively or like the or easy problem relatively or like the second media second media second problem like a quantum medium but second problem like a quantum medium but relatively easy problem relatively easy problem uh i'll i look at the n and i just do uh i'll i look at the n and i just do some n square and algorithm some n square and algorithm where we just loop for everything twice where we just loop for everything twice right right that's why we we insert and we loop for that's why we we insert and we loop for everything once and that's fine everything once and that's fine uh that's pretty straightforward and you uh that's pretty straightforward and you can do that in like can do that in like a minute um like just typing it out a minute um like just typing it out uh there are a couple of other solutions uh there are a couple of other solutions some requires uh some requires uh you know the one that i probably like is you know the one that i probably like is one that we um is is it one that we um is is it now it's it's a scan line or sword line now it's it's a scan line or sword line uh uh yeah scanline algorithm-ish but there is yeah scanline algorithm-ish but there is an the one that an the one that um or prefix sum if you want to call it um or prefix sum if you want to call it that uh there's one about prefix sum that uh there's one about prefix sum as well which is dynamic programming but as well which is dynamic programming but the key thing to noting the key thing to noting is that uh so how do you do prefix sum is that uh so how do you do prefix sum well well you add one under the start range and you add one under the start range and then you then you do a subtract one and end range and then do a subtract one and end range and then now now now that you have this prefix sum you now that you have this prefix sum you just have to query everything in between just have to query everything in between and of course the naive implementation and of course the naive implementation of a prefix number is not going to cut of a prefix number is not going to cut it it but if you're being really slick but if you're being really slick and you do a binary index tree or a and you do a binary index tree or a segment tree segment tree then you know then that's how you would then you know then that's how you would um do it in n log n time or um do it in n log n time or well it's not n log n times n log well it's not n log n times n log um the dom n log u time where u is um the dom n log u time where u is 10 to the ninth is that true uh well i 10 to the ninth is that true uh well i guess if you do it with guess if you do it with uh binary index tree that's true but you uh binary index tree that's true but you could probably do it with segment tree could probably do it with segment tree or something like that or something like that um yeah um yeah so so there's some ways of doing it so so there's some ways of doing it there's also there's also um just binary search uh you just put um just binary search uh you just put everything in um yeah same idea with prefix sum is that you you know you just put i mean same edge they're all kind of related in a way because you're representing the same underlying data but you can just do a binary search you know the thing to note there is that you know the thing to note there is that there really only there really only a couple of possibilities for for a couple of possibilities for for sigmund sigmund um uh yeah i mean i think the tricky one is yeah i mean there are a couple of things you can have to make sure your binary searching on but i think that should be okay or at least a binary index tree oh yeah actually no i mean you could oh yeah actually no i mean you could just i was gonna do something even just i was gonna do something even really fancy but you can really fancy but you can actually just um actually just um just do a two binary search right one on just do a two binary search right one on the end start start point and one on the the end start start point and one on the end point end point and if there's any number in between or and if there's any number in between or any um any um endpoints in between then then um so they're only a couple of scenarios right there either there's another endpoint in between your two numbers or your current um segment is uh entirely overlapped by or dominated by another event which means that when you do a binary search just look at two adjacent numbers and so forth um so yeah so there are a lot of possibilities to play around this because this is uh uh that kind of problem with there's just a lot of possibilities so i gave you like five of them maybe i don't know i didn't count but try to up solve it if you can and play around with it uh maybe not the end square one because i mean okay you can spend a minute to play around with i'm just gonna do the binary search one i and then maybe we'll go over other people's solutions afterwards because i think there are definitely a lot of solutions here so how do i want to do it okay so let's so how do i want to do it okay so let's just just keep a assorted list i'm a big fan of sorted lists but uh but i'm a big fan of sorted lists but uh but you know you know make sure you know other ways of make sure you know other ways of implementing around it implementing around it otherwise you know you only want to be otherwise you know you only want to be in an interview where they're like in an interview where they're like nope you cannot use it right uh actually nope you cannot use it right uh actually i'm having a little bit allergy thing i'm having a little bit allergy thing everything's so itchy i don't know if i everything's so itchy i don't know if i ate something ate something or just trees in general i'm allergic to or just trees in general i'm allergic to a lot of things who knows how these a lot of things who knows how these things work things work technology is weird uh i don't know if technology is weird uh i don't know if you know this but in new york you know this but in new york um there's a new york times article at um there's a new york times article at some point recently or maybe not that some point recently or maybe not that recently a couple of years ago recently a couple of years ago where they mentioned that they changed where they mentioned that they changed all the sex of the trees to be all the sex of the trees to be um i think they changed it all to male i could be wrong on that one but anyway they changed it to one of the sex so um so so that because it's less messy i forget which one it is um i think it's the male it's a less messy one where um it's less smelly um but but there's a lot more pollen uh so that's why like everyone's just getting hit hard uh the last decade or so because when i was growing up i was pretty fine there's no uh no issue here but but it is what it is so yeah so let's do two binary searches on i have to remember i have to think about i have to remember i have to think about this a little bit with respect to this a little bit with respect to whether this should be inclusive or whether this should be inclusive or exclu or sorry left bisect left or exclu or sorry left bisect left or bisect bisect right um i'm gonna make everything right um i'm gonna make everything inclusive anyway because this is just i inclusive anyway because this is just i don't like so then then don't like so then then um you can be a little bit sloppier uh i um you can be a little bit sloppier uh i think maybe think maybe uh let's do start indexes here and uh let's do start indexes here and indexes you go self-doubt indexes you go self-doubt bisect left of bisect left of uh n if start index is equal to an index um that means that okay so now we okay so if they're not in the same index then we return false because that means that literally there's an endpoint in between right so you don't want to add it um because if there's an endpoint in between them you know if you have this point there's an end point here that means that by you know either it overlaps in some way right you could visualize it in your head uh whatever but okay and so now if they are the same then that means that the other possibility is that you're in between two endpoints i think i have to keep track of i think i have to keep track of because there are two in other scenarios because there are two in other scenarios right where like right where like the i think i got it but but it's just i think i got it but but it's just running through the scenarios in my head running through the scenarios in my head um definitely try a little bit at home um definitely try a little bit at home i was going to think about caring about i was going to think about caring about um um each particular segment uh and whether each particular segment uh and whether that matters but actually i think it that matters but actually i think it doesn't it just matters whether doesn't it just matters whether you're looking at the right end point or you're looking at the right end point or the left endpoint or or the start the left endpoint or or the start endpoint and endpoint and end point of the previous um the end point of the previous um the previous previous segment because for example if you have segment because for example if you have a segment like a segment like you know that's for the purpose of um you know that's for the purpose of um you know you know if you have two indexes that are if you have two indexes that are here and then you have one that is to here and then you have one that is to the right the right or the one that appears afterwards if or the one that appears afterwards if the starting point is the starting point is to the left um yeah because the by some pigeonhole of force e kind of way if the next if the index are the same then then okay so you look at two things right one is that the index if it is the right index then it's just to the right oh is that true i mean that part is true oh no because okay because i was going to say that there could be other overlaps but in this case there the reason why this could work is that there is an invariant in which nothing overlaps because if they're overlapping then you have to check all these other segments but here the closest segment because they're not overlapping if it faces the other way yeah another way of thinking about it okay let me actually i know that i talked a lot so and it's very confusing the way that i'm talking about it so i'm gonna just pull up paint real quick uh what i'm saying is that okay so let's say you know we basically have a number line uh we have points um let's say our our search is here and then now we we have to look at the two adjacent indexes right so so i i i describe these two um the two adjacent endpoints as either a start endpoint or an n endpoint but you can actually face look at it the other way if it's an end point that means that here this faces that way uh or this one faces that way depending on which one and then if it's a start endpoint then it faces that way right and because there are no overlaps if if this index is facing this way uh if changing colors hang on if we're doing this way that means that this lines end point it's going to be going the other way somewhere but it passes our point because that's the definition of in between right um and then in the same way if if we are here and it's facing left meaning it's in uh in an end end point and it goes you know here and it you know intersects with some other endpoint but i guess it has to be this one actually because as we said there's no overlaps so okay so actually in that case because there's a lot of things that's uh in a way forced because there are no overlaps and because of that and variant actually i was wrong about this this this drawing as well just actually have to stop here right because there's no overlaps so that means that we just have to check with these things and that also means that we only have to check for one end point which is that your index is facing right which it your index is facing right which it means that it's a start endpoint means that it's a start endpoint okay so that's the only thing that we okay so that's the only thing that we have to do so um so yeah so now of course we don't really do any so now that just means that we have to track one thing more um let's also double check real quick that this is in it because if because there is a case where oops link with this then so this is in between and that's good otherwise if it's either all the way to the beginning or all the way into the end then this is true so let's actually return true in the other case but here let's say it's in between so now we have to check the indexes so we do something start index um so let's just have two two things right one is the x which we don't care about because we we know that it's smaller and then let's just say we have a tag on whether this is the start endpoint so uh it starts saying let's go here wait oh yeah return true uh we actually wait oh yeah return true uh we actually didn't didn't do this problem quite right of course um do this problem quite right of course um or by we i mean me or by we i mean me because we have to insert stuff in this because we have to insert stuff in this the list which we the list which we have not done so um okay so actually let's actually change this to if it's not start then we turn force otherwise we just do add here and the way that i restructure this code so that i don't have to write the same thing twice though depending on what you're doing it may be a little bit tricky so yeah so now you you just insert the start which is an insert true and then also and also true oh sorry n and then force and of course we change these to be inclusive don't so hopefully this should be good uh let's give it a spin only one test cases so i hope this is right uh tuple and int oh yeah [Music] okay i think i want to top up one okay i think i want to top up one element element and i guess we can put a dummy element and i guess we can put a dummy element as a second element but i think this as a second element but i think this should be okay should be okay nope into object is not there well do i insert weird things okay fine let's just do i don't i don't know if this would be sorted the right way that's why i'm a little bit worried about doing this um i thought that you could do it with tuples of different lengths but maybe i'm wrong maybe this is what i need this is what i need okay there we go uh syntax is very awkward apologize for that um the reason is because uh we have a second thing that we don't want to search by and we want to get the first element no matter what anyway and i forget whether i mean i think intuitively it would uh put force before true but i didn't want to test that and also it's a little bit awkward so yeah so this looks okay i'm not confident about it because this test case is kind of crummy uh but i am lazy so i am lazier than i am not i am lazier than i am unhappy so let's give it a submit and see how it goes because after all it is 3 28 a.m uh here in new york uh unfortunately we do have a wrong answer and it's a big case 72 hour 148 it's a big case 72 hour 148 uh unfortunate though still but uh unfortunate though still but let's see so that i could click on div let's see so that i could click on div so i returned probably later on as well so i returned probably later on as well um because these things tend to cascade um because these things tend to cascade or maybe apparently not or maybe apparently not but okay so one two three but okay so one two three zero and seven overlaps but i returned zero and seven overlaps but i returned true why do i return true oh [Music] [Music] and i know what i i think i know why and i know what i i think i know why this is to this is to get yeah okay i see why because i because um now we search for sixes and inclusive it finds a six um so any overlaps is not good but i did not check for that case i was a little bit sloppy on this one uh okay and six is of course the end now this is and six is of course the end now this is a start point a start point huh that is awkward though wouldn't that because it is the start point i do search for sex and it finds huh i mean there are huh i mean there are a couple of things to fix that i'm just a couple of things to fix that i'm just trying to think through it a little bit trying to think through it a little bit um so this returns the same index oh because they return the same and no no um so it returns the same index so it goes here and then the start index should be zero so it goes here all right let's just um let's do some minor debugging um and i sometimes even when i get something right i will debug it because i'm not confident about it but oops okay okay so 23 and 31 okay 42 and 50. that's gucci 23 and 31 okay 42 and 50. that's gucci six and fourteen six and fourteen [Music] [Music] uh okay so that that's good uh okay so that that's good uh this is also true that's basically uh this is also true that's basically what i said right what i said right why is the is start not right why is the is start not right [Music] [Music] so this is six and true so if this so this is six and true so if this is oh maybe i just confused my logic a little bit if it is the start then it will return force no wait yeah if it is to start yeah wow whoops i think i said the right yeah wow whoops i think i said the right things but i confused myself at some things but i confused myself at some point point yeah okay i think my logic is just wrong in general to be honest um i think i messed something up here i think that's why i was very confused and i just got like i said um that's why i got lucky on the first one having that test case but um i definitely should have checked a little bit more okay let me step back a second uh because i get confused easily clearly so okay let me do a bisect left the number that you get is actually not the number on the left is the number on the right so i messed up that one um i think that's where um i confused myself so we look at the number to the right and if the number to the right is to start then that means that this is good true but then true but then that's how we okay so i actually i think that's how we okay so i actually i think i did this by accident i did this by accident i made two so the funny thing is that i made two so the funny thing is that yeah i made two bugs yeah i made two bugs that counteracted each other um that counteracted each other um but then now we're checking the one but then now we're checking the one that's to the so now this is the start if this is a starting endpoint i'm just trying to think whether it is i'm just trying to think whether it is good enough that we do a bicep good enough that we do a bicep right i think it is actually because then now but i could be wrong i think i'm off by one on that one oh no i stepped the wrong same wrong answer okay let's just so it gives us the okay let's just so it gives us the number that is so okay so bisect let me step back for a second uh okay so the bisect left will get us the number that is bigger than this one or equal to this one if it is equal to this number but whether it is start or not did we miss a case i mean how did i miss this case i'm trying to think okay and i think we're just i'm just not handling off by once very well that's the short okay i think we can just check it okay i think we can just check it another case another case i thought i didn't need this but maybe i thought i didn't need this but maybe we have some off by one issues that uh okay so now it looks good um though obviously given what we experienced i'm not as confident again but i am still lazy though so i am again but i am still lazy though so i am going to submit going to submit uh get the wrong answer here okay so uh get the wrong answer here okay so let's take a look again at this one let's take a look again at this one so this one i have 99 100 45 57 so this one i have 99 100 45 57 [Applause] why would this return force so okay so we're looking at the right because by different i think i'm just because by different i think i'm just confusing myself with the direction confusing myself with the direction i visualization's hard sometimes late at i visualization's hard sometimes late at night night okay so when we do a binary search okay so when we do a binary search we get the thing that's on it we get the thing that's on it okay that return force okay that return force so or bigger so or bigger um so assuming these two indexes are the um so assuming these two indexes are the same same then yeah i think this needs to be then yeah i think this needs to be eyesight right i think this is a little eyesight right i think this is a little bit awkward otherwise bit awkward otherwise but then this would never be true so i don't know i think i'm just being a little bit awkward i think bicep right will get us to the next for example if it is six it gets us next one and then where to start then it next one and then where to start then it is good now i think i just need to check for more cases i think oh fine okay but this is just not even off by one so basically this is saying that this searches um this gives us zero zero because we're inserting the beginning uh this is gucci this is gucci um we looked at the first element that we're installing before um it's going to be the 47 the 47 and it is to start and because this is uh this should be good this should be uh this should be good this should be good right yeah i gotta point it again i i get so confused right now no i think i have two other test cases okay okay i think it's this one though right did i mess up why is 99 of oh it's 99 b did i mess up why is 99 of oh it's 99 b oh that's why because i've i did forget about this case so the case is that because we're now doing [Music] inclusive now this is a point it's going to give me that true end it's going to give me that true end force so maybe it just force so maybe it just by definition um gave me a by definition um gave me a force for this thought because it's force for this thought because it's taking taking like we said it sorts by force first like we said it sorts by force first uh okay how do i want to handle it well i guess of the g code and they'll never overlap with anything no that's not true because then the um 90 to 100 or something right so we um 90 to 100 or something right so we have to be able to support this case but have to be able to support this case but we just wanted to put we just wanted to put we want to sort this the other way i we want to sort this the other way i guess so guess so i am very yucky today my apologies so i i am very yucky today my apologies so i guess we just need to do guess we just need to do sn instead so that it sorts the other sn instead so that it sorts the other way way um maybe someone like that uh evolution of bad code i suppose and i thought this was supposed to be pretty straightforward but you see me struggling this a little bit uh okay is this good again okay this is good again um let's give it a spin okay welp ah you've been hit with me half an hour uh give yourself some props for having a good attention span or maybe just skip to the end i don't know either way give yourself props uh thanks for the support i i appreciate it um but yeah so what is the complexity of this um it's gonna be n log n where n is a thousand uh maybe if i just did the two for loops it'd be less embarrassing because we do a by we do a couple of binary search but constant number of binary searches each and each of them is going to be log n so this is going to end uh oops and also these two operations for um it's not binary search but it binary in section insertion something like that uh but yeah so n log n is the total complexity and that's all i have um let me know what you think about this problem i think my visualization made sense my implementation is kind of terrible though and i had some weirdness weird edge case that i did not anticipate uh enough with respect to you know the one point case i guess with the inclusive inclusivity but uh but yeah well i hope hope this was uh educational for you uh let's actually take a look at the solutions before i go uh but i still hope it was educational for you though um let's see what other such i mean i think i mentioned a few so uh yeah i mean we knew about before so that's fine uh band's tree that's kind of what we yeah uh okay yeah yeah uh okay yeah so we can we basically did that and so we can we basically did that and that's the two ideas that they have that's the two ideas that they have um oh well i think i could have done i think i i think i could have done i think i tried a little bit too hard looking back tried a little bit too hard looking back though in that i try to make this like though in that i try to make this like prefix something that which prefix something that which i generally like uh thinking about i generally like uh thinking about things in a prefix some kind of way things in a prefix some kind of way because because it comes in a lot more handy in it comes in a lot more handy in different places um different places um but i think what uh we looked at very but i think what uh we looked at very briefly briefly and the binary search tree solution is and the binary search tree solution is that if i just put the actual segment in that if i just put the actual segment in the binary search tree then i could have the binary search tree then i could have just just binary search for the next one and then binary search for the next one and then just see if it overlaps and then just see if it overlaps and then look at the previous element or look at the previous element or something like that see if that overlaps something like that see if that overlaps um and that would have saved me a lot um and that would have saved me a lot more time but uh and more time but uh and because because when you're doing because because when you're doing interviews and um interviews and um and competitive especially uh you want and competitive especially uh you want to keep it as stupid as possible to keep it as stupid as possible as simple as possible because that means as simple as possible because that means that you're not doing anything fancy that you're not doing anything fancy uh and it'll get you way far once it uh and it'll get you way far once it gets hard it gets hard but gets hard it gets hard but but for the simple ones keep it as but for the simple ones keep it as simple and stupid as possible simple and stupid as possible because when you try to do things that because when you try to do things that are an overkill uh you are an overkill uh you you know people are not that impressed you know people are not that impressed people just get uh people just get uh i mean people may be impressed if you i mean people may be impressed if you get it right very quickly but if you get it right very quickly but if you mess up then you'll be like uh what's mess up then you'll be like uh what's what is this what is this person doing anyway person doing anyway i hope you all have a good thursday and i hope you all have a good thursday and the rest of the the rest of the week i'll see y'all later see you week i'll see y'all later see you tomorrow hopefully tomorrow hopefully uh and happy lead coding happy solving uh and happy lead coding happy solving and and ticker mental health bye bye | 2024-03-21 11:39:40 | 729 | 729. My Calendar I - Day 10/30 Leetcode June Challenge |
|
NqRXfJQ5jMY | hey guys let's understand the problem 1609 even odd trees okay it's bit a 1609 even odd trees okay it's bit a unique question uh this question let's unique question uh this question let's read the question given a binary tree read the question given a binary tree name even and odd if it meet the name even and odd if it meet the following conditions means uh we have to following conditions means uh we have to say if the tree is even or or tree it say if the tree is even or or tree it will be only by these following will be only by these following conditions so let's understand the root conditions so let's understand the root of the binary tree is at level zero of the binary tree is at level zero means the root should always be at zero means the root should always be at zero index okay index okay so let it floats so yeah uh the thing is so let it floats so yeah uh the thing is suppose I have a which would be the two suppose I have a which would be the two then it level should always be zero okay then it level should always be zero okay this is the first condition now it this is the first condition now it children are the at the level index one children are the at the level index one means if I have a a then it's um means if I have a a then it's um children should always be at level two children should always be at level two level one level one sorry okay so the level should keep on sorry okay so the level should keep on increasing and as we go deeper and deep increasing and as we go deeper and deep and same as would and same as would be oh that for every even index levels be oh that for every even index levels suppose this I have a d here and it's a suppose this I have a d here and it's a even L even level then uh all noes of even L even level then uh all noes of the level have all integers value in a the level have all integers value in a strictly increasing order means uh strictly increasing order means uh suppose I have a value suppose I have suppose I have a value suppose I have two notes and these are the childrens two notes and these are the childrens okay and these are childrens of this okay and these are childrens of this note and these are children of note and these are children of these and it's on level two okay so the these and it's on level two okay so the thing is this the value of this index should be very should be the smallest and this will keep on increasing okay this will keep on increasing and have odd integers and all these are OD integers 2 = to 1 okay this would be the condition for even and the same opposite for the or indexes okay so what can we do is uh you can you can just say that we are going for each level then going from left to right okay so what is the level it is simple BFS okay so we have to use a simple BFS in this um to just solve this question so let me just code for you okay so I need a CU first of all so let's make it a Cu uh in which I have start start okay okay so Q would be R okay now I need a so Q would be R okay now I need a level level should be starting to zero level level should be starting to zero okay now what I need okay now what I need is uh a flag you know a flag that will is uh a flag you know a flag that will tell me U that the value that I have to tell me U that the value that I have to check is keep on increasing or should it check is keep on increasing or should it be keep on decreasing okay if I have a be keep on decreasing okay if I have a flag with one then I have to keep on flag with one then I have to keep on checking for the increasing order and if checking for the increasing order and if I have a zero it means I have to keep on I have a zero it means I have to keep on checking for the decreasing order okay checking for the decreasing order okay so I need a flag which will be in the so I need a flag which will be in the starting would be starting would be one one means increasing and zero means one one means increasing and zero means decreasing okay let's decreasing okay let's U why Q uh n would be the length of Q and while n and we have to minus n also and if every iation I have to Simply switch the flag means uh flag Z flag to one Z means at every level I have to suppose in this I have one then I have to make it zero then I have to make it one and suppose I have to make it zero these are the flags and these are the levels as I keep on going in in the level then I have to change the flag also okay it will tell me the increasing or decreasing increasing or decreasing also okay these are the conditions and also okay these are the conditions and now let's go for the conditions okay now let's go for the conditions okay okay let me P the L from the que of top top bottom node okay or the first node then I have to check for few um suppose I have few values okay and I um suppose I have few values okay and I have to check for if these are in have to check for if these are in increasing or decreasing with only one increasing or decreasing with only one iation so what I will do is I will take iation so what I will do is I will take a a pre which in the starting would be minus pre which in the starting would be minus one okay now if I'm standing here I'll one okay now if I'm standing here I'll check is my pre minus one if yes then I check is my pre minus one if yes then I have to Simply make it the same as a have to Simply make it the same as a value then I will check for this is my value then I will check for this is my threee is less than or equal greater threee is less than or equal greater than according to the increasing or than according to the increasing or decreasing okay if my flag is one decreasing okay if my flag is one suppose my flag is one then I have to suppose my flag is one then I have to check is my pre previous node is less check is my pre previous node is less than the current node okay if it yes than the current node okay if it yes then it is a true okay for this if it's then it is a true okay for this if it's true then I have to make a reverse true then I have to make a reverse condition okay to make it false sp Let condition okay to make it false sp Let me let me just go for you uh I need a me let me just go for you uh I need a pre first of all um if um f 3 = to minus one then what I have to do just simply uh change the value of previous value it would be no do okay else uh if soor I can do this else okay now the conditions if my flag equals to one and uh previous is less than node do well then it is a correct correct we are going in a correct direction but we have to check for the I'm checking for the false condition okay so I'm just making it false and make it false and say here Al flag equal to Z and p is less thanal to no do well and I have to return false okay you two condition that I have to check either it is uh keep on increasing or decreasing if I found something that is decreasing then I will return false and the flag one and if the flag is zero then I have to check for keep on decreasing values increas keep on okay what I do is um I just uh come make the previous note to the current note then I will check if I have check for even the odd indexes and the even indexes okay is the odd value or the if 11 mod 2 = to Z and if 11 mod 2 = to Z and node well to = to Z then return what right okay these are the conditions that I have to do and simply just if node do left then U left and what I have to do left and what I have to do is Dri right okay so this is the code and if it all satisfi then in the end I have to return okay will be not Z not Z like Z okay the thing is I'm Z okay the thing is I'm one submit this yeah it's been submitted and it will accept yeah it being accepted so yeah this is the main concept behind this I'm going for each level and from left to right I'm checking if it increases or decreasing according to the flag and the Lev okay this is the main concept | 2024-03-15 18:15:17 | 1,609 | 1609. Even Odd Tree | Medium | Leetcode 1609 |
|
FPgC3RfHMBI | That's all Hello everyone welcome back to my channel today were going to discuss the problem problem is channel today were going to discuss the problem problem is minimum cost to move chips minimum cost to move chips to same position its very easy problem butter to same position its very easy problem butter concept is very good so let's see what concept is very good so let's see what problems we have and ships where the problems we have and ships where the position of position of position of LIGHT VINNY TUNG ALL THE TIPS TO THE SAME POSITION IN ONE STEP WE CAN CHANGE THE POSITION OF COMMISSIONER CHIP FROM POSITION I2 POSITION OF TO OR POSITION OF - 263 AND SUBSCRIBE TO 2051 AND SUBSCRIBE ONE 2051 AND SUBSCRIBE ONE 2051 AND SUBSCRIBE ONE Understand Problem That Lipstick 10,000 From Position Reduce Position Suddhowala Position It Is The Volume Two Two Two Three D Joe Position Digestive One Two Three Position Restorative Chips Chips Thoughts 821 Kum Kum TOO TOO TOO TOO TOO'S NEW TOXINS A TASK TU ALL THIS IS TOO NEW TOXINS A TASK TU ALL THIS IS TOO ONE POSITION IS PAIN E TO SHOOT LESS HAIR ONE POSITION IS PAIN E TO SHOOT LESS HAIR AND OTHER GOOD WORK TORCH AND OTHER GOOD WORK TORCH LIGHT TOO WE NEED TO TELL THEM MINIMUM LIGHT TOO WE NEED TO TELL THEM MINIMUM COST NOW HOW TO STITCH DEFINE THE EFFIGIE AF COST NOW HOW TO STITCH DEFINE THE EFFIGIE AF IS THE CURRENT POSITION IS THE CURRENT POSITION Fiber Glue Two and Three Two Like Ki and Figure Add One and 20 Plate Improve One Ki and Figure Add One and 20 Plate Improve One Step Ahead or Step Ahead or Wave Step Back and Will Give Equal to Wave Step Back and Will Give Equal to aLove aLove Letter I Will Know Problem Solve What We Will Do It Letter I Will Know Problem Solve What We Will Do It Will Be Moving Bto Tips Hair Will Be Moving Bto Tips Hair Hai Tu Yaar Movie Dhoom One Step What Means The Hai Tu Yaar Movie Dhoom One Step What Means The Current Position Current Position Video 5 - 105 -1.3 Lee - World Bittu Video 5 - 105 -1.3 Lee - World Bittu Sudheesh Two Tips Will Go Near To Avoid To Sudheesh Two Tips Will Go Near To Avoid To Switch 142 Chipset 52122 So This Scene From Switch 142 Chipset 52122 So This Scene From Distant K Out This Is Stupid So They Can Also Be Is Stupid So They Can Also Be Is Stupid So They Can Also Be Chips To Parishad Teen To Worry About Your Beloved And * * Will And In The State Will Go To Three Liberties Pet Will Question Is Great And 222 Returns Minimum Cost Minimum Cost Subhash Viewers Shifting Btu Kuber Hai Input Input Input Output Don't Worry For Not Getting Approach You Output Don't Worry For Not Getting Approach You All The Best And Wants A All The Best And Wants A And Width Very Illegal Approach Gather And Width Very Illegal Approach Gather Possible To This Topic See So Let's Possible To This Topic See So Let's Celebrate Hadith Hai Celebrate Hadith Hai Lahariya Retired This Point Hai To Ephesians Fiber That CRPF And To Improve 520 Upright With Cost 0 Ki and Effigy Behen Fifth Class One Behen Fifth Class One So So No Need to Know Which Position Will Be Keeping Up with the Position From Position Lake to Position Final Position Want the Final Position Hai Torch Want the Final Position Hai Torch Want the Final Position Hai Torch final position dubai dat ki which means all also elected tis e to m 3 ki indicators 22182 question effects over your this teachers and over into tears effect diet want to be i want the final position will government even into water drips subscribe Video झाल झाल feature hai hai tu from this what we get from get final position final position 2110 2110 is P55 is even is P55 is even no problem no problem no cost cost no problem no problem no cost cost ka abhi aas final try And this oil do I will dare I will have to go to the ship which will go to the final finally Bigg Boss main to Bengaluru final position only one and went UPTO 5000 court violin opinion * * Arvind Singh and similar in Delhi but its final position final position final position liner 6 days 259 56001 between 1000 ads hello friends smart together brave what is the final position has given a hai idhar pfi is jeevan mein a low cost a letter and its pure form in opposition has given only but your fit third You Will Have To Switch On The You Will Have To Switch On The You Will Have To Switch On The Right Development We Are Right Development We Are Going To End The Last Article Going To End The Last Article Supportive 12328 18182 One Day One Day 116 Chi Method Cash Deposit On It Final 116 Chi Method Cash Deposit On It Final Position Easy Position Easy 157 Definitely A Point And You Will Not 157 Definitely A Point And You Will Not Possible To Possible To Torch Light Poking Iodine For Electrical Torch Light Poking Iodine For Electrical Yadav And Final Position In The 5th Yadav And Final Position In The 5th That Daily Use Hee In Award Shows Means Less Than What That Daily Use Hee In Award Shows Means Less Than What You Rent From You Rent From Three To From Which You Want To Reach From Three To From Which You Want To Reach From C-25 Gillard To In Delhi Which Means When C-25 Gillard To In Delhi Which Means When You Reach You Reach You Reach so otherwise speed 512 ki lete oct sudhir voting tour from if you want to listen to panch this lad for * * * * * * no cost because you are doing to medium to low Photo Photo Photo 50 28182 50 28182 That Badwani Was Cost 155 And Cosmetic That Badwani Was Cost 155 And Cosmetic Act Act Is To Ayurveda Want From You Got Is To Ayurveda Want From You Got Introduced Introduced In More Trends Which Will Get Is That Is Pay's Exit Poll Defense Life Secure Final Exit Poll Defense Life Secure Final Position Thinking Is 115 The Position Thinking Is 115 The Appear For Even No Cost Appear For Even No Cost Final Position In China Final Position In China hua tha but profile award dene wa hua tha but profile award dene wa hotspot on this hotspot on this point se 1 inches resignation final point se 1 inches resignation final position is not a loot any of your choice position is not a loot any of your choice award main tere award main tere bina cost but if you find bina cost but if you find even be equal to even be equal to ki tum logic airplane ho gayi hai se this is the ki tum logic airplane ho gayi hai se this is the mean mean mean Another Taste Take Off A Plate Yudhishthir Vacation Super Different Aspects Lipstick 462 318 The Elected As 462 Atin 462 Atin 15000 And Share 15000 And Share And Different Aspects Of The Great And Different Aspects Of The Great Warrior Behave Like Position 12345 Take And Warrior Behave Like Position 12345 Take And Drop Drop Tips This Seventh Tips This Seventh Tips This Seventh Posted on 20 Sep 6 2013 पुन की की Navneet To Calculate Which Will Be A What Is Navneet To Calculate Which Will Be A What Is Of In Opposition Should Be Worshiped Even Total Cost Also Number Of Lord Position Because All Total Cost Also Number Of Lord Position Because All Final Position Is Just Final Position Is Just Not Mean That Position On Even position tips Even position tips Even position tips I hope you are getting less is so simple it's very simple now just simple simple it's very simple now just simple things with me to just calculate how many even numbers things with me to just calculate how many even numbers in this we give them and na de to even in this we give them and na de to even numbers in this position are this 123 This position airways This position airways This position airways 1234 1234 soft effect 12424 12424 number two number two how to come to reddy bandhu good morning how to come to reddy bandhu good morning 12.21 tight it cost but as 12.21 tight it cost but as you fix position to final position 212 mode of the function finally only which will give function finally only which will give 21 hai to 21 hai to so nak isko so nak isko so nak isko suited depends upon how many even numbers where pencil we go in noida what ever The Amazing minimum number one dead to dooba dooba court to sharp answer for kids and beautiful to basically a affected approach the code very simple pleasures due to find how Many Even Numbers Aa Jaye Hamari Aur Damage Hai Jagdish What Means To Understand Things Which Is The Preparation To Exceed To Not That If U Ment For Tak Water Can You Understand It Developed Agendas And Visits To A Dysfunctional Give Worst Position Actress Give Winners Were Taken 2001 Hot and Where Going to Cheese Pages of Creating This Edifice Edit to three layer checking even if not effective work in preventing the invisible and if they cultivate thought for improvement in the heart and detergent show in this year show in this year ₹5 and spirits pimple time click ₹5 and spirits pimple time click tips very simple staff and don't thing that you will tips very simple staff and don't thing that you will show a flying jatt video please show a flying jatt video please like and share with your friends and like and share with your friends and electrical department of fuel is very electrical department of fuel is very interesting problem thank interesting problem thank you | 2024-03-18 11:53:07 | 1,217 | Minimum Cost to Move Chips to The Same Position | Leetcode 1217 | Array | Math |
|
GxTwKRlhBAI | hello hello hello hi guys good morning welcome back to a new video this maximum welcome back to a new video this maximum element after decreasing and rearranging element after decreasing and rearranging I hope that you guys are doing good I I hope that you guys are doing good I hope that Changi now let's go see the it hope that Changi now let's go see the it has been asked by Amazon not pretty much has been asked by Amazon not pretty much uh just in last one two years and not uh just in last one two years and not not not much frequently let's see uh not not much frequently let's see uh it's marked as medium but it's a pretty it's marked as medium but it's a pretty easy question uh that we given a easy question uh that we given a positive integer array called as ARR and positive integer array called as ARR and we have to perform the operations we have to perform the operations possibly none on are so like number of possibly none on are so like number of operations are not needed here you'll go operations are not needed here you'll go and see uh now what are the operations and see uh now what are the operations like the the thing which you have to like the the thing which you have to make sure after applying the operations make sure after applying the operations are the first element in the array must are the first element in the array must be one okay must be one that is one be one okay must be one that is one thing which you have to make sure right thing which you have to make sure right we'll make sure that and also the we'll make sure that and also the absolute difference between two adjacent absolute difference between two adjacent elements should be less than equal to 1 elements should be less than equal to 1 which means if I have two elements right which means if I have two elements right here so either they can be same or they here so either they can be same or they have a difference of one are in why not have a difference of one are in why not 2 one because like you saw that the 2 one because like you saw that the first element must be one so I'm just first element must be one so I'm just considering this is the first element considering this is the first element and then the next element I'm just and then the next element I'm just picking okay it can be a one or a two picking okay it can be a one or a two but Max to Max it can be a two now there but Max to Max it can be a two now there are two types of operations which we can are two types of operations which we can perform that first just decrease the perform that first just decrease the value of any element of ARR to any value of any element of ARR to any smaller value so I can just decrease the smaller value so I can just decrease the value that is one I can decrease the value that is one I can decrease the value and other is I can rearrange in value and other is I can rearrange in any order which means I can just do the any order which means I can just do the rearranging in any order I can just do rearranging in any order I can just do the shuffling now I have to return the shuffling now I have to return return the maximum possible value now if return the maximum possible value now if you just go and imagine the same thing you just go and imagine the same thing now this are the two things which we can now this are the two things which we can achieve starting because it is a achieve starting because it is a starting value so we know very well sure starting value so we know very well sure that we can achieve these two formats that we can achieve these two formats either same or more now if I want to either same or more now if I want to achieve the maximum possible value then achieve the maximum possible value then it is evident right that if I have four it is evident right that if I have four numbers so I will always try to place numbers so I will always try to place the maximum possible value one next the maximum possible value one next maximum possible values is two although maximum possible values is two although I can also place a one here but I'm I can also place a one here but I'm saying okay I'll just try I'm trying to saying okay I'll just try I'm trying to place the maximum possible value okay if place the maximum possible value okay if it is three now like I can place a three it is three now like I can place a three which is the next possible maximum value which is the next possible maximum value next I can place a four so you saw that next I can place a four so you saw that okay I'm just always trying to place a okay I'm just always trying to place a next possible maximum value which is next possible maximum value which is nothing but what the value I had nothing but what the value I had previously plus one but I okay so with previously plus one but I okay so with this concept your answer should have this concept your answer should have been and uh like whatsoever the side of been and uh like whatsoever the side of the array is that should be the answer the array is that should be the answer which is n so is that the answer I'll which is n so is that the answer I'll say no because here I just assume that say no because here I just assume that I'm putting a one and then I assume that I'm putting a one and then I assume that I'm putting a two I did not consider the I'm putting a two I did not consider the array itself I have my array as a array itself I have my array as a benchmark what if what if my array benchmark what if what if my array itself has an element like 1 1 uh 4 like itself has an element like 1 1 uh 4 like 1 1 8 and 9 so if my AR had an element 1 1 8 and 9 so if my AR had an element like 1 18 and N so no matter what I do I like 1 18 and N so no matter what I do I cannot make this one or two I cannot cannot make this one or two I cannot increase a value let's say it was the increase a value let's say it was the aray element I'm hoping my array should aray element I'm hoping my array should look something like this finally so as look something like this finally so as to obtain the maximum element is four to obtain the maximum element is four but for that for sure I need to increase but for that for sure I need to increase 1 to two that I cannot do so I have to 1 to two that I cannot do so I have to take minimum of what I have and I and take minimum of what I have and I and what I expect to be so for sure what what I expect to be so for sure what will happen is this will modify to one will happen is this will modify to one now if this modifies to one for sure the now if this modifies to one for sure the later part will also be modified right later part will also be modified right so the later part will actually become so the later part will actually become now okay what what's the previous value now okay what what's the previous value I can just increase that value to one I can just increase that value to one okay previous value was one add a one okay previous value was one add a one you can obtain a maximum value of two you can obtain a maximum value of two here now so how we got this we got this here now so how we got this we got this by just saying okay what's thee what's by just saying okay what's thee what's the previous value just just have that the previous value just just have that value which is pre like previously to us value which is pre like previously to us just have that value which is previously just have that value which is previously to us and then add a one to it and same to us and then add a one to it and same I just can say Okay previous value is I just can say Okay previous value is two I can add a one I can get a three so two I can add a one I can get a three so this is how we can get the new maximum this is how we can get the new maximum value again make sure that whatsoever value again make sure that whatsoever you are expecting I expected a two but I you are expecting I expected a two but I have a one so I have to take the minimum have a one so I have to take the minimum of both of them and then I have to place of both of them and then I have to place a one here so now I'll say okay at this a one here so now I'll say okay at this location which is a r of one I'll place location which is a r of one I'll place a one and then moving forward I can use a one and then moving forward I can use this previous value which is which is this previous value which is which is prev to actually compute the next value prev to actually compute the next value so this next value will be nothing but so this next value will be nothing but my prev value + one again when I just my prev value + one again when I just take minimum of both of them minimum is take minimum of both of them minimum is again two so my prev will become a two again two so my prev will become a two my prev will become a two and then this my prev will become a two and then this two will actually make sure I use when two will actually make sure I use when I'm Computing for the next element I'll I'm Computing for the next element I'll make sure that this next value will be make sure that this next value will be nothing but prev + one so it will be 2 + nothing but prev + one so it will be 2 + 1 is three and I'll take minum of three 1 is three and I'll take minum of three and 9 okay I get a three and that will and 9 okay I get a three and that will be my answer so I'm just trying to be my answer so I'm just trying to modify my input but RN okay okay okay modify my input but RN okay okay okay now also you imagined one thing you now also you imagined one thing you considered one thing that it is considered one thing that it is sorted can you sort it yeah I can I can sorted can you sort it yeah I can I can rearrange the elements of error in any rearrange the elements of error in any order so what I can do is I will simply order so what I can do is I will simply sort this stuff out which is 1 1 2 2 2 sort this stuff out which is 1 1 2 2 2 now I'll start from very beginning I now I'll start from very beginning I know that initially I can have a zero as know that initially I can have a zero as the previous because I know that if I the previous because I know that if I will add a one in my previous it will will add a one in my previous it will actually become a one so I know okay I actually become a one so I know okay I just simply add a one here so now my just simply add a one here so now my element which I have to compare which is element which I have to compare which is next element this is the next element it next element this is the next element it will actually become a one which means will actually become a one which means simply adding with the simply adding with the previous simply adding a one to my previous simply adding a one to my previous previous was zero so now I'll previous previous was zero so now I'll just compare one and one minimum is one just compare one and one minimum is one simply okay the current element I'll simply okay the current element I'll replace by one cool I just go on next replace by one cool I just go on next next I'm expecting to have a two but next I'm expecting to have a two but I'll take minimum oh bro it's a one I'll take minimum oh bro it's a one sorry bro sorry I'm really sorry it's a sorry bro sorry I'm really sorry it's a one minimum is one so for sure I can one minimum is one so for sure I can only place a one here I'll place a one only place a one here I'll place a one here cool I'll go next I'm expecting a here cool I'll go next I'm expecting a two now okay minimum I took minimum it's two now okay minimum I took minimum it's two okay I'll just leave it here now two okay I'll just leave it here now expecting I'm I'm expecting a three I'll expecting I'm I'm expecting a three I'll take minimum uh bro three you cannot take minimum uh bro three you cannot have the two is maximum you can have have the two is maximum you can have okay cool place a two next I'm expecting okay cool place a two next I'm expecting a three because just is it is a previous a three because just is it is a previous plus one I'm expecting a new value plus one I'm expecting a new value higher value previous plus one take higher value previous plus one take minimum bro bro bro again you cannot minimum bro bro bro again you cannot take a two expecting a three oh it's take a two expecting a three oh it's over cool last element was AR of nus over cool last element was AR of nus which is the maximum element I could which is the maximum element I could achieve was two same for this example achieve was two same for this example 100 and th000 I was initially the per 100 and th000 I was initially the per was Zero I was expecting a one minimum I was Zero I was expecting a one minimum I took it's a one okay cool move ahead I'm took it's a one okay cool move ahead I'm expecting a two minimum oh two is expecting a two minimum oh two is possible cool move ahead I'm expecting a possible cool move ahead I'm expecting a three minimum okay three is possible three minimum okay three is possible move ahead answer is three for this case move ahead answer is three for this case 1 2 3 4 5 same the per was Zero 1 2 3 4 5 same the per was Zero initially I am expecting a one yeah true initially I am expecting a one yeah true go ahead expecting a two yeah true go go ahead expecting a two yeah true go ahead expecting a three yeah true go ahead expecting a three yeah true go ahead expecting a four yeah true go ahead expecting a four yeah true go ahead spting five yeah true go ahead ahead spting five yeah true go ahead thus thus simply just check what's the expecting simply just check what's the expecting value just say Okay previous Value Plus value just say Okay previous Value Plus one is the new expected value take the one is the new expected value take the minimum of the current value of a of I minimum of the current value of a of I and the the value which is previously and the the value which is previously and just simply have your answer let's and just simply have your answer let's quickly and see it's just o of n uh we quickly and see it's just o of n uh we are not using any extra space so that are not using any extra space so that space will be o one itself cool uh let's space will be o one itself cool uh let's see it's pretty simple firstly as we saw see it's pretty simple firstly as we saw that we have to uh sort our entire array that we have to uh sort our entire array which is AR do begin and AR n because we which is AR do begin and AR n because we know that we have to like first we can know that we have to like first we can rearrange that in any order and also we rearrange that in any order and also we want this to be beginning with a very want this to be beginning with a very small value so that we can compare the small value so that we can compare the small values now I know that I need to small values now I know that I need to have a previous so I'll just have the have a previous so I'll just have the previous with a zero now I'll go on to previous with a zero now I'll go on to every element in my ARR now I'll just every element in my ARR now I'll just have uh say to that element that bro uh have uh say to that element that bro uh just do one thing um just check what is just do one thing um just check what is the current minimum value so for sure the current minimum value so for sure that minum value will only get placed that minum value will only get placed here so I just say bro minimum value is here so I just say bro minimum value is my current value which is this my current value which is this element um or I can just keep it by element um or I can just keep it by address so this element will be nothing address so this element will be nothing but AR and let's also have the N so that but AR and let's also have the N so that we can actually get that last element in we can actually get that last element in just by just saying okay AR of n minus just by just saying okay AR of n minus one so I just say that the current one so I just say that the current element will be nothing but minimum of element will be nothing but minimum of the element itself and also the current the element itself and also the current value which I'm expecting which is pref value which I'm expecting which is pref plus one I'm expecting a pref 1 and for plus one I'm expecting a pref 1 and for sure uh please put the prev as the sure uh please put the prev as the element whatsoever you have got element whatsoever you have got ultimately simply return the rror of nus ultimately simply return the rror of nus one and that should be your answer cool one and that should be your answer cool let's see let's quickly have this let's see let's quickly have this running yeah and by this you can simply running yeah and by this you can simply get this solved I hope that you guys got get this solved I hope that you guys got it right | 2024-03-25 10:25:38 | 1,846 | 1846. Maximum Element After Decreasing and Rearranging | Amazon | Leetcode 1846 |
|
ZMGfson_X94 | hi guys welcome to algorithms made easy today we will go through the day 7 today we will go through the day 7 problem from august lead coding problem from august lead coding challenge vertical order traversal of a challenge vertical order traversal of a binary tree binary tree please like the video and if you are new please like the video and if you are new don't forget to subscribe to our channel don't forget to subscribe to our channel so that you never miss any update so that you never miss any update given a binary tree we need to return given a binary tree we need to return the vertical order traversal of its the vertical order traversal of its nodes value nodes value for each node at position x comma y its for each node at position x comma y its left and right children respectively left and right children respectively will be at position x minus 1 comma y will be at position x minus 1 comma y minus 1 minus 1 and x plus 1 comma y minus 1. and x plus 1 comma y minus 1. running a vertical line from x equal to running a vertical line from x equal to minus infinity to x equal to plus minus infinity to x equal to plus infinity infinity whenever the vertical line touches the whenever the vertical line touches the same node we report the same node we report the value of nodes in order of top to bottom value of nodes in order of top to bottom that is decreasing y coordinates that is decreasing y coordinates if two nodes have same position then the if two nodes have same position then the value of value of node that is reported first is the value node that is reported first is the value that is smaller that is smaller return a list of non-empty reports in return a list of non-empty reports in order of x coordinate order of x coordinate where every report will have a list of where every report will have a list of values of node values of node let's take this tree and find the let's take this tree and find the coordinate of the nodes coordinate of the nodes for that let's take a grid where we have for that let's take a grid where we have x and y coordinate as shown x and y coordinate as shown the root will always be positioned at 0 the root will always be positioned at 0 comma 0. comma 0. 9 and 20 will be 1 level beneath the 9 and 20 will be 1 level beneath the root and one step root and one step left and right to the root respectively left and right to the root respectively so so with respect to the root nine will be at with respect to the root nine will be at x minus one comma y minus one x minus one comma y minus one and twenty will be at x plus one comma y and twenty will be at x plus one comma y minus one minus one similarly for this two till now we got similarly for this two till now we got one node at one coordinate one node at one coordinate now let's take two more nodes and see now let's take two more nodes and see the effect on the coordinates the effect on the coordinates with this we can see that there is an with this we can see that there is an overlap in 0 comma minus 2. overlap in 0 comma minus 2. as we need to add all the node values in as we need to add all the node values in same line in one list same line in one list we would get a result as shown we would get a result as shown here there are three things to remember here there are three things to remember or you can say three points to consider or you can say three points to consider first the ordering in the result is first the ordering in the result is primarily done on basis of x coordinate primarily done on basis of x coordinate starting with the smallest one second starting with the smallest one second for the values in same for the values in same column the ordering is done based on column the ordering is done based on rows from top to bottom fashion rows from top to bottom fashion and third for nodes with same x and y and third for nodes with same x and y coordinate coordinate the one with the lower value must appear the one with the lower value must appear first first so the sorting in this case will be so the sorting in this case will be based on the value of node based on the value of node summarizing we need to perform sorting summarizing we need to perform sorting on three parameters on three parameters x y and value to make this simpler we x y and value to make this simpler we will create a custom class will create a custom class and implement a custom comparator or and implement a custom comparator or comparable interface comparable interface that suits our sorting requirement the that suits our sorting requirement the class will have three parameters class will have three parameters x coordinate value y coordinate value x coordinate value y coordinate value and the node value and the node value let's call this class as location and let's call this class as location and the implementation the implementation of the comparable interface will look of the comparable interface will look like this like this in this we have overridden the compare in this we have overridden the compare to method to sort the data primarily to method to sort the data primarily based on x based on x in ascending order then on y in in ascending order then on y in descending order and lastly on descending order and lastly on value in ascending order now that we value in ascending order now that we have a data structure we need to travel have a data structure we need to travel the tree and store the value in it the tree and store the value in it so we will take a list of location and so we will take a list of location and traverse the tree traverse the tree which can be done using either bfs or which can be done using either bfs or dfs dfs in our case let's use dfs i have not in our case let's use dfs i have not shown the entire tree traversal in this shown the entire tree traversal in this video so as to keep this one brief video so as to keep this one brief you can find the similar video link in you can find the similar video link in top and in the description top and in the description to get an idea of tree reversal while to get an idea of tree reversal while reversing we will store the location of reversing we will store the location of each node in the data structure created each node in the data structure created so for root node the value of x and y so for root node the value of x and y will be 0 comma 0 will be 0 comma 0 and the value of its child node would be and the value of its child node would be in respect to the root node in respect to the root node the left child will have the coordinate the left child will have the coordinate x minus 1 comma y minus 1 x minus 1 comma y minus 1 while the right child will have the while the right child will have the value x plus 1 comma y minus 1. value x plus 1 comma y minus 1. this would be the value for each node this would be the value for each node the list of location after dfs traversal the list of location after dfs traversal will look like this will look like this now we would sort the list to obtain the now we would sort the list to obtain the data in correct order data in correct order after sorting the location list will after sorting the location list will look like this look like this we have the data in correct order now we we have the data in correct order now we just need to correct the format just need to correct the format so we will prepare the result list from so we will prepare the result list from a location list by iterating through it a location list by iterating through it all the values with same x coordinate all the values with same x coordinate would fall in the same list would fall in the same list so we need to compare the x coordinate so we need to compare the x coordinate values in each iteration values in each iteration and bring the same x values together and bring the same x values together if x is same we would need to put the if x is same we would need to put the values in same list or create values in same list or create a new one so the values will get a new one so the values will get combined combined in this manner at the end we return this in this manner at the end we return this result list result list summarizing the steps we will create a summarizing the steps we will create a custom class called location with custom class called location with x y and node value and add a custom x y and node value and add a custom sorting to incorporate sorting based on sorting to incorporate sorting based on x x y and value we can either use a y and value we can either use a comparator or comparable for this comparator or comparable for this we will initialize a list of locations we will initialize a list of locations and apply bfs and apply bfs or dfs on tree and store the location or dfs on tree and store the location for each node in list for each node in list after that we sort the list using the after that we sort the list using the custom sort for the class custom sort for the class we now iterate over the location list we now iterate over the location list and check if current x coordinate and check if current x coordinate is equal to the previous x coordinate if is equal to the previous x coordinate if yes we add the value associated in the yes we add the value associated in the same list same list otherwise we create a new list and add otherwise we create a new list and add the value in it the value in it at the end we return the result list the at the end we return the result list the time complexity for this algorithm is of time complexity for this algorithm is of n log n n log n while the space complexity is of n while the space complexity is of n here's the actual code snippet for the here's the actual code snippet for the method you can also check method you can also check out the link to this code in the out the link to this code in the description below description below thanks for watching the video please thanks for watching the video please like share and subscribe to the channel like share and subscribe to the channel also let me know in the comments what also let me know in the comments what you think about the video | 2024-03-25 14:30:42 | 987 | Vertical Order Traversal of a Binary Tree | Leetcode - 987 |
|
1bww6LWxE5g | hey what is up everybody welcome back to my channel my channel this is a part two this is a part two of um the problem 309 of um the problem 309 and uh and uh previously we had an intuitive attempt previously we had an intuitive attempt trying to solve the problem by breaking trying to solve the problem by breaking uh uh this this stock buy and sell problem into stock buy and sell problem into into sub problems into sub problems um um by you know cutting by you know cutting the entire array of prices into the entire array of prices into different different uh smaller chunks but looking at you uh smaller chunks but looking at you know where we had like uh um know where we had like uh um by looking at the specific places where by looking at the specific places where we had like a temporary one-day we had like a temporary one-day uh price drop uh price drop um that was kind of like an intuition um that was kind of like an intuition but but it's way more problem specific but but it's way more problem specific and it didn't turn out very well so and it didn't turn out very well so um we ended up looking at solutions um we ended up looking at solutions and trying to follow from the solutions and trying to follow from the solutions and uh one of the solutions was and uh one of the solutions was similarly using dynamic programming similarly using dynamic programming but the explanation was a a little bit but the explanation was a a little bit vague or confusing to me so i actually vague or confusing to me so i actually did it uh did some um learning offline did it uh did some um learning offline now i'm prepared um and i got some now i'm prepared um and i got some slides actually to show you my slides actually to show you my upgraded understanding of that solution upgraded understanding of that solution and hopefully my solution is more and hopefully my solution is more intuitive at least to myself intuitive at least to myself and explaining you know and explaining you know the combination of using dynamic the combination of using dynamic programming and programming and state machine state machine to uh basically to uh basically decompose this problem and solve it decompose this problem and solve it using dynamic programming all right so using dynamic programming all right so let's uh let's uh take a look take a look now now this is the solution that we were this is the solution that we were looking at and so let me just remind you what we're doing here we were doing uh we're doing the uh uh best time to buy and sell stock with the cool down so unlike the previous buy and sell stock problems now we have to actually go through a day of cool down which is like doing nothing and wait until we can buy again on the next day so then we looked at solutions and this so then we looked at solutions and this approach one dynamic programming with approach one dynamic programming with state machine was the one we looked at state machine was the one we looked at and uh you know although these state and uh you know although these state transitions transitions were kind of making sense were kind of making sense you know this you know this this table of you know deriving things this table of you know deriving things was a bit confusing to me was a bit confusing to me uh uh but then i just you know but then i just you know uh thought about it offline and now i uh thought about it offline and now i think uh i figured it out so i'm gonna think uh i figured it out so i'm gonna share with you what is my understanding share with you what is my understanding of what this is okay so now let me now of what this is okay so now let me now um switch to my um switch to my own slides that i prepared for own slides that i prepared for this this prepared for this uh for this problem all right so if you remember we had a uh example one where we had a five-day uh stock price list uh one two three zero two right and we start basically from day zero and and we can and we can basically either buy or just you know you know wait right and uh and this is like the three states that i'm defining actually let me start by defining i'm gonna just make a brand new slide and start um showing you guys what i mean by these three states right so i'm gonna actually go here and make stuff on the go we have empty we have frozen we have holding those are the three states that we have right and now let me just make them a little larger not really okay let's just do it like this so when we're empty of course we can uh we can you can go from empty to holding yeah the color is fine yeah the color is fine by by what by by buying right so this by by what by by buying right so this action here would be called action here would be called buying buying so if we buy we go to holding so if we buy we go to holding uh and uh and if we if we stay in empty like we don't do anything stay in empty like we don't do anything while we're empty while we're empty uh oops uh oops yeah something like that yeah something like that or something like this yeah that is when we're like uh not doing anything right so it's like uh uh hold or you know rest right and while we are holding we can actually still keep holding so once we're in holding what we can do is that we can keep holding keep holding the stuff right hey this is better i wish i could add more points here uh how do you do that actually add more points uh um for my shape i don't know alt shift control doesn't really work okay all right fine um then we're just gonna say that if we rest we're gonna stay in holding but also we can go from holding to frozen by by selling right so if we have a cell action instead um we can go from holding to frozen uh so we have a one day freeze right and after our one day freeze we'll definitely go into empty right yeah we're definitely going to empty oh let me just yeah put something there we'll definitely go into empty and that is by the action of uh rest we just wait right basically you rest we just wait right basically you just rest and uh just rest and uh you will go into empty you will go into empty actually you know what let me just put actually you know what let me just put this here it's a little weird looking that way but anyway this is what we have right okay like this maybe okay like this maybe let me just make things a little bit let me just make things a little bit uh normal yep this looks better right so this is our basically our state transition uh so now let's go back into presentation mode and uh because this looks better right we have the state transition like this so we have three states and we have basically and they're not like totally symmetric and they're not like totally symmetric for example you cannot stay in frozen for example you cannot stay in frozen state state all right so all right so now let's switch to this now let's switch to this uh uh tabular tabular view where view where uh we can be switching uh we can be switching among these three states but we're also among these three states but we're also looking at the state on each day looking at the state on each day specifically specifically and we're basically uh comparing that and we're basically uh comparing that against the price for each day so that against the price for each day so that it's easier for us to calculate what's it's easier for us to calculate what's happening happening uh anyways uh anyways um so um so um if we just look at it this way we can solve this by uh so-called dynamic programming in a forward direction it's um but you know what when when actually when i was like learning about dynamic programming you know in in terms of a theory uh people i always uh learned it as like a backward direction algorithm i'll explain that difference in a bit but let's just you know stick with the forward direction which is more suitable and intuitive to this to the stock buying selling problem and then i'll show how it could be generalized or equivalent to uh the more usual traditional backward dp uh in that form so now let me just start on this and uh because i'm now going to start some editing i'm just going to switch to this editing mode right what are we do we're looking at here so what are we do we're looking at here so if we compare what we had before in this if we compare what we had before in this transition uh for among the states transition uh for among the states and we look at it here um and we look at it here um let's start from day zero and because let's start from day zero and because we're going forward we're gonna we're going forward we're gonna basically examine basically examine what is possible and what is not on day what is possible and what is not on day zero okay zero okay um for example um for example let's see if on day zero it's possible let's see if on day zero it's possible to just stay empty to just stay empty uh yes of course we can right uh yes of course we can right and uh is it possible to be holding on and uh is it possible to be holding on day zero day zero no because holding no because holding means that you already have some stocks means that you already have some stocks if you don't have any stocks if you don't have any stocks it does not it does not it does not qualify as holding so let's it does not qualify as holding so let's be you know actually more specific uh on be you know actually more specific uh on that so that so this empty leg has stock you know this this empty leg has stock you know this is like is like no stock right when you're empty of no stock right when you're empty of course that means you have no stock course that means you have no stock oh let me use a different font maybe oh let me use a different font maybe let's choose let's choose yellow yep so that means you have no yellow yep so that means you have no stock stock if you're holding of course if you're holding of course you know you know you definitely have stock you definitely have stock right right uh but when you're frozen uh but when you're frozen of course that means you have no stock of course that means you have no stock as well because you just sold something as well because you just sold something so you have no stock so you have no stock uh therefore at the beginning of the um uh therefore at the beginning of the um day one because day one because because we haven't because we haven't we haven't bought anything yet um we haven't bought anything yet um uh so uh so um um we cannot be in holding position so i'm we cannot be in holding position so i'm just going to put it put an x here just going to put it put an x here meaning that it's impossible also meaning that it's impossible also we cannot be frozen because we cannot be frozen because frozen frozen uh uh only happens only happens after selling right so i'm not going to after selling right so i'm not going to say this is a frozen state because this say this is a frozen state because this is literally just day one we haven't saw is literally just day one we haven't saw i haven't sold anything yet so the only i haven't sold anything yet so the only possibility is possibility is to stay in uh empty state to stay in uh empty state right and then and then that's it and right and then and then that's it and we're gonna move on to day day one we're gonna move on to day day one using zero indexing right because in using zero indexing right because in zero indexing the first day is day zero zero indexing the first day is day zero and the second day is day one all right and the second day is day one all right so on day one let's see what can so on day one let's see what can happen um happen um well well on day one we on day one we we also i mean we also i mean uh let me just put down something here uh let me just put down something here as well you know we use we're gonna use as well you know we use we're gonna use we're also gonna track we're also gonna track our cache our cache right track a cash at each state you right track a cash at each state you know at each on each day know at each on each day on each day on each day yeah yeah uh uh you know before action you know before action before and before any action before before and before any action before taking action right taking action right so so here is here is here's what it is here's what it is on each day we can take an action either we we hold or we sell or we you know buy right but there's definitely like an amount of cash in the morning you know before the market uh like just when the market you know uh starts or even before the market starts you're going to have a certain amount of cash in your hand and we're going to track that we're going to use that number and we're going to write that number into um into the circles here so on day 0 oh that's oh that's you can buy uh you can also um you can buy uh you can also um uh let me just actually make the text uh let me just actually make the text black that way yeah you can see them black that way yeah you can see them uh uh on day zero whether you you try to buy on day zero whether you you try to buy the stock at price one or not the stock at price one or not um before you take any action your value um before you take any action your value is at zero right is at zero right so we're going to write our zero there so we're going to write our zero there um um and actually and actually i'm gonna i'm gonna make a modification to that say make a modification to that say track our maximum track our maximum possible possible cash each day before taking action cash each day before taking action and that when we use the keyword maximum and that when we use the keyword maximum this is where you know dynamic this is where you know dynamic programming comes in and we will find programming comes in and we will find that sense will make sense as we go on that sense will make sense as we go on all right just so just now trust me all right just so just now trust me we're gonna use this number to represent we're gonna use this number to represent our maximum possible cash our maximum possible cash uh each day before taking uh each day before taking taping the taking the action on that day taping the taking the action on that day so this is going to be so this is going to be uh definitely zero right because on day uh definitely zero right because on day zero whether we buy or not you know zero whether we buy or not you know uh uh in the morning we're gonna have zero in the morning we're gonna have zero asset asset um um well then on date on day one well then on date on day one on day one let's take a look at this on day one let's take a look at this empty state is it possible that we are empty state is it possible that we are gonna be gonna be empty on day one yeah of course so why empty on day one yeah of course so why is that possible we're gonna start using is that possible we're gonna start using some arrows to to draw why it's possible some arrows to to draw why it's possible because because if we didn't buy anything on day one on if we didn't buy anything on day one on day zero and uh we just you know don't day zero and uh we just you know don't do anything and just rest we're gonna do anything and just rest we're gonna have a value of zero uh on have a value of zero uh on uh in state empty on day one uh in state empty on day one uh but there is another possibility uh but there is another possibility because if we look at our transition um because if we look at our transition um like state like state uh uh uh uh state machine here another way to uh go state machine here another way to uh go to empty to empty if is if we were frozen previously if is if we were frozen previously right but right but is it possible that we were frozen is it possible that we were frozen previously well previously well um you know what because this is um you know what because this is impossible so you know although impossible so you know although theoretically it's possible but in theoretically it's possible but in in in reality because we couldn't be in in in reality because we couldn't be in the frozen state on day zero so this is the frozen state on day zero so this is like impossible so the only value that like impossible so the only value that you know this value you know this value uh can take is is value zero okay let's uh can take is is value zero okay let's move on to holding so we ask ourselves move on to holding so we ask ourselves um um is it possible to be holding is it possible to be holding a stock on day two on day one sorry on a stock on day two on day one sorry on day one day one yeah it's possible if we had purchased yeah it's possible if we had purchased the stock you know before day one right the stock you know before day one right um um so that is possible so that is possible and we're gonna just start drawing the and we're gonna just start drawing the line so line so um it's possible if if we were like um it's possible if if we were like previously holding previously holding right but because this is impossible right but because this is impossible like we cannot be holding on day zero so like we cannot be holding on day zero so this arrow is now just no this arrow is now just no meaningless meaningless but there's another possibility but there's another possibility if we if we just bought the stock on day zero just bought the stock on day zero l as uh as the action on day zero then l as uh as the action on day zero then we would have acquired a stock we would have acquired a stock uh at the price of one uh at the price of one uh on day zero and now in day uh on day zero and now in day one we will be holding and one we will be holding and what is the value what is the value what is the cash value what is the cash value we have right now what for if we're not we have right now what for if we're not if we're not selling anything then if we're not selling anything then we are still gonna have um we are still gonna have um uh uh well because we have spent you know if well because we have spent you know if you buy something now you're all you you buy something now you're all you have is stock right but your cash drops have is stock right but your cash drops so actually it's going to be minus one so actually it's going to be minus one here why because here why because you need to spend some investment in you need to spend some investment in order to to obtain the stock right order to to obtain the stock right so on day one you're gonna have one so on day one you're gonna have one stock but then stock but then your cash flow is minus one so that your cash flow is minus one so that makes sense makes sense okay so that's all the all the ways that okay so that's all the all the ways that you can uh be holding on day two let's you can uh be holding on day two let's take a look at frozen is it possible take a look at frozen is it possible that we are frozen on that we are frozen on uh on day one uh on day one well well in order to be frozen the previous day in order to be frozen the previous day has to be a selling action has to be a selling action and for the previous day to be a selling and for the previous day to be a selling action the previous day itself has to be action the previous day itself has to be in the holding state because it's only in the holding state because it's only in holding state where we actually have in holding state where we actually have a stock if you look back here a stock if you look back here right holding state uh right holding state uh is only possible if you already have is only possible if you already have stock um stock um uh before before that date right so uh before before that date right so we have to be in the holding state so we have to be in the holding state so it's gonna be like this it's gonna be like this and this but since this previous holding and this but since this previous holding state on day 0 is impossible state on day 0 is impossible so we're going to call so we're going to call we're going to call this as x which we're going to call this as x which means you know it's it's an impossible means you know it's it's an impossible state it's an unachievable state state it's an unachievable state anyways anyways right so right so uh let's move on to uh let's move on to day two then so on day two day two then so on day two again we start asking ourselves again we start asking ourselves is it possible to be an empty state on is it possible to be an empty state on day two well it's of course possible day two well it's of course possible because because what you can do is that you can what you can do is that you can basically uh basically uh um inherit inherit the the empty state um inherit inherit the the empty state like like you don't buy anything uh on you don't buy anything uh on you you don't hold anything on day one you you don't hold anything on day one so you can continue to hold nothing on so you can continue to hold nothing on day two uh day two uh and that is going to give you and that is going to give you um a cash value of zero since you have um a cash value of zero since you have not bought anything not bought anything um your your cash um your your cash is is at the neutral value at the neutral value uh another way to stay to to be in empty uh another way to stay to to be in empty state state uh is if you had uh uh is if you had uh excuse me if excuse me if uh you had sold uh you had sold something on the previous day which something on the previous day which means that you will be oh no you have sold something on the day before yesterday so then you had because you know there's a cooldown requirement right so that means like um if on day one we had we were like in frozen state then on day day two we could be in empty state but since this state you know we have we have shown before that it's impossible to be in frozen state uh on day one so basically this line does not provide any uh alternative values for for for for this empty state whoops empty state on day two so that's all possibilities for empty state on day two let's move on to holding state on day two so is it possible to be holding on day two well um in order to be holding there are two possibilities the first possibility is that yesterday we didn't have it didn't have anything and yesterday we actually bought something so there's that possibility so if that's the case uh so on day on day one we bought a stock uh at the price of two so then our net cash is going to be net cash flow or our net cash amount is going to be minus two because uh that buy that buying action uh on day one has cost us you know two two dollars so we're at -2 but there's another possibility right if we had bought actually previously on day zero and we were holding it on day one then we can actually um you know have a net cash value of minus one and uh here is where the maximum you know here's where the uh the maximum thing comes in because um in the end we want to you know maximize our kind of like rolling uh cash on our our rolling cap you know our our net cash gain in the end uh we always want to maximize our cash amount at any state so we're gonna inherit uh this cash amount from uh holding on day one so we're gonna we're gonna do that because because now minus one is greater than minus two so we take minus one value here so again the reason of you know taking a maximum is that you know um all the actions forward can can you know can can be um forward in the future can can be something that we decide later on and we're just you know look looking back to see what is the you know uh the maximum rolling uh net cash uh at any state uh on a particular date and that is what we're looking for like we're trying to build the maximum uh cash history we're trying to build our maximum cash history so let me just write that down here just if it makes more sense you know we built uh uh we built our maximum cash history his uh history history yeah this is what we're doing here we're building we're building our maximum uh cash history that's what we're aiming to do here so our maximum cash history here is now minus one now let's take a look at the third one here uh frozen is it possible to be frozen on day two well um we could because if we want to be frozen on day two that means we must be selling something on day one and it's possible because uh this holding state for day one is possible right so uh what's the value here um so uh at the holding state on day one we had an uh net cash value of minus one but since we sell uh uh we take the selling action on day one that's going to correspond to a price of two dollars so we're gonna have we will have we will obtain like a two dollar uh selling reward and minus that you know uh one dollar uh um cost price uh our our um total net cash uh value is at one here so one equals to 2 minus 1 right so our net cash value is at 1 here so that's for day 2. now we're going to repeat this process onward and take a look at now what is the maximum possible cash value at the at the empty state on day three so one there empty state on day three so one there are two ways to achieve an empty state are two ways to achieve an empty state on day three on day three number one number one is if we were in empty stating day is if we were in empty stating day two and that will give us a continued two and that will give us a continued value of zero value of zero another way to achieve empty state on another way to achieve empty state on day three is if day three is if we were we were frozen on day two frozen on day two after selling something after selling something on day one right so on day one right so uh if that's the case well because the uh if that's the case well because the frozen action frozen action during the frozen day you basically just during the frozen day you basically just rest and do nothing you don't have any rest and do nothing you don't have any change in your cache value change in your cache value you just copy this value here and since you just copy this value here and since this value is one is greater than zero this value is one is greater than zero we take the maximum like we uh we take the maximum like we uh like we specified here like we specified here uh we are going to use one here so that uh we are going to use one here so that is the value for the empty state on day is the value for the empty state on day three three now okay we move on to um holding the now okay we move on to um holding the value the cash value of a holding state value the cash value of a holding state on day three on day three and and what are the possibilities well there what are the possibilities well there are again two possibilities are again two possibilities possibility one is if we were empty and possibility one is if we were empty and we bought we bought uh something actually uh uh something actually uh uh uh on the previous day so on the previous day so that means we bought that means we bought uh one stock at the price of three uh one stock at the price of three dollars dollars on day two so on day two so uh today what do we have well we have uh today what do we have well we have minus three dollars because we had like minus three dollars because we had like a deficit now we just turned our three a deficit now we just turned our three dollars into one stock dollars into one stock uh and one other way is if we just uh and one other way is if we just hold if we hold on to our existing stock hold if we hold on to our existing stock from a previous purchase from a previous purchase in that case in that case we just directly copied the we just directly copied the on the cash value on the cash value from the holding state from the previous from the holding state from the previous date and that is -1 and now because -1 date and that is -1 and now because -1 is greater than minus 3 we're going to is greater than minus 3 we're going to reduce -1 here reduce -1 here all right so we just calculated the all right so we just calculated the holding state value on day 3. now let's holding state value on day 3. now let's move in now let's move on to the frozen move in now let's move on to the frozen state value on day 3. is it possible to state value on day 3. is it possible to be holding be holding to be like in frozen state on day three to be like in frozen state on day three yeah it's possible yeah it's possible that means we were that means we were selling on day two and we could because selling on day two and we could because on day two we could be owning the stock on day two we could be owning the stock um and let's take a look at the selling um and let's take a look at the selling value on day two it was three dollars value on day two it was three dollars so we had a minus one cash net cash so we had a minus one cash net cash uh amount and now we sell it we sold it uh amount and now we sell it we sold it at three dollars so now three minus one at three dollars so now three minus one equals to two now we had uh now we have equals to two now we had uh now we have a net cash value of two dollars here in a net cash value of two dollars here in this frozen state on day three all right this frozen state on day three all right so now let's move on to the final day so now let's move on to the final day day four day four for empty state again uh we're gonna for empty state again uh we're gonna take a look at these two possibilities take a look at these two possibilities the first one is just the first one is just uh uh keep holding uh keep uh keep holding uh keep uh resting and uh resting and uh keep ourselves in the empty state and keep ourselves in the empty state and the values of course the values of course wait it's not zero uh sorry about that wait it's not zero uh sorry about that it should be one we just inherit that it should be one we just inherit that value of one from the previous day right value of one from the previous day right uh and then uh and then one other possibility is if we one other possibility is if we uh uh we were in the we were in like the we were in the we were in like the freezing state freezing state uh previously uh previously uh and because uh and because uh you know spending the frozen state uh you know spending the frozen state spending the uh spending the uh the time you know in the frozen day the time you know in the frozen day doesn't really gain us any cash we're doesn't really gain us any cash we're just going to copy the cash value here just going to copy the cash value here and because 2 is greater than the 1 here and because 2 is greater than the 1 here we're going to take 2 as the value for we're going to take 2 as the value for empty state here empty state here and for the holding value and for the holding value there are of course again two different there are of course again two different values two different possibilities the values two different possibilities the first one is that if we bought something first one is that if we bought something on day three on day three uh and on day three the stock is almost uh and on day three the stock is almost free it is indeed free so uh we do not free it is indeed free so uh we do not have a drop in cash and in addition we have a drop in cash and in addition we now have one stock now have one stock uh so our cash value is one uh so our cash value is one and then um and then um what about our what about our uh what if we hold on to you know the uh what if we hold on to you know the previously owned cash uh stock then we previously owned cash uh stock then we will have a value of minus one but since will have a value of minus one but since minus one is less than one we still take minus one is less than one we still take the one value the one value uh by you know buying a stock for free uh by you know buying a stock for free from day three from day three all right what is the value of frozen all right what is the value of frozen state on the last day well if it's state on the last day well if it's frozen state that means we just sold frozen state that means we just sold something something uh um uh um uh uh yesterday so on day three yesterday so on day three so so let's represent that with this arrow let's represent that with this arrow here here and if that's the case what is the and if that's the case what is the selling value well unfortunately if selling value well unfortunately if we've sold we've sold the uh the stock on day three that's the the uh the stock on day three that's the the you know the worst thing that you the you know the worst thing that you can do you're just giving away your can do you're just giving away your stock for free so you're still going to stock for free so you're still going to have a deficit of minus one have a deficit of minus one all right so is this the end all right so is this the end uh we're looking at you know a net cash uh we're looking at you know a net cash value of two one and minus one here can value of two one and minus one here can we say this is the end of it we say this is the end of it no not really because you know what no not really because you know what ins remember in holding state we we're ins remember in holding state we we're still holding one stock here right still holding one stock here right um um but but but you know um but you know um what we can do we can still take one what we can do we can still take one action on day four right uh remember we action on day four right uh remember we can still take that action so let's can still take that action so let's actually um actually um uh uh um uh uh um i guess i guess what what we're gonna do what what we're gonna do is we're gonna um is we're gonna um use a use a uh let's change this color of this uh uh let's change this color of this uh filling filling change the fill in color here we're change the fill in color here we're gonna use gonna use a yellow as like the final value okay so a yellow as like the final value okay so our final value for our final value for being in the uh being in the uh being in the empty state being in the empty state on day four is still two because on day four is still two because we don't hold any stocks we don't hold any stocks but if we were but if we were in like in like if we were in the holding state on day if we were in the holding state on day four then at the end of the day you know four then at the end of the day you know you know this is like day four end of day let me just say that you know just to explain a little bit more intuitively day four end of the day you can you can do like a plus two here because because why because because you have still one stock and you can still sell that stock on that day uh and then basically clear it right after declaring you're gonna have a value of three um and then what about what about the other one here you're just gonna do minus one because uh if you were frozen you know at the end of the day you're still maybe you're still at the same value the next day you're free but at the end of the day you still have the same amount of money so this is our obvious champion here so i'm just gonna uh surrounded by a uh by a green thick green edge to say okay this is our optimal solution right um because at the end of the day on day four we have three dollars and what are the and what are the states that leads to it well we can now backtrack uh it's uh it's gonna be this as well right and uh let me just make it thick it's gonna be this as um it's gonna be this this state right um make it thick it's gonna be this state um yeah that's how we uh we went to that state right uh uh yes uh and and then it's gonna be uh this state let me just you know give it an outline make it thicker uh and then it's gonna be this state right because these are the actions that are leading to the optimal value there so we're going to just highlight it there here we go here we go uh and why was that because because you know um for all these possible actions you know actually there was like a preferred action at each um at each um leading leading to each state we should have like recorded that so actually let's let's run that again right let's run it over again um because we wanted to record it so for day zero it was basically like that for day one uh what what's the action that you know lead to the value zero here it was this so i'm going to actually um make this thicker okay make this uh like yeah three pound thick uh and then for this one of course it was this action that led to the uh uh this so we're gonna just use the format painter to highlight and then for this this one uh uh well it was this but then i mean it's it's a uh infeasible impossible state and for day two empty uh the value of these two empty is this one here so hey format paint uh format paint this we're gonna again format paint now for holding state on day two uh how how did we get here we get here by you know holding it for this state for the frozen state in order to get value of one we were seldom on day two right and then uh for day three uh to get the value of one we were actually taking this uh uh this line here and then for for this holding state on day three to achieve minus one we were what we were doing we were actually uh just still resting um for this frozen state here to achieve the value of two we were actually selling right and uh for dave on day four in order to achieve number of two here we were doing the uh we were doing the uh the yeah um the resting after the frozen state and then for to achieve the number of one here uh we were basically getting free stock on day three um and for the last one here because this is the only way you can go that's it uh right so now what are these thick arrows right so let me just uh write that down the thick arrows the thick arrows the thick arrows meaning the thick arrows meaning optimal optimal uh decision right optimal decision optimal decision at each state um leading to leading to each state right each state right leading to each state leading to each state for example yeah the optimal decision for example yeah the optimal decision that led to that led to this state having a value of minus one this state having a value of minus one is is this arrow is is this arrow so yeah uh so that is why when we so yeah uh so that is why when we have selected our have selected our um um best value at the end of day four best value at the end of day four we can just you know backtrack these we can just you know backtrack these thick arrows to find our trajectory thick arrows to find our trajectory and uh you know basically find out our and uh you know basically find out our decisions decisions so this is uh this is like so this is uh this is like um um how using dynamic programming in a how using dynamic programming in a forward direction forward direction we can solve our problems we can solve our problems and i'm going to show you actually the and i'm going to show you actually the equation equation that um that um that represents it that represents it so the equation that represents it is so the equation that represents it is the one the one uh on top uh on top so you have you have a so you have you have a g of x k j well what does it mean the g of x k j well what does it mean the symbol g symbol g uh is a function symbol uh is a function symbol this function is the maximum this function is the maximum um is the maximum cash value given the state in the bracket right the maximum cash value that you can accumulate up to this point um given the state inside the bracket and what is the state well x um x of k and j um what what this means is uh so x of k it is k is like the it is k is like the the day index or the the day index or the uh is it uh uh is it uh no not really okay xk is like no not really okay xk is like uh hold on a second yeah so k is the time index in our case we have like 0 1 2 3 4. so k equal to zero one two three four it's a time index and j um j is the actual state index we have three states so j could be zero one two uh you know depending on how we define our states so uh the k index is our time index the j index is our discrete state index uh for example if we have like k 0 j 0 and if r 0 means um uh means the state of um empty then that means okay uh at day zero we're empty so that's what k zero zero would mean so anyway this g function which is the maximum cash value of of the corresponding state it could be we can express this as a recursive relationship and it depends on um uh depends on the uh on these following things right um first um it's a maximum like overall it's a maximum function uh and the iterator is uh let's say uh uh you know the state we were like a day uh you know the state we were like a day before before right so k minus one means this is like right so k minus one means this is like a day before and i is a day before and i is uh you know the kind of like the state uh you know the kind of like the state that we were uh from from yesterday that we were uh from from yesterday so so then then uh uh so in this bracket we have two compo two so in this bracket we have two compo two parts the first part is a parts the first part is a uh arc reward so what does arc reward uh arc reward so what does arc reward means it's the uh the reward of you know means it's the uh the reward of you know uh uh of of performing an action uh of performing an action on a previous day so for example if on day k minus one you sold a stock uh and then you landed at uh this may be a frozen state uh on the current day then your arc reward is going to be uh you know uh whatever the the stock value was on yesterday so this is the arc reward and uh let's make another example if we were holding um if we took like resting uh as the action yesterday then the arc reward is of course zero like if you don't buy or don't sell then of course you're not getting cash or losing cash at all so that's what arc reward means and then plus um this uh this is the same function uh symbol plus the maximum cash reward value uh uh on a day before right so on day k minus one uh at the state i so again i could take three values zero one two representing the uh empty state the holding state and the frozen state so basically um this is like the uh kind of like the uh recursive relationship for your dynamic programming uh but it is somehow in a forward direction the sense that you were relying on a previous day information to calculate the current day information so you're basically going forward in time uh while you were like well you calculate this thing this these rewards in uh in a recursive manner uh and this g we can say that you know it represents the rolling reward in the past uh you know up to the x k minus 1 i uh yesterday x k minus 1 i uh yesterday so this is the forward direction so this is the forward direction but you know this is not how normally but you know this is not how normally people formulate dynamic programming people formulate dynamic programming and the backward direction is is and the backward direction is is actually how people actually how people formulate dynamic programming recursive formulate dynamic programming recursive relations which is the one below relations which is the one below i'm going to show you next i'm going to show you next um how we could solve the same problem um how we could solve the same problem actually in the actually in the in the nominal in the nominal uh representation uh representation of a dynamic programming done in the of a dynamic programming done in the backward direction backward direction so i have a slight for that let's uh so i have a slight for that let's uh let's take a look and see how we solve let's take a look and see how we solve this same problem this same problem uh uh but flipping the direction so that you but flipping the direction so that you know know this dp problem is going to be your this dp problem is going to be your textbook dp problem and you if you have textbook dp problem and you if you have learned dynamic programming somewhere learned dynamic programming somewhere in this manner you will immediately in this manner you will immediately recognize it recognize it so now let's get into it uh first let's so now let's get into it uh first let's uh take a look what's the difference uh take a look what's the difference if you if you go back to our forward direction you you go back to our forward direction you you notice that we notice that we um we list the days um in an ascending um we list the days um in an ascending order day zero all the way to day four order day zero all the way to day four and our price of course is accordingly and our price of course is accordingly uh in the in the correct uh in the in the correct um you know um you know time forward time forward order but now when we order but now when we solve this in the backward direction we solve this in the backward direction we actually we actually flipped uh the actually we actually flipped uh the order of um of the days and now day four order of um of the days and now day four is the first one and day zero is at the is the first one and day zero is at the end the reason for this is that you know end the reason for this is that you know in order to apply in order to apply uh transfer or transform uh transfer or transform on the stock by this stock buy and on the stock by this stock buy and selling problem into a standard dynamic selling problem into a standard dynamic programming form uh in the backward programming form uh in the backward direction we this is what we had to do direction we this is what we had to do uh and i will explain in the very end uh uh and i will explain in the very end uh why we have to do so and uh and and that why we have to do so and uh and and that will basically explain will basically explain maybe uh your your question now i i maybe uh your your question now i i think you might have that question now think you might have that question now like why do we have to do this backward like why do we have to do this backward uh how why do we have to flip the days uh how why do we have to flip the days so now let's just uh so now let's just uh uh uh take this problem as a standard uh take this problem as a standard uh dynamic programming problem dynamic programming problem uh in which now let me just show you the uh in which now let me just show you the formulation here formulation here uh uh in which this is how it uh in which this is how it uh how it works so how it works so in a dynamic programming problem uh you in a dynamic programming problem uh you could either be like minimizing an could either be like minimizing an overall cost during a doing a process or overall cost during a doing a process or you can be like maximizing your overall you can be like maximizing your overall gain in a process in this case we're gain in a process in this case we're maximizing like a gain so we're using maximizing like a gain so we're using the max the max symbol here symbol here and and now now this g here this g here it has a different meaning it has a different meaning the g the g what it means here is that it means what it means here is that it means the maximum the maximum reward uh uh you can get onward right like from now on all the way to the last day uh uh let me just actually write that down because this is important let me uh yeah put another label here right this is like the maximum maximum reward onward make some reward onward from current from current uh from current state and time uh from current state and time yeah so this is what this uh this g yeah so this is what this uh this g means means and uh and uh let's just let's just do it that way let's just let's just do it that way make it a white make it a white uh well previously uh well previously our g when we were defining our problem our g when we were defining our problem in a forward direction in a forward direction it meant um it meant um our maximum reward our maximum reward uh uh our maximum reward our maximum reward uh uh uh uh you know maximum rolling reward so far uh uh um at this current state and time right so these are these are different slightly different but you know in fact they've been quite different things previously the maximum rolling award so far at this current state and time is the accumulation from all previous histories right up to this time and when you know in the standard uh dynamic programming backward direction what we would like to uh uh calculate is the maximum reward onward in the future uh uh from the current state and time on like if you land at this state you will be certain that you know the best thing you can do in the future uh until you die or until at the end of the game is is that much and you and that's it like like there's a limited future i mean there's a limited future of games that you can you can you can achieve and um basically that's that's your that's your cap that's your ceiling that's your cap right um so it's like okay it's it's not very exciting but you know it's a certain thing that you that you can rest a certain um that you know if you're at that state uh then the g value at that state is the maximum amount of reward you can ever get you can ever ever ever get moving onward if you don't screw up or actually if you if you if you perform your best yeah that's that's what it means uh uh to be the g or the maximum reward onward from the current state and time in the standard uh dp backward direction definition whereas previously this you know variant this actual variant this forward direction variant yeah let's just actually call it variant forward direction variant in this variant rg was defined as the maximum rolling reward so far at this current state and time so it's like the wealth or the money we've accumulated so far if we're in this state at this current time and the future we don't know the future could be sad could be really awesome but we just don't know right so that's why i say that you know to compare these two um directions you can you know casually just compare it as investment versus work you know in the world in the world of working you you know like you know if you work hard at the end of the year you're gonna get x amount of salary and if you work very hard and you get promotion all the time uh until the day you retire there's like there's like a cap right there's like a maximum amount of money you can make by working very hard making all the right decisions uh you know uh work your relations with your supervisor and whatnot you know do your best at work uh that's the maximum amount of reward you're gonna get um uh uh until you retire right or until you die uh so the this is like the conventional dynamic programming uh perspective actually why not let's just you know call it the work perspective of dynamic programming right so yeah work perspective perspective that's a first okay that's my invention now now it's official we're gonna we're gonna call it work perspective dp uh and then this this this forward direction variant is actually the invest perspective of dp so yeah so this is where you are like kind of like your own boss with your own money uh and uh you're you're looking at you know what is the maximum reward i have at this current step and uh the future is something um the future is something uncertain and we have to you know uh recursively calculate to to to basically to find out the answer whereas you know in the work perspective dp you know you kind of like start with the maximum answer or like the uh the best result already and then you just calculate backward till the current time uh and basically your objective is to you know to not screw up uh that best reward that you kind of already knew ahead um but then in this forward direction uh if you're making rewards then you always start looking at you know what's the current uh what's the current rolling reward and what are the actions you know in the future that can they can you could build up my uh asset and build up my uh maximum reward onward so yeah so this is how i can best explain um this new variant of forward direction and backward direction um okay so back to back to you know i'm going to walk you walk you through this uh uh expression uh a little bit so in the traditional or conventional dynamic programming expression uh if we're talking about rewards then the reward at any uh time or any day k uh within the state i is going to be um the maximum of all possible combinations of you know you know maximum onward rewards i'm gonna remain maximum onward rewards i'm gonna remain this uh onward reward right in the this uh onward reward right in the future future uh rolling reward onward reward yeah so um max reward yeah let's call it uh onward reward or best reward how should we call it best reward in the future you know just onward reward okay onward reward right uh the best onward reward uh from uh next state uh on the next day plus the arc reward by taking certain actions on the current day which leads to the state j on the next day on day k plus one so in principle these two are the same i mean if you flick flip the time direction uh one expression becomes the other so um it's just that the backward direction expression is more popular is and it's how bellman i think back in the 1950s when he invented this algorithm of uh bellman's principle of optimality uh came up with so this has become this becomes like the uh established expression of dynamic programming and now we're going to solve the same problem now uh in in that fashion so now okay with all that explained now let's look at the problem again we have uh reversed the dates and then we're going to basically change our perspective and think of the reward in a different way now we're looking at the maximum reward onward from current state and time and we're going to start from the last state and so on this empty state on day 0 we're going to basically ask ourselves right what is the maximum onward reward now onward means looking back right because now time has been flipped so onward means you know going going to the right but there's no more um days to the right so uh so it's gonna be actually uh empty so we'll be at zero well let me actually now do a little bit of a change here make the text color black yeah so it's gonna be zero and for holding uh first let's check if if this possible if this state is valid um if this is like in holding state then um then you know a day before right um then you know a day before right onward which in other in uh onward which in other in uh in other words a day before or yesterday in other words a day before or yesterday we must be we must be having some stock but that is impossible having some stock but that is impossible like right this is like the initial day like right this is like the initial day already already and a yesterday and a yesterday we couldn't be owning any stock we couldn't be owning any stock yesterday so this state is uh yesterday so this state is uh uh uh is impossible is impossible same thing with the frozen state because same thing with the frozen state because in order for the frozen state to be in order for the frozen state to be possible possible uh then yesterday we must be selling but uh then yesterday we must be selling but there's no yesterday there's no yesterday after this right this is it literally after this right this is it literally the initial day the initial day so all right we have zero action x so so all right we have zero action x so moving on to day one moving on to day one uh is it possible to be an empty state uh is it possible to be an empty state well well uh if we want to be an empty state that uh if we want to be an empty state that must mean that we um must mean that we um uh uh uh we either uh we either were empty yesterday or were empty yesterday or uh we were in frozen yesterday so those uh we were in frozen yesterday so those are the two possible um are the two possible um possible possible scenarios and we actually want to scenarios and we actually want to you know you know draw these arrows now in this direction draw these arrows now in this direction because it's almost as if we're making a because it's almost as if we're making a decision and we're going to land at the decision and we're going to land at the state state although the decision was actually made although the decision was actually made yesterday yesterday now we reversed the problem now we reversed the problem uh we inverted the problem and now we uh we inverted the problem and now we want the arrow to kind of like um want the arrow to kind of like um now in the reverse direction as well so now in the reverse direction as well so these are the two possible uh uh these are the two possible uh uh scenarios scenarios uh and uh because this scenario is uh and uh because this scenario is impossible impossible so the only scenario possible is going so the only scenario possible is going from from empty from yesterday to empty today and empty from yesterday to empty today and so we're gonna assign again zero here so we're gonna assign again zero here and holding on day one well and holding on day one well um um there are two there are two options right again options right again uh uh if we were holding yesterday if we were holding yesterday like this arrow if we were holding like this arrow if we were holding yesterday then we today we can just stay yesterday then we today we can just stay rested and rested and keep holding but this is impossible keep holding but this is impossible right right we put an x here but another possibility we put an x here but another possibility is if we were is if we were empty empty yesterday and we actually bought yesterday and we actually bought something yesterday so this is the arrow something yesterday so this is the arrow and it's possible and we need a cash and it's possible and we need a cash value of one to buy that stock so value of one to buy that stock so right now right now our maximum onward reward is going to be our maximum onward reward is going to be uh minus one in this case uh minus one in this case is it possible to be frozen is it possible to be frozen well um well um the only way it's possible is if we've the only way it's possible is if we've sold something sold something um um yesterday but since yesterday but since uh on day zero we couldn't be holding uh on day zero we couldn't be holding there's nothing to sell so this is there's nothing to sell so this is basically impossible we're gonna put an basically impossible we're gonna put an x here x here all right day two all right day two day two uh empty state again it's day two uh empty state again it's possible uh there's two possibilities possible uh there's two possibilities one is like we keep keep um resting and one is like we keep keep um resting and uh uh by by holding nothing and this will give by by holding nothing and this will give us a us a continued value of zero or the other continued value of zero or the other possibility is if we've sold something possibility is if we've sold something on day one and that is uh infeasible so on day one and that is uh infeasible so we basically just have this one value we basically just have this one value here here for um for um the holding state the holding state is it possible well it is is it possible well it is we could either just keep holding and we could either just keep holding and then we just use the same value then we just use the same value uh same maximum uh same maximum um onward reward of minus one here or we um onward reward of minus one here or we could be could be uh buying something uh yesterday uh buying something uh yesterday uh and uh and that would give us a value of minus two that would give us a value of minus two because the price yesterday was minus because the price yesterday was minus two but then minus two is less than two but then minus two is less than minus one so we still take minus one minus one so we still take minus one here here what about this frozen state well what about this frozen state well uh if we want to be frozen on day two uh if we want to be frozen on day two then on day one we must be selling so then on day one we must be selling so that's the only possible way that this that's the only possible way that this can go can go and and what is the maximum what is the maximum reward onward well reward onward well um um you have to take you have to take uh uh um the stock as being like already sold um the stock as being like already sold and so and so the onward value is going to be one the onward value is going to be one because because uh there's a minus one net cash amount uh there's a minus one net cash amount but then because a selling action was uh but then because a selling action was uh performed on day one performed on day one uh so actually moving onward you're uh so actually moving onward you're going to have going to have a value of one here a value of one here so now let's move on to day three day so now let's move on to day three day three for empty there's again two three for empty there's again two possibilities possibilities one is just you know keep resting and uh one is just you know keep resting and uh we keep the value of zero we keep the value of zero or or uh we could be uh we could be uh we could be uh we could be uh coming from like a frozen state uh uh coming from like a frozen state uh yesterday and uh because frozen state is yesterday and uh because frozen state is not going to change anything in terms of not going to change anything in terms of cash amount so we actually would have cash amount so we actually would have one dollar cash instead of for empty as one dollar cash instead of for empty as the maximum onward reward so we'll take the maximum onward reward so we'll take one there for holding again there's two one there for holding again there's two possibilities one is that we continue to possibilities one is that we continue to hold hold on the other one is if we uh on the other one is if we uh bought something bought something is if we bought something on day two so is if we bought something on day two so if we continue to hold that's going to if we continue to hold that's going to give us a continued value of minus one give us a continued value of minus one for holding but if we bought something for holding but if we bought something on day two that would cost us three on day two that would cost us three dollars dollars and plus the existing character value of and plus the existing character value of zero that's going to be minus three it's zero that's going to be minus three it's gonna be less than minus one so we take gonna be less than minus one so we take minus one instead minus one instead for frozen state on day three there's for frozen state on day three there's only one possibility that is only one possibility that is uh we sold something on day uh we sold uh we sold something on day uh we sold something on on day two something on on day two because the price was good three dollars because the price was good three dollars uh with existing cache amount of minus uh with existing cache amount of minus one we will get a value of two here now one we will get a value of two here now let's move on to day four last day uh let's move on to day four last day uh again for empty there's uh one again for empty there's uh one possibility of just you know staying possibility of just you know staying with that with that uh mtm uh empty value uh mtm uh empty value on day three which is one on day three which is one or we could or we could be be selling on day three which was really a selling on day three which was really a bad choice because you would be like bad choice because you would be like uh uh basically giving your basically giving your giving your stock away giving your stock away but you know what um because but you know what um because this is a pretty high value even if we this is a pretty high value even if we just you know just you know sold our our our stock for free on day sold our our our stock for free on day three following this three following this uh we will still have like a value of uh we will still have like a value of two two so so it's not that bad but uh can we be it's not that bad but uh can we be holding on the last day yeah we could holding on the last day yeah we could and uh one possibility is that we just and uh one possibility is that we just continue to hold what we already had continue to hold what we already had uh with that one stock or we could be uh with that one stock or we could be you know you know selling something on day three selling something on day three which was which was uh uh which was pretty bad right like we were which was pretty bad right like we were selling on day three uh sorry buying ah i'm sorry buying but not sorry buying ah i'm sorry buying but not selling buying selling buying uh because now day three if we were uh because now day three if we were buying buying at a zero value we basically got a free at a zero value we basically got a free stock and we're gonna inherit that uh stock and we're gonna inherit that uh cash value of one so it's a pretty good cash value of one so it's a pretty good scenario here we have one stock and we scenario here we have one stock and we also have some cash and frozen uh also have some cash and frozen uh for for day four to be frozen we had to be day four to be frozen we had to be selling selling on um on day three right on um on day three right and that was and that was a pretty bad choice because a pretty bad choice because uh we gave that uh out for free well i uh we gave that uh out for free well i was wrong about you know this line here was wrong about you know this line here let me just redo this line so let me just redo this line so for um for this for this day four to be for um for this for this day four to be empty the second alternative empty the second alternative was to just stay idle was to just stay idle during a cool down on day three and we during a cool down on day three and we basically don't have any change in our basically don't have any change in our um um in our cash value so that's why this uh in our cash value so that's why this uh highest value here was two highest value here was two so i just corrected what i just said uh so i just corrected what i just said uh all right so we now have the full list all right so we now have the full list but is this everything well but is this everything well not really right because not really right because again again we need to on the last day we need to we need to on the last day we need to clear we need to clear our clear we need to clear our our value like we might still have some our value like we might still have some stock here right so we're going to do stock here right so we're going to do day 4 day 4 day 4 day 4 uh uh end of day end of day clearing right day for clearing clearing right day for clearing uh at the end of day we're gonna do that and let's take a look at the value here let's just use a link to represent that and this will be two because we we don't have any stock on day four uh but what about this holding option here because we still hold some stock we're gonna actually clear that on day on on day four at the end of the day so this will lead to three because we had a uh a plus two here right a plus two in this direction uh and uh what if we were frozen or if we were frozen then there's no change in the cash value because the only thing we can do is to you know rest it rest for the entire day so we're gonna have a value of minus one so this is now pretty obvious uh this is the better choice oh by the way we again forgot to add the uh arrow that uh that indicate the best action uh from any state onward so let's redo that again so um for the day zero of course uh there's no more further action uh so we didn't have to do anything like that but for this day one the optimal action is actually taking this one so we'll make this thicker right make the sticker by painting it with three pounds and then for this next state the best thing to do is to again by start buying some stock and then for this one since this is the only action possible we're gonna give it yeah a thick line arrow on day two the best value uh the best option the best control action or the best action is still like uh stay rested right and for this minus one here uh um it is when we uh inherit like we just keep we if we just keep um uh keep resting right and for this one here it is achieved by selling the stock we bought yesterday now uh on day three this one here is by following just you know resting on day two uh and then the for for the holding state on day three the value is achieved by you know keep resting and for frozen on day three this is the only action uh for for to empty on day four the best value was obtained by uh resting after the frozen state uh for holding state on day four this was achieved by uh by buying that free stock uh then for frozen state on day four the best action well it's the only action here so all right we just built our again you know optimal control action mapping some some call it the optimal control law basically it means the optimal action to take at any given state so indeed if you look up any state here it's going to have one um you know thickened arrow that indicates where to go next and in the way in a way we could just take a look at what's the maximum value at the beginning and then we're going to just follow these uh thick arrows to um to find our uh our optimal trajectory so that is how i'm going to do this um and we're again highlighting the uh optimal trajectory here um right and then this one will just outline and give it the thick outline uh next one will be this one here with the thick outline the next state is frozen uh so we're gonna highlight that with a thick outline the next state is um uh uh uh holding well we should say the previous state like the previous date state holding and then on day zero we should be empty because that's the only thing possible all right so this is the optimal trajectory and uh our dynamic programming solution as if we were doing it in the backward direction which was the standard direction that dp was first defined for all right so uh that's it guys let me just uh you know give you a summary of what we just went through we went through the problem formulation of this stock buy and sell with a cool down problem first with its uh state machine but it's a slightly modified state machine than the leak code answer because i think my definition is more intuitive we have an empty state which means that we don't hold any stock we also have a holding state which means that we're having a stock and we also have a frozen state that is basically a one-time state after uh we sell a stock and we're just going to sit in that state for a day and it's a state with no stock in our pocket and then um after the frozen date you know uh which we rest uh through the entire day then the next day we are empty again and we are able to buy or you know rest uh just or or idling uh also like when we were holding we were we we are still given the option to you know rest and you know keep uh in the holding state so this is the state machine uh and then next we moved on to formalizing this problem in a forward unconventional uh dynamic programming uh as a former as a forward dynamic programming problem and uh our intuition was basically that we want to build our maximum cash history from day zero and the value that we're assigning in each of these state circles uh represent the maximum possible cash each day before taking any action and then we just basically perform such uh calculations step by step onward until the end of the day and then of course uh on day fours because the special day it's the last day we will have another uh day four end of the day clearing where we we're gonna you know clear any um holding stock and change it into cash and then just compare the cash value at the end of day four and find our champion and work our way back to find the uh optimum uh choices and trajectory if we want to i mean if if the if all this is about is just to find a value and we don't need to you know uh look up those things anymore and then of course this is the most textbook correct dynamic programming way of formulating this problem and it would have to require a reversion uh an inversion of the time direction because you as you can see we're actually starting from day four and then you know ending at day zero uh that is unfortunately the case because because this is like finally this is the something that i would like to say to wrap up the theory part of this is that in the standard dynamic programming formulation which is the backward direction formulation your reward has to be a reward um uh uh in the type of onward reward in the future right um it cannot be like the rolling reward type which was like all the reward that you've accumulated so far in the past it has to be like the onward reward into the future right so this is like the the difference between the uh standard backward direction dynamic programming and our forward direction variant of the damage programming which is just an inversion of the problem in terms of the time direction everything else is the same as you can see here like you can just uh a mirror image these uh these you know graphs you know these dots and lines you'll get this right so there's nothing um uh inherently different it's just you know two different directions or ways or preference of representing the same problem uh and i offered like a casual uh kind of like uh metaphor you know to differentiate uh metaphor you know to differentiate between this forward direction between this forward direction perspective in this backward direction perspective in this backward direction perspective perspective so so uh i guess in my mind you know uh i guess in my mind you know um the standard backward direction uh um the standard backward direction uh calculation calculation uh is like uh is like calculating your salary uh calculating your salary uh in a works perspective right um because in a works perspective right um because then the reward is calculated like the then the reward is calculated like the uh the accumulated reward is calculated uh the accumulated reward is calculated like as an onward reward like as an onward reward so so you're gonna you're gonna start looking at you know start looking at you know uh for example if you're just working uh for example if you're just working you're gonna start looking you're gonna start looking uh at the day you retire like what's the uh at the day you retire like what's the maximum maximum uh level that you can achieve uh level that you can achieve uh on the day you retire maybe it's the uh on the day you retire maybe it's the company ceo company ceo uh or maybe you're just a technical uh or maybe you're just a technical tracker it's like a cto or uh you know tracker it's like a cto or uh you know tech lead or you know principal engineer tech lead or you know principal engineer something like that something like that then um you basically travel backwards then um you basically travel backwards uh in time like okay what's the year uh in time like okay what's the year before i retire what's the before i retire what's the second year third year before i retire second year third year before i retire all the way down to your current you all the way down to your current you know work year here know work year here and then you're gonna see okay and then you're gonna see okay how much money i can make how much money i can make at any year at any year on any year on any year in any like i guess job title job in any like i guess job title job position so this is like a work position so this is like a work perspective calculating your income perspective calculating your income you're going to be tackling the maximum you're going to be tackling the maximum reward onward from the current state and reward onward from the current state and time all the way to the day you retire time all the way to the day you retire right right um so there's like a cap of how much um so there's like a cap of how much money you can make money you can make uh just by looking at you know your uh just by looking at you know your current year uh and between your current current year uh and between your current year and then the year you you're going year and then the year you you're going to retire maybe it's going to be 30 to retire maybe it's going to be 30 years 20 years years 20 years 10 years you know depending on which 10 years you know depending on which what age you're at or you know what age you're at or you know how you project your retirement uh this how you project your retirement uh this is gonna be how you calculate how much is gonna be how you calculate how much money you're gonna you're gonna be money you're gonna you're gonna be making uh in total making uh in total uh from from today on to the day you uh from from today on to the day you retire right this is the work retire right this is the work perspective of uh perspective of uh dynamic programming and on the other dynamic programming and on the other hand if we calculate actually on the hand if we calculate actually on the problem in the forward direction problem in the forward direction you're going to be looking you're going to be looking at an investment problem at an investment problem because because because now the um the the reward is is because now the um the the reward is is different it's going to be like a different it's going to be like a rolling reward rolling reward it's going to be looking at all the it's going to be looking at all the money you have money you have right now or at any like position or right now or at any like position or role uh or you know your current role uh or you know your current portfolio portfolio and then you're gonna just move your way and then you're gonna just move your way forward and accumulate as much forward and accumulate as much uh this is called an arc reward uh as uh this is called an arc reward uh as much as you can along your way and then much as you can along your way and then you know you know uh uh and then you know until some certain and then you know until some certain time in the future you're gonna time in the future you're gonna calculate what's the maximum amount of calculate what's the maximum amount of money that i can make money that i can make from today on with this with the current from today on with this with the current asset uh uh until like asset uh uh until like uh maybe the day you want yourself to uh maybe the day you want yourself to retire so this is like the investment retire so this is like the investment perspective dp perspective dp uh they could be used to save to solve uh they could be used to save to solve the same problem but these perspectives the same problem but these perspectives are just different okay uh and that is are just different okay uh and that is how i how i kind of like can best explain this kind of like can best explain this and there it is guys um now the next and there it is guys um now the next thing i'm going to do is to actually thing i'm going to do is to actually implement implement uh one of these variants uh one of these variants i think i'm going to implement um i think i'm going to implement um let's say i think i'm going to implement on the forward uh variant right and then um and then see how it goes all right so now let's uh go back to our problem and apparently we don't have any submissions um and we're gonna just work on prototyping this now this is problem 309 and we want to build our dynamic programming um in the forward variant style right so what we do is uh in dynamic programming of course there's going to be like a i guess a for loop right further to to just basically walk you from day zero all the way to day four even you know day five or the uh the the end of day for day four so we're definitely gonna build a for loop here right four uh um for p in prices right um yeah paying prices so the the reason why i wanted to iterate the the content of the of the uh the list instead of you know the index of the list is because you know look up all the content by indexing the list it's gonna cost time um but i guess because we're doing recursive relationships it's better to actually use index so i'm going to stick with index now um so for indexing we need to first find what's the length of the prices array and then we're going to now use a range function to to represent that now it's going to be in range in so now each k is going to be an index on the prices list and what do we do well if you look at this um graph again what we're doing is that on each day you know look at this recursive relationship uh on each day we're going gonna be calculating the uh the arc reward uh towards any possible future state as well as the uh the rolling reward in the past that we have so far right so we probably want to define the initial rolling values of our of our three different states right so let's just define that as well in here uh let's say our state zero for um for our state uh in empty uh one for our holding state and two for our freezing frozen state right so um and do we need like a table to re to remember everything right this is like important because we only need like a memory of one previous uh one previous uh days like um uh one previous days uh maximum rolling reward uh in order to move forward so we don't need to remember you know the entire history we just need to remember yesterday's history okay um right actually now let's start something like here this was our previous uh idea and it was not so good uh now our so problem 309 uh with a forward dp variant uh solution the first thing i'm going to write down is that uh we do not need to remember all uh um right um like max rewards uh for all history omr max reward for all history we just need the most recent history yeah just literally yesterday right like i yesterday that is ie that is yesterday um and what is mr is a maximum let's add a rolling there rolling let's add a rolling there rolling maximum reward let's call it rmr rolling maximum reward for our history we just need the most recent history from yesterday so this will make this will this makes the space a pleasant what a pleasant um a pleasant what a pleasant um of one of one yeah so that's what we're gonna do um so for our empty so let's yeah what is um um rmr right like rmr is um uh rolling maximum reward rmr is gonna be a list right rmr is gonna be a list right um with three elements um with three elements and it'll be and it'll be let's see what should be that should be let's see what should be that should be zero zero impossible impossible so let's make it impossible impossible so let's make it zero zero none none is it possible none none is it possible um yeah maybe it's possible let me let me just uh make it that way zero none none right moving on right moving on um moving on right moving on um for k in range n for k in range n we're going to start on um k equal to we're going to start on um k equal to zero zero which should we already kind of like which should we already kind of like calculate it right calculate it right uh uh yeah so let's actually start from k in yeah so let's actually start from k in range of one one n range of one one n so we're gonna start on the second so we're gonna start on the second element and what we're going to do is element and what we're going to do is that we're going to apply now these that we're going to apply now these iterative conditions iterative conditions of this of this right right we're going to see we're going to see how many things we need to compare for how many things we need to compare for the maximum the maximum well for for um for rmr1 rmr0 which is the um uh you know uh the yeah which is the the reward the the maximum reward like the maximum cash history rolling maximum rolling maximum reward while this is a little bit uh reward while this is a little bit uh hard to hard to say it and you know say it and you know in one second rolling maximum reward in one second rolling maximum reward okay or rmr yeah okay or rmr yeah let's just call it reward okay let's just call it reward okay um reward um reward so the reward on on on day one is going so the reward on on on day one is going to be to be uh um uh um it's going to be r1 it's going to be r1 so it's going to be r1 so it's going to be r1 let's just call it r you know let's just call it r you know uh our one uh our zero right our zero uh our one uh our zero right our zero we're just updating it uh now this one we're just updating it uh now this one is is what there's two ways to uh uh uh yeah there's two ways to try to calculate it first is to use the value of from the previous actually we should use our new right actually we should use our new right yeah this is a better way yeah this is a better way um um our new zero because you know we don't our new zero because you know we don't want to end up modifying things want to end up modifying things um from from yesterday from history um from from yesterday from history now our new zero is equal to now our new zero is equal to the maximum the maximum between two things um the first thing between two things um the first thing is um continue to is um continue to rest so it's going to be rest so it's going to be the same r value from yesterday the same r value from yesterday uh our new r0 right r0 and the other one uh our new r0 right r0 and the other one is um is um i guess i guess uh uh the previous value of the frozen state the previous value of the frozen state yes uh yesterday's frozen value uh yeah yes uh yesterday's frozen value uh yeah yesterday's value yesterday's frozen yesterday's value yesterday's frozen state value yeah yesterday's frozen state value yeah yesterday's frozen state value plus zero state value plus zero so yesterday's frozen state value so yesterday's frozen state value uh so that would be r2 yep uh so that would be r2 yep right that's it and uh right that's it and uh um um how about the next one the value for the how about the next one the value for the holding state holding state well for the holding state um we could there are again two different ways one is we take uh the reward value of yesterday's empty state value right and then we're going to minus the price of the stock yesterday right so max between r0 minus the price of uh of yesterday so price k minus one uh or we could continue to hold from a previous hold so we're gonna take uh the previous hold value uh yep yep yep uh and yep yep yep uh and the uh our new three our new two you know what let me just uh somehow initialize the our new uh with something okay so that at least it'll have a memory there now r2 equals the max between well actually r2 there's only one way to achieve a frozen state that is you know take the holding state value from yesterday and plus the sale value of uh the stock price so we're going to do there's no max edges are from yesterday's um hold value and plus the the price yesterday k minus one um i would say we don't want to look up um i would say we don't want to look up the list twice so the list twice so i would rather just you know i would rather just you know price price equals to this equals to this uh price yesterday right price yesterday i'm gonna just do that and then just gonna do that yeah price yesterday price yesterday right so now we updated uh this what are you gonna do are you gonna say update r yeah so r becomes the uh our new uh our yeah our new becomes the art but looking at it um do you think we really need like two [Music] lists are in our new to rotate this stuff well the the new first element relied on the first and the third element right the new second element relied on the zeros and the first element the new second element relied on the first element so i guess what we can do to avoid doing that is to perform this first because at this point r1 hasn't been modified yet uh wait but then r2 would have been wait but then r2 would have been modified already modified already we can't afford that so this r2 has to we can't afford that so this r2 has to be before that be before that but then our zero is modified so we had but then our zero is modified so we had to to put this before that put this before that now r1 now r1 relies on r0 which is not modified yet relies on r0 which is not modified yet which is great which is great uh and price yesterday r1 yeah you can't do that because this one relies on r1 okay anyway i give up i think i'll just keep two arrays of um r and r our new r and r new and we're gonna just you know do an update like that all right so i think this is all this is everything really uh and then after this for loop we'll be looking at you know the the values on the last day uh and then we're just gonna do a clearing at once you know clear all remaining clear you know uh um clear the uh uh holding stock value on last day right so of course we're gonna have like uh at the end of the day we're gonna have like an r array and then the day r becomes our new so it's the same thing uh so we're gonna just make our uh one right we're gonna choose r as the the array to work on is equal to r1 um plus the uh the price value of of you know just uh the last day right yeah minus one is gonna be just just yeah clear it at the last value there and then we're gonna have an r array basically it's gonna be like three different things uh we're gonna return return what max of uh of r right i think that's it um i think that's uh basically it let's see if it works okay um right run it well there's something uh right i had i had thought about this so you cannot initialize them as none basically but so then what should i initialize them as if they cannot be not basically we want these values to be never uh like selected if you want them to be never selected you have to make them like very negative right because we're maximizing so if you make these x values like very negative you'll make sure that they will never be selected so what is the um yeah negative value you can get there so the the highest price you can get is like a thousand so if we initialize these as like minus ten thousand will be probably pretty sure that they will never be selected right just as an overkill it's an overkill but uh let's see well ah this is again wrong we are expecting three right are we let's see one two three oh two we're expecting three one two three oh three one two three oh two we're expecting three right we're expecting three uh but somehow we got a answer of uh of four so how is that happening um let's just you know hand calculate this a little bit okay we take this array want you know actually let's just uh try it one two three we're all here we're already here so we can um basically inspect the progression of the the r array at each step right we can we can do that and we can basically debug uh using that so now let's put our debugger on uh now we you know at the end of which uh at the end of each for loop we're gonna just look at you know the r value right right so we're gonna do this oops this yeah we're here already good all right we're at this um k equal to one right so k equal to one uh what shall we expect um so day one we should expect it to be zero minus one and a very negative value there zero minus one and a very negative value there so let's see zero minus one and a very negative value zero minus one and a very negative value that's correct that's correct so let's uh just stop again now k equal so let's uh just stop again now k equal to two to two we expect to see we expect to see again zero zero minus one one again zero zero minus one one zero minus one zero minus one one that's correct one that's correct and let's step again and we expect to and let's step again and we expect to see see one one minus one two minus one two um um one minus one two that's correct so one minus one two that's correct so let's uh move one step forward let's uh move one step forward we should be expecting we should be expecting two one minus one two one minus one and we have two and we have two two two two two okay okay that's where it went wrong it shouldn't that's where it went wrong it shouldn't be two two two be two two two it should be so it should be so things went wrong when when k equal to y things went wrong when when k equal to y k equal to four k equal to four right right so why would it go wrong when k equal to so why would it go wrong when k equal to four let's see when k equal to four four let's see when k equal to four we're just basically going to calculate we're just basically going to calculate price yesterday right price yesterday price yesterday right price yesterday was zero which uh makes sense price was zero which uh makes sense price yesterday was zero yesterday was zero and then for the um and then for the um for the um yeah for the for the um yeah for the empty value it's gonna take the maximum empty value it's gonna take the maximum between between 1 and 1 and the frozen value from yesterday the frozen value from yesterday so if we just take a look at r you know that's basically yesterday's list wait wait hold on why is uh we shouldn't have updated r yet okay let's uh okay let's uh let's do this again okay let's do this again okay we now know where to look at all right let's put on the debugger again and we're going to stop on this line here here well i guess we have to restart the to make the debugger working again to make the debugger working again right we put our right right you know the fact that our new and r are you know the fact that our new and r are like basically like basically synced instantly before i update them synced instantly before i update them that's that's that's scary that tells me something that's scary that tells me something maybe is wrong about you know the memory maybe is wrong about you know the memory location location let me just uh move forward now let me just uh move forward now r r is is zero zero and then two and then two minus crazy values minus crazy values okay so they are actually different okay okay so they are actually different okay that's that's actually good news that's that's actually good news so when k equal to so when k equal to when k equal to one when k equal to one we're basically seeing like r and r nu we're basically seeing like r and r nu so r represents um so r represents um the initial thing like zero the initial thing like zero minus minus right minus minus right and r represents uh the actual and r represents uh the actual calculated value for day one which is calculated value for day one which is zero minus one zero minus one minus a lot minus a lot um um right so right so zero minus one minus a lot which is zero minus one minus a lot which is correct so correct so the next step is where you know our r the next step is where you know our r becomes zero minus one one the r here should be it should always the r here should be it should always like um i mean why i mean r after the update r should be what our new was previously right so when k equals to uh now k equals to 2 we shall see that you know is going to be whatever was before so 0 is going to be whatever was before so 0 minus 1 like minus 9 minus 1 like minus 9 99 99 minus minus 9999 but 9999 but here we're seeing that uh here we're seeing that uh our r is zero minus one one but why is our r is zero minus one one but why is that this is quite strange you know like i didn't tell update at all update at all oh oh maybe this is not the right way to maybe this is not the right way to assign or to update the rs assign or to update the rs i mean i mean that's the only thing that i can think that's the only thing that i can think of that could be wrong right like this of that could be wrong right like this is not how you update r is not how you update r if we do if we do r r and then our new this maybe is how you and then our new this maybe is how you assign it right so let's just uh assign it right so let's just uh make it make an example if so for make it make an example if so for example if p is equal to example if p is equal to one two three one two three and then p and then p new is equal to uh you know four five new is equal to uh you know four five six six and if you want to update p with p new and if you want to update p with p new just by saying p equals to p new just by saying p equals to p new let's see what p is let's see what p is four five six okay hey it does work but four five six okay hey it does work but what if we say what if we say p this equals to p nu of this it's the now hey actually now it works now hey actually now it works so i mean so i mean this line did have some magic this line did have some magic i don't know why but uh i don't know why but uh no it actually works no it actually works which is crazy you know um i guess i which is crazy you know um i guess i need some python memory and list need some python memory and list assignment knowledge assignment knowledge uh uh to to see what you know to to see what you know yeah let's just look it up don't yeah let's just look it up don't python um python um assign assign a assigned list a assigned list to another to another list outside in one list to another how list outside in one list to another how do you do it uh list one list two oh so you see this is like maybe when you change list two this one has right this is like shallow copy or right this is like shallow copy or something oh right right okay okay okay okay to make a copy right okay so i guess i was right so so this is actually now a a deep a deep copy okay this is a deep copy um whereas r equal to r nu so what what are these things well if so what what are these things well if you don't know you don't know i previously had looked up you know the i previously had looked up you know the difference between deep copy and shallow difference between deep copy and shallow copy on another occasion copy on another occasion so basically a deep copy is a copy of so basically a deep copy is a copy of the content of the variable the content of the variable whereas the shallow copies just copying whereas the shallow copies just copying the address the address of of another variable so if you just of of another variable so if you just copy the address copy the address um um um it's like um it's like it's like okay it's like okay uh uh okay um how should i say this if uh uh okay um how should i say this if you just copy the address let's say your you just copy the address let's say your parents live in florida okay parents live in florida okay uh and uh when when you you know uh and uh when when you you know uh register for your amazon account and uh register for your amazon account and you just you know you just you know copy your parents address and put it as copy your parents address and put it as your shipping address your shipping address then then then whatever you order is going to be then whatever you order is going to be shipped to your parents house right shipped to your parents house right that's what i mean by saying copy that's what i mean by saying copy but if you actually you know but if you actually you know instead of copy their address but copy instead of copy their address but copy the entire thing and place it in another the entire thing and place it in another place that's like okay place that's like okay you basically you basically buy another house but exact the same buy another house but exact the same size and look of your parents house size and look of your parents house and this house is now in where michigan and this house is now in where michigan okay now in michigan and this is your okay now in michigan and this is your house although you know everything in house although you know everything in the house is the same this is a deep the house is the same this is a deep copy of the house instead of just the copy of the house instead of just the house address house address then you put this michigan address into then you put this michigan address into your amazon account then you can your amazon account then you can actually receive your amazon packages in actually receive your amazon packages in your very own your very own michigan house which is exact which look michigan house which is exact which look exactly the same as your parents house exactly the same as your parents house but it's on a different address does but it's on a different address does that make sense that make sense all right so in this case we actually all right so in this case we actually need need um um we actually need a new copy of we actually need a new copy of of r right because because yeah so actually um because r is the one that we will be returning in the end we want this to uh always update so our new is like our our temp our temp our template temporary temporary variable right wait actually i just want to keep you wait actually i just want to keep you know these two values at two different know these two values at two different locations locations um we don't want to point to yeah we don't want to point we we may not want to create a different address for r as well we just want r to use the same address but when we were updating r we just want to use the content of uh of our new yeah that's that's all i think that's uh that's how you do it and uh right that's right to the to the to the you know to the solution here to the you know to the solution here and see if it works right it's uh working for the first one what about the uh yep that works too so let's submit it accept it there we go all right so above average performance let's uh submit it a few times a couple of times still above average okay good another one still about marriage so all right we are confirmed that this is an above average uh solution and it's actually the dynamic programming solution so uh yeah this is uh working pretty well and we just implemented this dp in the forward direction uh we could have implemented in the backward direction as well um so but i mean it's not necessary you can you can do this um you can do this on your own uh because because it's just gonna you know flip the um recursive uh relations and now you're working on the onward reward in the future instead of the rolling reward in the past and you're gonna build your for loop from the last index uh which is now you know the first index anyway because you flipped your problem right um and then you know to the first index which is uh in reality the last day in the stock market so anyway uh this is our today's submission um so what we did let me give you a summary is that you know we um i learned from this uh solution of dynamic programming uh um with state machine kind of offline trying to digest what's going on in here uh and you know the names and the diagrams in here was a little bit you know confusing to me so i had to kind of like create my own graphics to figure out what's going on so i used my own i guess duplicate um my own kind of like remake of that solution and then this is my solution uh both in forward direction and backward direction but we implemented the forward direction code and also i made a comparison between what is the the classical dp recursive um equation in the backward um fashion compared to what we have been using uh in this particular problem using a forward direction variant uh there although they're all the same uh you know doing it in forward or do it in the backward or forward just requires you to inverse invert the uh the direction of your time or your progress and then just reformulate the problem with the uh inverted um uh time and uh i made an analogy saying that okay the backward direction dp is like calculating uh your work salary towards you know the day you retire whereas uh the forward direction dp is looking at you know the rolling reward in the past up till now that you've made so far uh and then looking forward to see how much more you can gain so that you never know how much you how what's the maximum amount of money you can make until you actually uh uh uh recursively moved to the last day where uh where you work uh whereas in the backward direction you kind of like know immediately what's the you know the the maximum you can achieve by starting from the last day you work and then you're just going to calculate backwards and then find out realistically um how much you can make from where you are at the status you are on the day right today so uh that's it that's it guys that's the summary hope you liked my graphics and my explanation and i will see you in our next video | 2024-03-24 10:11:23 | 309 | 1 Leetcode 1 Day 309 Best time to buy and sell stock with cooldown (Part 2 of 2) |
|
UmudS7EXz6o | [Music] hey guys welcome back to another video hey guys welcome back to another video and today we're going to be solving the and today we're going to be solving the lead code question linked cycle 2. lead code question linked cycle 2. sorry linked list cycle 2. all right so sorry linked list cycle 2. all right so in this question we're going to be given in this question we're going to be given a linked list and we want to return the a linked list and we want to return the node where the cycle begins node where the cycle begins and if there is no cycle we're going to and if there is no cycle we're going to end up returning no end up returning no so there is a cycle in a linked list if so there is a cycle in a linked list if there is some node there is some node in the list which can be reached by in the list which can be reached by continuously following the next pointer continuously following the next pointer internally a pos is used to denote the internally a pos is used to denote the index index of the node the entails next pointer is of the node the entails next pointer is connected to connected to note that pos is not passed as one of note that pos is not passed as one of the parameters the parameters and notice that you should not modify and notice that you should not modify the linked list and we want to do this the linked list and we want to do this in constant memory in constant memory all right so uh this is one of those all right so uh this is one of those questions where i feel like if you don't questions where i feel like if you don't know the algorithm know the algorithm which is in play uh for solving this which is in play uh for solving this question you won't really be able to question you won't really be able to uh solve it so the algorithm that we are uh solve it so the algorithm that we are going to be using is called the floyd's going to be using is called the floyd's algorithm algorithm and it's a really simple and a kind of and it's a really simple and a kind of intuitive algorithm so let's take a intuitive algorithm so let's take a quick look at quick look at how that looks like so let's start off how that looks like so let's start off by building our linked list by building our linked list so this linked list that we're going to so this linked list that we're going to have is just going to be numbers so we have is just going to be numbers so we have one have one pointing to two let's point that to pointing to two let's point that to three three and then four and then five six okay so and then four and then five six okay so that's enough that's enough so now let's look at a condition where so now let's look at a condition where this linked list is the end of it okay this linked list is the end of it okay so after seven over here seven is going so after seven over here seven is going to to point to none so when this happens there point to none so when this happens there is a certain stop point is a certain stop point so we go to one two three four five six so we go to one two three four five six and once we reach to seven the next and once we reach to seven the next uh value is not so that means that the uh value is not so that means that the linked list has a definitive linked list has a definitive stopping point so in this case we're stopping point so in this case we're going to return null for the question going to return null for the question but if this was a cycle what would but if this was a cycle what would happen is happen is this value over here might end up this value over here might end up pointing to pointing to some other value so let's say the seven some other value so let's say the seven instead of pointing to null instead of pointing to null is actually going to end up pointing to is actually going to end up pointing to the number let's say three okay the number let's say three okay so seven is going to now have a pointer so seven is going to now have a pointer going from seven all the way to three going from seven all the way to three so basically in this case what's so basically in this case what's happening is we're doing one two happening is we're doing one two three four five six seven and then from three four five six seven and then from seven we go to three again seven we go to three again then four five six seven and three and then four five six seven and three and there's the there's the infinite cycle that keeps going on and infinite cycle that keeps going on and on now the question is on now the question is how exactly do we identify such a cycle how exactly do we identify such a cycle so let's take a quick look at that so let's take a quick look at that all right so over here we're going to be all right so over here we're going to be having two pointers okay having two pointers okay and uh this method i think you might and uh this method i think you might also be knowing it as a rabbit in the also be knowing it as a rabbit in the tortoise method tortoise method so you have two pointers one of them is so you have two pointers one of them is going to be the slow pointer going to be the slow pointer and we're going gonna also have one more and we're going gonna also have one more called the fast pointer called the fast pointer so i'll denote slow with s and fast with so i'll denote slow with s and fast with f f okay now both of these pointers over okay now both of these pointers over here are gonna start off here are gonna start off at the head node and the head node is at the head node and the head node is nothing else but the very starting node nothing else but the very starting node so in this case it's going to be one so so in this case it's going to be one so s s and f both start off at one now why is and f both start off at one now why is one called slow and why is one call fast one called slow and why is one call fast now the reason one is called fast is now the reason one is called fast is because the fast pointer because the fast pointer for every one step that the slow pointer for every one step that the slow pointer takes takes the fast pointer is going to take two the fast pointer is going to take two steps steps so let's see what happens so in this so let's see what happens so in this case let's go into the next iteration case let's go into the next iteration so the slow pointer is now going to take so the slow pointer is now going to take one step so now our slow pointer is one step so now our slow pointer is going to be over here going to be over here so now that the slow pointer took one so now that the slow pointer took one step the fast pointer step the fast pointer is going to take two steps so we take is going to take two steps so we take one one and then we do two and now our fast and then we do two and now our fast pointer is going to be pointer is going to be at three okay so just to make it easy to at three okay so just to make it easy to understand let's remove the old values understand let's remove the old values so let's just keep continuing this so let's just keep continuing this pattern and if we have a cycle what is pattern and if we have a cycle what is going to end up happening is that going to end up happening is that the fast pointer and the slow pointer the fast pointer and the slow pointer are going to end up meeting are going to end up meeting at some point so i'll just go through at some point so i'll just go through this step by step real quickly and you this step by step real quickly and you should see how this happens should see how this happens so now the slow pointer is going to be so now the slow pointer is going to be over here and the fast pointer is going over here and the fast pointer is going to be one to be one two so now it's at five so now let's two so now it's at five so now let's look at the next iteration so i'll just look at the next iteration so i'll just go to the color green so over here the go to the color green so over here the next pointer so slow would be over here next pointer so slow would be over here and fast would go one two and now it's and fast would go one two and now it's going to be over here going to be over here right so now i'll just change the color right so now i'll just change the color again and now the slow pointer moves again and now the slow pointer moves over by one so this little pointer is over by one so this little pointer is over here over here now the fast pointer is going to move now the fast pointer is going to move over by two but now you gotta notice over by two but now you gotta notice that that since it's a cycle it does not end but since it's a cycle it does not end but what will happen it goes to three what will happen it goes to three and now it goes to four so now the fast and now it goes to four so now the fast pointer is right over here pointer is right over here so let's erase it so it's more clear so so let's erase it so it's more clear so this is where we ended off with so the this is where we ended off with so the fast pointer came to the value four here fast pointer came to the value four here and the low pointer is over here so now and the low pointer is over here so now let's go to the next iteration so slow let's go to the next iteration so slow pointer moves by one pointer moves by one and now the fast pointer is going to and now the fast pointer is going to move by two so one two move by two so one two and now it's going to be here so one and now it's going to be here so one thing that you want to notice what thing that you want to notice what happened is the slow and fast pointer happened is the slow and fast pointer ended up meeting at a point now when ended up meeting at a point now when they they both end up meeting at a certain point both end up meeting at a certain point what that's telling us what that's telling us is that we have a cycle and if we did is that we have a cycle and if we did not not end up at the same node at any point end up at the same node at any point that means we do not have a cycle that means we do not have a cycle so since fast and slow are both at the so since fast and slow are both at the value six currently at the same node value six currently at the same node that means that we do have a cycle okay that means that we do have a cycle okay so that is part one of the question so that is part one of the question we have a cycle and let's say just for we have a cycle and let's say just for quick uh comparison so let's say quick uh comparison so let's say seven actually ended up pointing to none seven actually ended up pointing to none so in that case what's gonna happen so in that case what's gonna happen is once the fast pointer reaches seven is once the fast pointer reaches seven it won't have anywhere to go and it will it won't have anywhere to go and it will obviously never obviously never reach the slow pointer so in that case reach the slow pointer so in that case we're directly just gonna return none we're directly just gonna return none since we will not have a cycle if that since we will not have a cycle if that was to was to if that was what was about to happen so if that was what was about to happen so this over here is step this over here is step one and we got that done okay but now one and we got that done okay but now the question is the question is how do we know where the cycle starts at how do we know where the cycle starts at so to find out let's just look at this so to find out let's just look at this as it is so the cycle starts as it is so the cycle starts at the number three over here right and at the number three over here right and the reason we know that is because seven the reason we know that is because seven points all the way back to three and the points all the way back to three and the cycle always starts at the value three cycle always starts at the value three so three is going to be considered as so three is going to be considered as our starting point our starting point and we want to understand how can we and we want to understand how can we actually come up or actually come up or reach to that value so to do that what reach to that value so to do that what we need to do is we want to store the we need to do is we want to store the value of value of our fast pointer so the fast pointer our fast pointer so the fast pointer here we still want to keep that in mind here we still want to keep that in mind but we can get rid of the slow pointer but we can get rid of the slow pointer okay so let's remove this and again okay so let's remove this and again the fast pointer like i said is going to the fast pointer like i said is going to stay in the same place stay in the same place so the fast pointer ends up staying over so the fast pointer ends up staying over here now what we're going to do is we're here now what we're going to do is we're going to have another pointer going to have another pointer and this another pointer is going to and this another pointer is going to start off at the head node start off at the head node okay so let's call this pointer slow okay so let's call this pointer slow again just for the sake of again just for the sake of just to make it easy so now this pointer just to make it easy so now this pointer over here over here it's a new pointer and it starts off at it's a new pointer and it starts off at the head node so we're starting it at the head node so we're starting it at the head node over here the head node over here and the fast pointer we get its value and the fast pointer we get its value from the previous iteration that we did from the previous iteration that we did so now that we have these values what so now that we have these values what we're going to do each time we're going to do each time both of these values just ignore their both of these values just ignore their names of slow and fast names of slow and fast because that doesn't matter in this case because that doesn't matter in this case right now each iteration they're both right now each iteration they're both going to move going to move one step so in this case the slow one step so in this case the slow pointer is going to move one step pointer is going to move one step so now it's going to be over here uh so now it's going to be over here uh simultaneously the fast pointer is going simultaneously the fast pointer is going to move one step to move one step and it's going to end up over here so so and it's going to end up over here so so far nothing happened but now let's go far nothing happened but now let's go over it again so now the slow pointer is over it again so now the slow pointer is going to move one more step so now this going to move one more step so now this little pointer is over here little pointer is over here and now similarly for the fast pointer and now similarly for the fast pointer it's also going to move one step it's also going to move one step and the fast pointer the seven points to and the fast pointer the seven points to three so it's going to go all the way three so it's going to go all the way back to the three so now what you want back to the three so now what you want to notice is that they're both to notice is that they're both now again at the same point and this now again at the same point and this time time whatever point that they are currently whatever point that they are currently on actually represents on actually represents what the starting value is in other what the starting value is in other words i'm representing sorry words i'm representing sorry i'm talking about this point over here i'm talking about this point over here and that makes sense so the three and that makes sense so the three is the starting point of our cycle so is the starting point of our cycle so once this once this happens in our second iteration that happens in our second iteration that means that we have found means that we have found the starting point so again real quickly the starting point so again real quickly we're first finding the cycle using the we're first finding the cycle using the slow and fast pointers slow and fast pointers and if there is not a cycle we return and if there is not a cycle we return null but if there is a cycle null but if there is a cycle we're going to store the previous fast we're going to store the previous fast value that we had value that we had we're going gonna go on to the next part we're going gonna go on to the next part which is finding the starting point which is finding the starting point and over there the fast pointer and the and over there the fast pointer and the new pointer which starts off at the head new pointer which starts off at the head both move by one iteration until they both move by one iteration until they reach reach a common point and the common point a common point and the common point which they reach is going to be which they reach is going to be the starting of the cycle which in this the starting of the cycle which in this case is the value 3 case is the value 3 and that's what we end up returning all and that's what we end up returning all right so hopefully all that did make right so hopefully all that did make sense and sense and let's just code it it should be pretty let's just code it it should be pretty simple once you understand how this simple once you understand how this algorithm over here algorithm over here works all right so real quickly let's works all right so real quickly let's start off by start off by doing the first thing which is finding doing the first thing which is finding our cycle and before we do that we want our cycle and before we do that we want to to define our variables so we have a slow define our variables so we have a slow pointer and we also have a fast pointer pointer and we also have a fast pointer now the slow pointer and the fast now the slow pointer and the fast pointer both start off at the head node pointer both start off at the head node and again real quickly the headnote and again real quickly the headnote starts is given to us starts is given to us in our function okay so now that we have in our function okay so now that we have this over here what we're going to do this over here what we're going to do is we're going to go inside of a while is we're going to go inside of a while loop and we're going to stay in this loop and we're going to stay in this while loop until while loop until fast has some sort of value in other fast has some sort of value in other words we're going to stay until a fast words we're going to stay until a fast is not is not equal to none and we're also going to equal to none and we're also going to check if fast dot check if fast dot next for the next value is not equal to next for the next value is not equal to none none so if both of those values exist what so if both of those values exist what we're going to do is we're going to end we're going to do is we're going to end up going inside of our up going inside of our while loop now inside of our while loop while loop now inside of our while loop the slow pointer over here the slow pointer over here is going to move by one iteration so is going to move by one iteration so slow is now going to be equal to slow slow is now going to be equal to slow dot next dot next and simultaneously the fast pointer and simultaneously the fast pointer instead of moving by one iteration is instead of moving by one iteration is going to move by going to move by two steps so fast dot next and then one two steps so fast dot next and then one more time more time dot next dot next since it's moving two dot next dot next since it's moving two steps steps now over here what we're going to be now over here what we're going to be checking for is we're going to check checking for is we're going to check if the slow pointer and the fast pointer if the slow pointer and the fast pointer ever end up colliding ever end up colliding at a certain point and if they do end up at a certain point and if they do end up colliding we can directly stop it over colliding we can directly stop it over there there and we're going to break out and at this and we're going to break out and at this point what's going to happen is we're point what's going to happen is we're going to store this value going to store this value of the fast value right so the current of the fast value right so the current pointer where the fast value pointer where the fast value is is going to be stored and we can use is is going to be stored and we can use that for the next part that for the next part so in this case uh if we end up breaking so in this case uh if we end up breaking out over there out over there that means that we do have a cycle but that means that we do have a cycle but what if we don't have one and in that what if we don't have one and in that case we're just going to do an case we're just going to do an else statement and in that case we can else statement and in that case we can just directly return none just directly return none since we do not have a cycle and that since we do not have a cycle and that means we're not going to have a starting means we're not going to have a starting point for a cycle point for a cycle okay so now we have we know we have a okay so now we have we know we have a cycle and now in this step what we're cycle and now in this step what we're going to do going to do is we're going to identify the starting is we're going to identify the starting point and to do that it's the same step point and to do that it's the same step so instead what we're going to be doing so instead what we're going to be doing is i'll be directly referring to the is i'll be directly referring to the head head but just to make it simple let's just but just to make it simple let's just come up with a new pointer so let's just come up with a new pointer so let's just call it pointer call it pointer and this new pointer over here is going and this new pointer over here is going to start off at the head okay to start off at the head okay and what we're going to be checking for and what we're going to be checking for is we're going to go inside of our while is we're going to go inside of our while loop as long as the pointer loop as long as the pointer is not equal to the fast pointer over is not equal to the fast pointer over here here and while that's happening our pointer and while that's happening our pointer is going to move by one enter one step is going to move by one enter one step so pointer is equal to pointer dot next so pointer is equal to pointer dot next and simultaneously and simultaneously the fast value is also going to move by the fast value is also going to move by one pointer one pointer so fast is equal to fast dot next and so fast is equal to fast dot next and we're gonna keep going into the we're gonna keep going into the into this while loop until we reach a into this while loop until we reach a point where pointer point where pointer is equal to fast and when we reach that is equal to fast and when we reach that point all we're going to do point all we're going to do is we're going to end up returning our is we're going to end up returning our pointer pointer and that should be it for our solution and that should be it for our solution so so let's just submit this and let's see let's just submit this and let's see what happens and as you can see our submission did get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thanks for watching | 2024-03-21 12:36:54 | 142 | Linked List Cycle II | Leet code 142 | Theory explained + Python code |
|
tWrvQyf3u0Y | so here we are given within data stream input of non-negative integer A1 to n input of non-negative integer A1 to n and we have to summarize the number seen and we have to summarize the number seen so far as a list of design intervals so so far as a list of design intervals so I have made a small presentation I have made a small presentation regarding the question and explaining regarding the question and explaining the example which has been given in the the example which has been given in the question and then I will explain my question and then I will explain my Approach and then we will code this Approach and then we will code this question question and then after I will explain my code and then after I will explain my code and let's try to submit the question in and let's try to submit the question in Java and C plus plus right so the question name is data stream as design intervals right so here we are given three functions to implement first of them is summary ranges which is the name of class and the Constructor itself so we have to initialize our container which we will use to uh find the diskline intervals right and the next next function is add number which will add that number into our container and into our stream which has been holding our value right and another another function that we have to implement is get intervals which will return the set of design intervals which are formed from the numbers in so far like what is this one set interval so design set interval is being formed from the non-never intervals right suppose if I have a number five six seven eight so these are contiguous stream and a interval from them is 5 to 8. right and if I have a stream of number 5678 and 11 then my intervals and then design interval will be 5 to 8 and 11. right so let's look into the example which has been given in the question so in the question we are given with this query summary ranges so in summary range I will initialize this container which is the data structure which will we will use that will return the interval at the time and add the value into it next where is adding number so I I have to add number one so this one is being added here then next word is get interval so only one is present in our data structure so I will return one comma one as the design interval up to down then I am adding 3 here so 3 will be added in our data structure right so ah next query is create interval so up to now 1 and 3 are only added in our data data sector therefore 1 comma 3 and 3 comma 3 are only interval that has been possible for that right so next query is adding number so I have added 7 here right so next next query is get interval so from these three numbers one three and seven I I can't make any uh defined intervals so like the design rechargeable for from this is one comma 1 3 comma three and similar Commission so next uh next query is little bit interesting we are here we are given with an add number and the value which we are given is 2 right so this 2 will will make this one two three as contact version right so then our interval will uh become 1 comma 3 and 7 comma same seven right and in the data structure if we we can see that if I can sort this data structure at the moment what we can do is I can form intervals easily so I can use a set here which will help me by sorting the number and storing the non unique storing the unique values like uh okay so next query is adding number which is six so six and seven becomes a disjoint interval so 6 comma 7 will come the next interval next interval in our set of intervals so whenever we get get intervals like the next query is get interval so I will return one comma 3 and 6 comma 7. so for this question what I supposed to what I uh intended to use is set like in the set what we can do is we will insert the data directly and set ensure that the value in the set should be sorted and non-unit suppose if we have a 3 here right so this 3 and 3 will be uh again pushed into the stream and there that doesn't help us in calculating any interval because 3 is initially taken into the consideration so having a unique value our in our data structure is important so we will use set here so uh so in my code instead of using a simple so in my code instead of using a simple headset what I have used here is tree headset what I have used here is tree set so I have initialized myself into set so I have initialized myself into the summary ranges Constructor so after the summary ranges Constructor so after that I have added the value whenever I that I have added the value whenever I get any value into my Adam so in the get any value into my Adam so in the gate interval part why what I am doing gate interval part why what I am doing is that we I am getting an interval into is that we I am getting an interval into the error list and adding them into the the error list and adding them into the arraylist and I will combine about them arraylist and I will combine about them into the 2D integer and will return it into the 2D integer and will return it last right so as it is given that my set last right so as it is given that my set my stream of the number doesn't contain my stream of the number doesn't contain any non negative number so I will start any non negative number so I will start my first interval as minus 1 comma minus my first interval as minus 1 comma minus 1. so I will iterate over the set up to 1. so I will iterate over the set up to now which is being made from the now which is being made from the insertion from the atom insertion from the atom so if my left is less than 0 so so if my left is less than 0 so initially if it is minus 1 so I will initially if it is minus 1 so I will assign that left and right value to the assign that left and right value to the current value current value that is selecting the first element that is selecting the first element and if the value of in the set is equal and if the value of in the set is equal to the right plus one that is the if it to the right plus one that is the if it is contiguous as my set is sorted as as is contiguous as my set is sorted as as my set is a DOT sorted data structure so my set is a DOT sorted data structure so that will be a possible condition that will be a possible condition so I will increase my right value to so I will increase my right value to that value right and increase the uh that value right and increase the uh increase the range of the current render increase the range of the current render one and if it is not happening so so one and if it is not happening so so what I'm what I will do is I will add what I'm what I will do is I will add that current interval into my intervers that current interval into my intervers arraylist and then in slice the left and arraylist and then in slice the left and right to the current value right to the current value and at last there will be an uh there and at last there will be an uh there will be a last interval which has been will be a last interval which has been left to add into the intervals so I will left to add into the intervals so I will do that and At Last I have converted do that and At Last I have converted that RL H2 to the 2D array so if you that RL H2 to the 2D array so if you have any another approach for doing this have any another approach for doing this error list to our account version so do error list to our account version so do comment below if you have any good comment below if you have any good approach so I have converted that and approach so I have converted that and send it as a response right so let's try send it as a response right so let's try to submit this to submit this so it gets accepted in Java let's try to so it gets accepted in Java let's try to submit this question in C plus plus so the test case given in the question is passing let's try to submit this question so it got accepted in C plus plus as well I hope you liked the video thank you for | 2024-03-24 11:19:10 | 352 | 352 Data Stream as Disjoint Intervals(C++ & Java) - Leetcode January Challenge 2023 |
|
3Tte86twOJ0 | hello and welcome back to another Elite code problem so today we're going to be code problem so today we're going to be doing problem number 212 word search two doing problem number 212 word search two so we're given an M by n Board of so we're given an M by n Board of characters and a list of strings and we characters and a list of strings and we need to return all words on the board need to return all words on the board each word must be constructed from each word must be constructed from letters of sequential adjacent cells letters of sequential adjacent cells where Jason cells are horizontally or where Jason cells are horizontally or vertically neighboring in the same vertically neighboring in the same letter cell may not be used more than letter cell may not be used more than once in a word once in a word so we're given something like this we're so we're given something like this we're given a board we're given a list of given a board we're given a list of words and we need to construct this words and we need to construct this and so and so it's going to be difficult to it's going to be difficult to do some kind of DFS or something because do some kind of DFS or something because the length of this the length of this word list is very long word list is very long but this is n by m but this is n by m where n and M are very short I think where n and M are very short I think they're like 12 karat 12 uh they're like 12 karat 12 uh only 12 spaces long so when you see only 12 spaces long so when you see something like that when you have a huge something like that when you have a huge word list word list and a short board and a short board so you are probably gonna have to do so you are probably gonna have to do some kind of search but something like a some kind of search but something like a depth for search makes a lot of sense depth for search makes a lot of sense with backtracking and the reason we can with backtracking and the reason we can use backtracking is in order to store indices we visited earlier like let's say we start this o in order to store indices we visited earlier it really matters where we got there from so for example if we get here it really matters where we got there from like did we get here from this o and if we did get here from the so did we originate it so or did we maybe start here and then go to here and here and so when there's all these different combinations and just because you get to an index doesn't mean you all these iterations are different it really matters where you got there you're gonna have to do something like backtracking as opposed to memorization because all these different things can't really be recorded like you'd have to record the exact path and then you're storing entire arrays which is not great so whenever you have an array of a path you typically want to use backtracking instead and so the other thing is when we when we Traverse how do we really know if we get a word well one thing we could do is we could have a path and then every time we get to a letter we just so let's say we go this way so we have Oath right oh you could be like okay we have Oath is oath in our dictionary we have some other things that enter a dictionary but that's going to get expensive rather fast because this words is really big so is there a better way to know if this is in our dictionary or if this is in our words without traversing it every time and there is actually a better way to do that and the better way to do that when our words list is long but all the words are kind of small and we have this small board is using a try and so the basic concept of a try is it's going to be a path so let me just demonstrate so it's going to be a variable let's just say this is the try and it's going to contain every letter in it and then every letter is going to point to another try so for example for oath we're going to have a root so this is going to be the root instance variable of the try then it's going to have a every single try is going to have a dictionary of children with keys being a letter and then the value being another try so like this is the root let's say now we go to O we get to another try this o has an a right get to another try this a has a t get to another try and then an H here and then also if try to share the same letter so for example this root can have an O and then this can point to like let's say of if of was a word or something like that so we're gonna whatever node we start at we're going to start at the root we're going to Traverse down every time and we're going to ask ourselves so the other thing a try has that's kind of important is every time we Traverse down a letter so there would be extra try here at the end try here at the end we would say okay once we're at a try all we have to do is we can have a variable a Boolean for the variable called like let's say we call it end and if n is true that means we've reached the end of a word and so we can iterate through this words oh we can iterate through this words dictionary one time take all of these words and make a try so for example let's see what a try would look like for all of these words so starting with oath right so let's delete this and let's do that so we start with oath remember we have this root node so let's just call that root node we go through an o go another try go through to an a so go to another try T another try H another try now we've reached the end of the word so we're going to mark this equal we're going to say this is an end and I'm just going to make this red and red means the end of a word so we also have P so p is a completely different it doesn't have any of the same letters so this dictionary once we're at this try this will have a dictionary of every single letter that we used words for so it would have it would add this p and then e and a have another try down here same thing this is showing that we reach the end now we have rain or we have heat sorry so eat is completely different as well so e a we're not sharing the first letter the end of the word the end of the word and finally rain so rain doesn't share and finally rain so rain doesn't share anything either so anything either so our our a a all right and all right and okay and this is the this okay and this is the this and so and so when we Traverse down like let's say when we Traverse down like let's say we're at oath so we start at the root we we're at oath so we start at the root we go to O then we go to a then we go to T go to O then we go to a then we go to T then we go to H and we see oh we're at then we go to H and we see oh we're at this end node that means this is a valid this end node that means this is a valid word word and we're just going to keep track of and we're just going to keep track of the current word the current word like we're just going to have some kind like we're just going to have some kind of current uh array that's going to keep of current uh array that's going to keep track of every single letter that's in track of every single letter that's in our path and as soon as we hit an end our path and as soon as we hit an end node we're going to add whatever current node we're going to add whatever current is to our result but keep in mind we is to our result but keep in mind we can't just can't just we can't just go back as soon as this we can't just go back as soon as this happens because there might be a longer happens because there might be a longer word that contains this word so for word that contains this word so for example this oath might also contain a example this oath might also contain a word like Oaths so even though there's word like Oaths so even though there's an end we have to keep going until we an end we have to keep going until we backtrack fully so you can see like this backtrack fully so you can see like this would be a word as well would be a word as well so we don't our con our return so we don't our con our return conditioner wouldn't be conditioner wouldn't be if we just hit a word we'd have to keep if we just hit a word we'd have to keep going going but we can have a return condition where but we can have a return condition where we are at some try we are at some try and we can see okay does this try have and we can see okay does this try have any paths from it does this have any any paths from it does this have any letters in it if not we don't really letters in it if not we don't really need to keep going because there's need to keep going because there's nothing in here so we can just return nothing in here so we can just return there so that would be an end condition there so that would be an end condition as well as if we check every single as well as if we check every single index in a backtrack index in a backtrack and also keep in mind for these tries and also keep in mind for these tries words can share letters right so let's words can share letters right so let's say this is a root so we have e but we say this is a root so we have e but we might have ears Maybe might have ears Maybe could be a word could be a word so then it would go down the same path so then it would go down the same path so it would go to EA but then it would so it would go to EA but then it would go here go here and to this try and to this try and this would be an end node and this would be an end node so that's kind of how a traged it so that's kind of how a traged it represented we're going to have a represented we're going to have a dictionary of letters as keys and then dictionary of letters as keys and then they're going to point to other tries they're going to point to other tries we're going to start our root and we're we're going to start our root and we're going to Traverse down and we're going going to Traverse down and we're going to have we're going to use this n to have we're going to use this n variable to know that we have a result variable to know that we have a result and we need to travert we need to start and we need to travert we need to start at every single node in this at every single node in this um in this grid and we need to try to um in this grid and we need to try to Traverse in every direction using Traverse in every direction using backtracking backtracking so let's and yeah by the way so we can so let's and yeah by the way so we can look at also look at also yeah so this is going to give you a lot yeah so this is going to give you a lot of hints to do things like that when you of hints to do things like that when you see this m is really small this n is see this m is really small this n is really small really small that means backtracking is going to be that means backtracking is going to be something useful because if let's say something useful because if let's say this grid was like a thousand by a this grid was like a thousand by a thousand then if you backtrack that's thousand then if you backtrack that's going to get really expensive and also going to get really expensive and also you see this words you see this words this word length is really big so you this word length is really big so you don't really want to compare every don't really want to compare every single node you're at to the words like single node you're at to the words like where if the sword length is only like where if the sword length is only like 10 words then we could easily just 10 words then we could easily just compare every time instead of using a compare every time instead of using a try because it's kind of small so hopefully that makes sense and let's just start coding it up so first of all we're going to have a try class right so actually for our try I don't think we so actually for our try I don't think we need to pass anything need to pass anything to it so we're just gonna have it in it to it so we're just gonna have it in it try and then we need self.children try and then we need self.children equals this empty dictionary right equals this empty dictionary right and self dot end equals false we can and self dot end equals false we can give our try a character but technically give our try a character but technically we don't need to do that because these we don't need to do that because these should all be connected should all be connected so so so then we need to go through this so then we need to go through this list words and we need to list words and we need to make this list of tries so this would make this list of tries so this would actually not be a try this would be a actually not be a try this would be a try node so now the the try is the actual try is this full tree type looking thing but all of these are actually try nodes okay and so first we need to make a root and that's going to be our root note that we're just going to start at and then we're going to start we're going to keep starting at the root node and go down all of these words to make our actual try so we can just say root equals try like that like that it doesn't take any values so it doesn't take any values so now we just have to iterate through now we just have to iterate through every single word so for a word every single word so for a word words words and then we have to iterate through and then we have to iterate through every single character as well so for every single character as well so for care and word care and word so for word and words first we have to so for word and words first we have to start at the root so we can do something start at the root so we can do something like this curve equals root like this curve equals root and then we are going to Traverse down and then we are going to Traverse down every single character every single character so if care in Cur dot children yeah if so it's actually if not so for example when we don't have um when we don't have these children we need to make them right so when we start with our initial root like we start with our root and we're going down some word like word when we're at this route we we check the children the W isn't in there so now we need to make it so every time the character isn't in the children we need to add it in and then we need to go to it so if character not incurred our children then we add it in there right and so we do Cur dot children care and then now we just simply Traverse or and then now we just simply Traverse or because we would have made it where it's because we would have made it where it's already in there so occur equals already in there so occur equals children children care care then once we Traverse that whole word so then once we Traverse that whole word so now we're going to be at the tri node now we're going to be at the tri node that's the end of the word and now we that's the end of the word and now we need to make this end true so just Cur need to make this end true so just Cur dot end equals true dot end equals true okay so now we made all of our tries and okay so now we made all of our tries and now we need to use this DFS backtracking now we need to use this DFS backtracking algorithm algorithm to actually search for all these nodes to actually search for all these nodes so first we're going to want a couple so first we're going to want a couple things we're going to want some kind of things we're going to want some kind of sort of backtracking it's good to have a sort of backtracking it's good to have a curve array and a curve array and a resume right for the actual output resume right for the actual output so we can just have so we can just have res equals this and then Cur equals this res equals this and then Cur equals this and then our curve is actually going to and then our curve is actually going to be a be a list of characters and then we're just list of characters and then we're just going to join those together and put the going to join those together and put the put it in the residents we actually have put it in the residents we actually have a word So Def DFS and the DFS is going to take an index and it needs to take a node because we need to see what Tri node are we in I believe so we're going to fasten the route to start off so it's just going to be a node okay so like I said if if the node were in has no children right that means that we can't go anywhere so we can just return straight away so if no dot children and we guess we can just say like this we do need to we do need to actually we do need to we do need to actually check if we're at this node we do need check if we're at this node we do need to still check if to still check if if it hasn't so like if we're at an end if it hasn't so like if we're at an end node even though this node has no node even though this node has no children that we're still at an endnote children that we're still at an endnote so we would have to append that word so we would have to append that word so that's the first thing we can do so so that's the first thing we can do so if if node dot end node dot end that means it's true we do need to that means it's true we do need to append this curve so we just need to do append this curve so we just need to do res dot pend res dot pend and then we need to join current so join and then we need to join current so join occur okay occur okay so now we do that but then we need to so now we do that but then we need to keep going because this can have more keep going because this can have more children so if no if not no dot children children so if no if not no dot children we can return here I believe we can return here I believe now what are our other cases well if we now what are our other cases well if we have children we need to actually DFS have children we need to actually DFS into all of these letters into all of these letters and so what we would do let's think so the way we would do this is we would get another thing we can do is we can add this directions array this is always useful for DFS so directions equals zero one zero one negative one zero zero negative one okay so let's say we're here if we try to DFS into one of these we we could only DFS into one of these if it's actually in the children so if it's not of the children we don't need to DFS it for example if we're at this zero and a is not in the children then we don't have to go there so the only way we would have to DFS is if it's a valid index and if it's a and if it's also in the in the nodes children by the way so this index would and so another another thing we can have and so another another thing we can have here is this as well equals length board and Link or zero this is good to have for checking if we're inbounds and things like that okay so so yeah so we need to check all these directions and get new directions let's do that so four I'll just say Direction new row new row new column new column equals rho plus Direction and and column okay now we need to check if they're in bounds so if new row is so we need to check if everything's in bounds and it's a valid and there's something there so here is this less than rows and zero it's about this new column lesson columns and so remember we need to check if this our children our children so if board you column in and then this would be node dot children okay so now we have everything valid I believe now we can backtrack to it we would just call DFS on that so we we would just call DFS on that so we would say something like DFS new row you call them and then this node would be node dot children and then it would be this letter right so that's what we would pass in so that's what we would pass in I think that makes sense I think that makes sense otherwise we don't even have to DFS into otherwise we don't even have to DFS into it okay and now let's think about do we even need a return value I don't think so I think once we go through all these backtracks we're not really modifying anything we're just updating where to go from here okay okay so I think that looks good so let's try so I think that looks good so let's try to just see what that looks like and see to just see what that looks like and see if we have any issues oh by the way do if we have any issues oh by the way do we need to we need to add to Cur and remove from Cur and add to Cur and remove from Cur and things like that that's another thing we things like that that's another thing we would need to do actually yeah so actually we do need to do something so if this is a valid location how do we do this so how do we do this so I think actually instead of checking I think actually instead of checking this let's think about this so we're at a root we're going to pass something no I think I think this is fine actually so what we do need to do is we do need to actually add it to the curve here I believe do we need to do that here no I think we're going to do that here yeah we're going to do that here so it's going to be right over here we need to add that here dot penned dot penned board row board row column column that way yeah so we we get to so let's that way yeah so we we get to so let's say we're at this o we check is this a say we're at this o we check is this a inner o yes it is so then we go to a and inner o yes it is so then we go to a and then we need to append here and then then we need to append here and then what we are going to do when we Loop is what we are going to do when we Loop is when we Loop we don't need to go when we Loop we don't need to go to to I mean we could have a check here as I mean we could have a check here as well for that actually well for that actually but no I don't I don't think that would but no I don't I don't think that would make sense well so we are gonna we're make sense well so we are gonna we're gonna have to do in our Loop is we're gonna have to do in our Loop is we're going to start with our root going to start with our root um we're gonna start with our root node um we're gonna start with our root node and we're going to check is this letter and we're going to check is this letter are all these letters in our root note are all these letters in our root note and if they are then then go there if and if they are then then go there if not we don't even have to start there so not we don't even have to start there so for example if we look at our picture for example if we look at our picture right right let's say for this one our starting let's say for this one our starting letters are e-p-o-r letters are e-p-o-r so then any letter that's not in like so then any letter that's not in like once we Traverse this whole thing if once we Traverse this whole thing if it's not epor we it's not going to be a it's not epor we it's not going to be a valid start index so we can skip all valid start index so we can skip all those those okay so let's just double check this okay so let's just double check this code just to make sense we have code just to make sense we have directions we have rows we have our this directions we have rows we have our this uh this should be fine res curve uh this should be fine res curve so once we're at an index we need to so once we're at an index we need to append to the curve okay makes sense append to the curve okay makes sense so the other thing we need to do as well so the other thing we need to do as well is because this is a backtracking I is because this is a backtracking I think right before we return we're going think right before we return we're going to need to delete to need to delete what we appended here what we appended here so so we can just pop we can just pop to delete and I think that makes sense so like let's say we're here we go to a we append but then we return We pulp okay I think that makes sense to me if no dot end that looks good that looks okay so let's just try this code and see what kind of bugs you're into oh by the way so we do need one other thing so we are going to do this nested Loop where we Loop through this whole Matrix and we check if we can do these so let's do that so four row in row and range rows so remember we need to check if this so remember we need to check if this value is actually in the children of the value is actually in the children of the root node so if root node so if board board column column [Music] [Music] in in and then where's our root node right so and then where's our root node right so it's going to be root it's going to be root dot children yes then we can just pass it in with the root yes and then in this DFS we're going to yes and then in this DFS we're going to yeah we're going to pass it this next yeah we're going to pass it this next thing so thing so so we actually don't want to pass in the so we actually don't want to pass in the root I believe we want to pass in root I believe we want to pass in the node that the node that is in the children so this kind of same is in the children so this kind of same thing like this so if board we would call DFS or we can so this would be row so this would be row column column root dot children root dot children row row column column uh so this is column column yeah so we're going to append the curve yeah so we're going to append the curve here so that should be fine so let's here so that should be fine so let's return return the the res here res here and I think that looks fine we're and I think that looks fine we're probably gonna have some errors it's probably gonna have some errors it's definitely complicated code so definitely complicated code so dict is not callable okay dict is not callable okay row column row column root dot children board row column I'm interesting did I have too many parentheses here yes so this needs to be brackets right so this needs to be brackets right so this needs to be brackets because it's like this because it's like this this is like this let's try that this is like this let's try that okay so we have an error okay so we have an error so we have oath and oeat so we have oath and oeat so why do we have O8 so why do we have O8 that's a bit strange but for a second one it works but for this one it doesn't so for some reason we are appending this o every time so why is that you're fast forward row column is there oh eat too many times is there oh eat too many times I think oh I see the problem I see the I think oh I see the problem I see the problem so we have this return problem so we have this return but we still have to pop regardless but we still have to pop regardless so we still have to so we still have to pop here pop here because we appended so let's try that hopefully that's fast enough we might hopefully that's fast enough we might have to make some optimizations if it's have to make some optimizations if it's too slow like I think there are some too slow like I think there are some optimizations that I remember doing this optimizations that I remember doing this problem problem um but let's see um but let's see okay so oh wait okay so we do have okay so oh wait okay so we do have okay so that's another thing I probably okay so that's another thing I probably wanted unique wanted unique yeah so it wanted unique uh answers yeah so it wanted unique uh answers yeah yeah and so what we need to do yeah yeah and so what we need to do like let's say this is OA and this is OA like let's say this is OA and this is OA and things like that so we need to have and things like that so we need to have one more data type pretty one more data type pretty straightforward now now we can we can where are we adding to the res let's where are we adding to the res let's take a look res dot append so instead of res dot append we can just do res dot add now we just return res I think this should work as a list anyway let's see yeah I think it'll just convert it for us and let's see if it's too slow and if it's too slow we're gonna have to make some other modifications to this it might be too slow I'm not exactly sure because this one I remember when I did this only code it barely passes so okay words a output a okay okay so it looks like we are going back and forth which is a problem so we're coming here yeah so we're coming here and then we're coming back and so we aren't we probably do need uh like let's see what that would look like actually in this in this code okay say we had this a a and let's try okay say we had this a a and let's try to walk through it to walk through it and then we are looking for AAA and then we are looking for AAA okay so it's going to go in this a okay so it's going to go in this a it'll add it to the curve so let's just it'll add it to the curve so let's just say our Cur is a we're here say our Cur is a we're here then we are going to go here then we are going to go here and yeah so then we're adding it now we and yeah so then we're adding it now we do go here which is a problem so we we do go here which is a problem so we we need to have some kind of thing where we need to have some kind of thing where we can't go back to I know that we were can't go back to I know that we were already there already there and so we do need to have a visited set and so we do need to have a visited set I think is what we need I think is what we need set set and then simply for backtracking what we and then simply for backtracking what we need to do is we need to do the same need to do is we need to do the same thing here we need to add the node to thing here we need to add the node to our visited set our visited set so therefore we can't go back and forth so therefore we can't go back and forth so just visited so just visited dot add dot add and we can just add row column here and we can just add row column here then we can remove here then we can remove here so remove I believe so remove I believe okay so visited.adrow column okay so visited.adrow column visited.remove row column and then we visited.remove row column and then we also need it here okay so we need one more check so so we need this is going a little a lot of we need this is going a little a lot of Bounce that's okay so we need Bounce that's okay so we need new row column and this actually needs to be here I guess we can split this up so we can just split these up a little bit to make it cleaner codes of this then we can have an and here and then here and there okay so something like that oh so let's try to see that okay so we have an error we have Oath and we expected oath and eat all right so this should be removed okay definitely a lot of stuff for this problem it's not super easy and it still okay so it pass which is good this one okay so it pass which is good this one down sorry about my cat for a second that this this definitely is a tough problem for sure there's a lot of room to make errors and when you make a solution if you forget one of these optimizations there might even be more I think there is actually one more that I'm forgetting but if you forget any optimizations I think it's really close to not being able to run on the code even yeah like when I submitted this how close was this to I think this is still not like eight top solution so I think there's another one let's see how many uh just to double check again yeah so we're only beating 20 so it's definitely a close one and you can have time limit exceeded if you have some issues so think of the time and space complexity let's make it tricky for sure so time space okay so what are we doing we have this directions array which is negligible this is negligible we have a tri node for every single letter in every single word and so that might be our limiting factor but let's or actually this this will that's that space so for our Tri nodes we actually go through every single letter of every single word so let's just make up some variables again let's just make up some variables again here I just say w equals word length here I just say w equals word length right and not um n equals word count let's say so that part is going to be W Times n to go over every single letter of every single word and make these tries okay and then we're going to do this backtracking so backtracking you will have repetitive operation so you will be you will be checking multiple nodes because it matters where you got here from so for every single node we can go to every single other node and then we can go back but I think that won't be as expensive compared to this making of the tries because these are only 12 by 12 like they're very small so I think that part of the code should actually be negligible compared to making these tries so I think most of the time is going to be spent making these tries if I'm correct and the average backtracking is pretty much Brute Force so it's definitely not an ideal solution but we do have a visited array so we can only go from every node to n by m but like I said even if you do like n by m by n it's still 10 times 12 times 12 which is not that big so I think that part is negligible and I think our time complexity is going to be mostly towards building this try um you can correct me if I'm wrong or I might edit this later if I am but um so space so we are going to make these tries and these tries can technically if all the words are completely different and start with completely different letters then our space is going to be the same thing it's going to be W Times n because we're going to have a try for every single one of these and then are we making anything else so we do have a res which is going to be every single it could be up to every single word which would be also W Times n and we have a cur which is just going to be the length of a word maximum and we do have a visited set and we have a rep and we have uh I think we have one more set no this is just a set so this visited set though is basically negligible because the most it can ever be is 10 by 12 so that doesn't matter so I think the space is this as well all right so this was quite a long problem and I hope you enjoyed it and if you like these kinds of videos like And subscribe and I'm going to continue | 2024-03-22 10:31:19 | 212 | Word Search II - LeetCode 212 - Python |
|
9PRzLrF8TQw | thank you foreign coming coming up [Music] [Music] thank you foreign welcome to this tutorial on solving the lead code problem summary ranges in this video we will tackle an interesting problem that involves efficiently finding and summarizing consecutive ranges within a sorted array this problem asks us to take a sorted array of unique integers and return the smallest sorted list of ranges that cover all the numbers in the array exactly each range is represented as a error B if a is not equal to B and as a if a is equal to B in this tutorial we will walk through the intuition behind the solution and dive into a python Implement implementation of the most optimized solution without further Ado let's get started well the problem requires us to find and summarize consecutive ranges in a sorted array to do this we need to identify the start and end points of each range let's break down the intuition step by step well to begin with we need to check if the nums array is empty we do this using an if statement if not nums if the array is empty we immediately return an empty list then we initialize and empty list called ranges to store our summary ranges this list will eventually hold the smallest sorted list of ranges that cover all the numbers in the input array well we then we also initialize two variables start and end and set them both to the first element of the input array these variables will keep track of the current range as we iterate through the array now we iterate through the remaining elements of the array starting from the second element by examining each element we can determine if it is consecutive to the previous element if the current number is consecutive to the previous number it means we are still within the same range in this case we update the end variable to the current number efficiently extending the current range and the other hand if the current number is not consecutive to the previous number it indicates that the end of the current range we need to add this range to our range list to determine the format of the range we use an if statement to check if the start and end are equal if they are equal it means we have a range with just one number in this case we add that single number to the ranges list if the start and end are different it means we have a range with multiple numbers in this case we add the range to the range list in the format start Arrow end after adding the range to the ranges list we update the start and end variables to the current number this prepares us to prepare this for the next range if any once we finish iterating through all the elements we need to handle the last range we use another if statement to check if the start and end are equal or different and append the corresponding range to the ranges list finally we return the ranges list which now contains all the summary ranges by following this intuition we efficiently identify and summarize consecutive ranges in the sorted array the algorithm keeps track of the start and end points constructs the output in the desired format and optimizes both time and space complexity the time capacity of the solution is O of n where n is the length of the input array why is it why is it Big O of M well we iterate through the entire array once visiting each element exactly once this is and this is because we have a single Loop that goes through the elements of the array starting from the second element therefore the runtime of the algorithm scales linearly with the size of the input now let's move on to the space complexity of the solution the space capacity of the solution is Big O of 1 or Y is it a big of one although we use an additional list called range to store the summary ranges the space it occupies does not depend on the size of the input array um it remains uh constant regardless of the array length additionally we use a few variables such as start and end which also occupy constant Space by having a constant space complexity we can efficiently solve the problem without incurring significant memory overhead even for large input arrays so to recap to recap the time complexity of the solution is Big O of M indicating linear runtime and the space capacity is Big O of 1 indicating constant space usage understanding the time and space capacities of an algorithm allows us to evaluate its efficiency predict its performance with larger inputs and compare it to other algorithms for the same problem and there you have it we have successfully tackled the summary range problem from with code congratulations I hope you found this tutorial helpful and gained a solid understanding of the problem and its solution if you have any questions please let me know in the comments below and if you enjoyed this tutorial be sure to give it a thumbs up and subscribe to the channel for more coding tutorials tips and tricks happy coding and thanks for watching goodbye foreign foreign [Music] | 2024-03-22 11:07:18 | 228 | LeetCode Python Solutions: 228. Summary Ranges #python #coding #leetcode |
|
PN68qx-Qkdw | hey what's up guys and quite here - tech encoding stuff on Twitch in YouTube and encoding stuff on Twitch in YouTube and I do all the Waco problems I got a I do all the Waco problems I got a million up right now not a million but a million up right now not a million but a lot so check those out if you're looking lot so check those out if you're looking for solutions on leak code problems and for solutions on leak code problems and explanations so yep that's what we're explanations so yep that's what we're doing right now we're doing this one doing right now we're doing this one it's called squares of a sorted array so it's called squares of a sorted array so given an array of integers a sorted in given an array of integers a sorted in non decreasing order I don't know why non decreasing order I don't know why they don't just say increasing return an they don't just say increasing return an array of squares of each number also array of squares of each number also sorted in non decreasing order so we see sorted in non decreasing order so we see the array is right here negative 4 the array is right here negative 4 negative 1 0 through 10 increasing order negative 1 0 through 10 increasing order and then we have 0 1 9 16 100 these are and then we have 0 1 9 16 100 these are the squares of these numbers also sorted the squares of these numbers also sorted and you can see that you know negative 4 and you can see that you know negative 4 times negative 4 is gonna be 16 so times negative 4 is gonna be 16 so that's gonna be right here and they come that's gonna be right here and they come on time so that one's good we want it's on time so that one's good we want it's right here so just to show you kind of right here so just to show you kind of how that works so basically the trick to how that works so basically the trick to this problem in solving it now optimal this problem in solving it now optimal speed space is just accounting for these speed space is just accounting for these negatives kinda that's the only tricky negatives kinda that's the only tricky part here so we're just gonna use a part here so we're just gonna use a two-pointer approach so what we're gonna two-pointer approach so what we're gonna do is we're gonna take a pointer and set do is we're gonna take a pointer and set it to the last negative element so we're it to the last negative element so we're gonna have a pointer here in this case gonna have a pointer here in this case and then we're gonna have that point or and then we're gonna have that point or decrement because that the FIR the first decrement because that the FIR the first element the last negative element here element the last negative element here is gonna be the smallest positive is gonna be the smallest positive element when we square it negative 1 element when we square it negative 1 times negative 1 is gonna be 1 so we're times negative 1 is gonna be 1 so we're gonna want to put that in to the right gonna want to put that in to the right before the next negative element so before the next negative element so we're gonna have our one pointer cover we're gonna have our one pointer cover the negative elements and go in the negative elements and go in decreasing order and then the other decreasing order and then the other pointer is gonna be at the first pointer is gonna be at the first positive element and it's gonna go in positive element and it's gonna go in increasing order because increasing from increasing order because increasing from the smallest positive to the biggest is the smallest positive to the biggest is going to give us the smallest Square to going to give us the smallest Square to the biggest so let's just start doing the biggest so let's just start doing that so first of all we're gonna grab that so first of all we're gonna grab the length of our right here and then the length of our right here and then we're gonna do set our first pointer so we're gonna do set our first pointer so let's say we have we can just call it let's say we have we can just call it positive positive Poynter I'll just so I can make this Poynter I'll just so I can make this clear for you guys so positive pointer clear for you guys so positive pointer is going to be equal to zero right now is going to be equal to zero right now and then we'll do a wild positive and then we'll do a wild positive pointer is less than and so while it's pointer is less than and so while it's less than the length of our array we less than the length of our array we will do will do oh no and and a positive pointer so the oh no and and a positive pointer so the current element is less than zero so current element is less than zero so while we're while are positive while we while we're while are positive while we didn't get to the end of the array we're didn't get to the end of the array we're looping through the array and while the looping through the array and while the elements are still negative then we're elements are still negative then we're going to increment our pointer positive going to increment our pointer positive pointer right so now once we break out pointer right so now once we break out of this loop we've gotten to the we've of this loop we've gotten to the we've passed the final negative element so if passed the final negative element so if we were on negative one here it would we were on negative one here it would still loop through and then we'd be on still loop through and then we'd be on zero right now so now we want to set our zero right now so now we want to set our second pointer so our negative pointer second pointer so our negative pointer is going to be set to positive pointer is going to be set to positive pointer minus one so now our negative pointer is minus one so now our negative pointer is set to the index of the first negative set to the index of the first negative element right perfect so now we could element right perfect so now we could set up our new sorted array for a square set up our new sorted array for a square sorted so we could do int stem I'm sorry sorted so we could do int stem I'm sorry about that int sorted squares I'll call about that int sorted squares I'll call this array as they go the new int of this array as they go the new int of size n it's gonna be the same size as size n it's gonna be the same size as our initial array here and then we're our initial array here and then we're gonna have our final pointer or find our gonna have our final pointer or find our counter so we'll just have a counter is counter so we'll just have a counter is at the zero to kind of increment our at the zero to kind of increment our array as we go and yeah that's pretty array as we go and yeah that's pretty much it now all we have to do is our much it now all we have to do is our loops so while negative pointer is loops so while negative pointer is greater than or equal to zero and greater than or equal to zero and positive pointer is less than n we are positive pointer is less than n we are going to do a check if a of negative going to do a check if a of negative pointer so if the square of the negative pointer so if the square of the negative element is less than the square of the element is less than the square of the positive element positive element I don't know if these naming conventions I don't know if these naming conventions are really good for a video but I kind are really good for a video but I kind of want to I hope that you guys it hopes of want to I hope that you guys it hopes you understand then we're gonna set our you understand then we're gonna set our sordid squares array sorted squares of sordid squares array sorted squares of counter and you can increment within counter and you can increment within right here or you can increment right here or you can increment separately I'll do it separately so you separately I'll do it separately so you guys can see better sorted scores of guys can see better sorted scores of counter is gonna be equal to a of counter is gonna be equal to a of negative pointer times a negative negative pointer times a negative pointer because we want the smaller of pointer because we want the smaller of the squares because the square of a the squares because the square of a negative element can be less than the negative element can be less than the square of a positive element obviously square of a positive element obviously and the square of a positive element can and the square of a positive element can be less than the score of a negative be less than the score of a negative element for example three squared is element for example three squared is nine but negative four squared is nine but negative four squared is sixteen so nine is gonna get it put in sixteen so nine is gonna get it put in before sixteen so we want to do that before sixteen so we want to do that check here so you know if the negative check here so you know if the negative element is less than the square is pop element is less than the square is pop squared is less than the positive squared is less than the positive element we're gonna put that in our element we're gonna put that in our array first else we put the positive array first else we put the positive element in our array from the first two element in our array from the first two sorted squares of counter encounters sorted squares of counter encounters once again just a little counter once again just a little counter variable to increment our array as we go variable to increment our array as we go positive pointer there we go and that's positive pointer there we go and that's pretty much the main loop here we do pretty much the main loop here we do have to obviously decrement our negative have to obviously decrement our negative pointers a negative pointer minus equals pointers a negative pointer minus equals one at each loop and increment our one at each loop and increment our positive pointer as we put these positive pointer as we put these elements in and then also our counter elements in and then also our counter like I said you could have just like I said you could have just incremented it right here if you wanted incremented it right here if you wanted both times but you don't have to so now both times but you don't have to so now that we break out of the loop this means that we break out of the loop this means that either our negative pointer we've that either our negative pointer we've hit the last negative element or we've hit the last negative element or we've gotten to the end of the array in that gotten to the end of the array in that case at the last positive element so we case at the last positive element so we just have to get those edge cases here just have to get those edge cases here so well negative pointer it's greater so well negative pointer it's greater than or equal to zero because one than or equal to zero because one them could be at the end but we still them could be at the end but we still have to account for the rest of either have to account for the rest of either the negative elements or the positive the negative elements or the positive elements while negative pointers greater elements while negative pointers greater than or equal to zero then we just add than or equal to zero then we just add our final elements here our final elements here sorted squares of counter is equal to a sorted squares of counter is equal to a negative negative point negative point D negative negative point negative point D commenting again and then it's gonna be commenting again and then it's gonna be the same type of deal here once again the same type of deal here once again and you also have to make sure you count and you also have to make sure you count for the counter Wow for the counter Wow positive pointer and just the same positive pointer and just the same conditions up there but one of them will conditions up there but one of them will break out so we have two these are just break out so we have two these are just edge cases counter hopefully you guys edge cases counter hopefully you guys understood this solution as I went understood this solution as I went through I tried to name it so that we've through I tried to name it so that we've made it better for you guys to made it better for you guys to understand I might have made it more understand I might have made it more difficult and then our race should be difficult and then our race should be filled and sorted order of all of the filled and sorted order of all of the squares of the original elements so squares of the original elements so we'll return not answer but sorted we'll return not answer but sorted squares and let's submit it hopefully it squares and let's submit it hopefully it works for strong positive pointer not a works for strong positive pointer not a statement line 35 positive pointer plus statement line 35 positive pointer plus equals 1 sorry incrementing that a lot equals 1 sorry incrementing that a lot of code there we go success that's of code there we go success that's pretty much it hopefully you guys pretty much it hopefully you guys understood that I tried to write it in a understood that I tried to write it in a way that would help you guys understand way that would help you guys understand that just a two-pointer method we're that just a two-pointer method we're storing everything new into a new array storing everything new into a new array so I guess that's open space and it's so I guess that's open space and it's linear so good run time here the linear so good run time here the pointers with the negative just going pointers with the negative just going backwards on the negative elements backwards on the negative elements forward on the positive elements and forward on the positive elements and putting them into the new array it's the putting them into the new array it's the smaller of the two squares one at a time smaller of the two squares one at a time so that's a check out my other videos if so that's a check out my other videos if you can everything is in description you can everything is in description then just watching you then just watching you and I'll see you later | 2024-03-25 14:19:12 | 977 | LeetCode Squares of a Sorted Array Explained - Java |
|
SXU--MPoUe8 | do channel 54 and you can also see the playlist of DP construction. If you want to understand DP from the beginner level, then okay 95 is the medium mark I have I have I have solved the question, solved the question, I have given its link in the description. It I have given its link in the description. It is a similar question. Okay, so the code from there is a similar question. Okay, so the code from there can be used here also. Okay, the can be used here also. Okay, the name of the question is Unique Binary Search Tree Part name of the question is Unique Binary Search Tree Part 2. Let us understand that the question is very small and very That you have given the interior, okay That you have given the interior, okay That you have given the interior, okay property, know that if this is the route then its left side value will be less than this route prestige which has exactly and notes of prestige which has exactly and notes of unique values from one to one is okay return unique values from one to one is okay return d answer in other can be made into examples. Look, one here, can be made into examples. Look, one here, its right side is three, left side you, its right side is three, left side you, this is binary search history because see, this is binary search history because see, its right child is bigger than one, it is bigger than one its right child is bigger than one, it is bigger than one and its left child of three is and its left child of three is smaller than three, you are this. smaller than three, you are this. smaller than three, you are this. history, this is also binary, this is also binary creation, this is also forest research, then okay, then what do we have to return, send the route of every binary search history, just like this, this is binary search history, what is its route, forest, us. route, so let's see how we will approach it and we have already solved a question find the possible full binary tree, today what we have to find the possible full binary tree, today what we have to find which is the possible binary search tree. find which is the possible binary search tree. So the structure of both the codes So the structure of both the codes will be exactly the same, okay, we will make them in a very simple way, will be exactly the same, okay, we will make them in a very simple way, okay, now coming okay, now coming to the approach, how will we take the approach, okay, to the approach, how will we take the approach, okay, so see, before increasing the approach, If we If we If we take Maa, take Maa, this is a binary search history of mine, then if this is a complete binary system, then if this is a complete binary system, then what does it mean that this is also true in itself and this is also a sister research history in itself. and this is also a sister research history in itself. And this is also a balance seat in itself. And this is also a balance seat in itself. All the trees are binary in themselves. All the trees are binary in themselves. You must know this. Okay, let's move ahead. What was the You must know this. Okay, let's move ahead. What was the example? Okay, meaning, what values can be there? It It can be It can be It can be free, it can be 4, it can be five, it free, it can be 4, it can be five, it can be six, okay, I showed you a little fear above, in this example, you are seeing that it Here it is, Here it is, Here it is, look here, √1 is root, you look here, √1 is root, you can also become root, can also become root, so everyone should get a chance to become root, otherwise so everyone should get a chance to become root, otherwise what will I do, what will I do, I will root this once, then I will I will root this once, then I will root this once, then I will root this once root this once, then I will root this once and so on, okay and so on, okay and so on, okay make a route, so I will show you an example that if I take a mother, I have made a route for four, look, everyone will make a route one by one, but I have made a route for four and now I am showing six how you can You will do it, let's take four as a root, You will do it, let's take four as a root, You will do it, let's take four as a root, I am fine, so sincere I am fine, so sincere is binary, so what does binary mean, if is binary, so what does binary mean, if four is a root, then on the left side of four, there will be four is a root, then on the left side of four, there will be all its small values which will be smaller than four, so the all its small values which will be smaller than four, so the thing is that thing is that thing is that left child of four which will be all the subtrees on the left side of four, their value should be smaller than four, then I can take the value from here only. Right means from where till where I I I I can take only the values from start to i - 1 to can take only the values from start to i - 1 to create the leftmost children of four, to create all the leftmost create the leftmost children of four, to create all the leftmost three, to three, to create all the things on the left. create all the things on the left. till now. till now. root and on the right all are capitals so let's root and on the right all are capitals so let's reduce one. Let's make this and see that reduce one. Let's make this and see that if the four root is formed then what I said if the four root is formed then what I said will be left on the left side so that I will be left on the left side so that I can make subtrees. can make subtrees. can make subtrees. and this I, I have made it the root and this I, I have made it the root and what are the values on the right, it will and what are the values on the right, it will become 516, I will make it, this was I + 1, this become 516, I will make it, this was I + 1, this was my end, okay so was my end, okay so I will collect all the binaries that can be made here, how many are being made on the left side, b1 on the left means life is chosen and on the right, then on the left b is chosen one and By By By pairing b1 with these two, I pairing b1 with these two, I chose left and right. Okay, from left, b one, from right, b six, similarly, what can I do that four is my route, b2 from left, b5 from left, B Six From here B Six From here B Six From here it is understood that this time I have paired these two with b2 and it is understood that this time I have paired these two with b2 and then similarly I then similarly I will pair these two with b3. If you see then will pair these two with b3. If you see then whatever left BSTC I have whatever left BSTC I have will come in the vector. I will have as many left BSTCs as I have. [Music] This thing will be understood and look at the loop. I know that he has posted it on similar question. If you remember, I have written similar question at the top of the description and have also given a link to his YouTube video. If you go there then you can see it. Logic has also been applied there that whatever was done on the left side was that the complete binary tree had to be extracted, it is okay that what is here is finally extracted, then whatever was found on the left side was taken out, whatever was found on the right side was taken out on the Picking up each one from the side and Picking up each one from the side and Picking up each one from the side and pairing the saree from the right side. pairing the saree from the right side. Okay, just like you were doing it here, the Okay, just like you were doing it here, the logic will be there as well, so the code will logic will be there as well, so the code will be there from the same. Okay, this is clear till now, be there from the same. Okay, this is clear till now, understand this thing. understand this thing. understand this thing. first of all, we have to give everyone a chance to become a root, see, I have just made this a root, while I have come, where will I start, everyone also has to make it, I will start by I will start by I will start by making it the root, let's take the mother, then later I making it the root, let's take the mother, then later I will make the I bigger and make it the root, then I will will make the I bigger and make it the root, then I will become the I and make it the root, okay then I will become the I and make it the root, okay then I will make everyone else's root, I will have to do these two things tomorrow, the make everyone else's root, I will have to do these two things tomorrow, the left ones will take everything. left ones will take everything. And to get all the things on the right, And to get all the things on the right, here I will get vector of trees, here I will get vector of trees, not research factor of tree, vector of tree note, it will be a better name from here and right BSTC will be found from here, But if we pair them by applying a loop, then But if we pair them by applying a loop, then But if we pair them by applying a loop, then our our question has become very simple. See how I question has become very simple. See how I said, whatever is the value of N, said, whatever is the value of N, I will write a solve function from one to one I will write a solve function from one to one and there are more values, and there are more values, this is it, now solve it. this is it, now solve it. this is it, now solve it. can never happen that the start is given can never happen that the start is given greater and it becomes start = end, meaning if we take the value of n as one, then you see If there is one more, then what will If there is one more, then what will If there is one more, then what will happen in it, if we happen in it, if we take the same value, then what does it mean, there is only take the same value, then what does it mean, there is only one root, so I will just one root, so I will just make a simple root, root is equal to you, made make a simple root, root is equal to you, made a new note, new note, What is the What is the What is the value of the start? What is the value of the start? What is the value of the start? What is the value of the start? The same is collected and value of the start? What is the value of the start? The same is collected and returned. Hey, we have to return the returned. Hey, we have to return the value of the vector in the vector. value of the vector in the vector. But if it is not so, is it? So what did I say, I will root everyone, root everyone, I will start from the start note and I will root everyone one by one, Start root everyone one by one, Start I < Who will be on the right side from Start to I I, I I? Who will be on the right side from Start to I I, I I? Who will be on the right side from Start to I I, I I? showed you above from plus one to and so what will it give me? Right BSC factor, I make the root one by one, I made a new note root, make the root one by one, I made a new note root, it is equal, you okay that's it. okay that's it. okay that's it. okay to return the result and if you have okay to return the result and if you have not seen that similar video of mine, then watch that also, not seen that similar video of mine, then watch that also, there you will get the code, it is there you will get the code, it is exactly the code, okay, so let's exactly the code, okay, so let's code it quickly and see, we have simply explained it code it quickly and see, we have simply explained it here. here. here. so wider memorization of this question will also be reduced but science here we can memorize it also then we will do it ok two variables are changing so what will happen to me to fascinate me by taking two variables And what we are returning is returning a vector of trains for each value. Okay, so I will take a map and and start and its corresponding result, see that too differently and now let's quickly see that too differently and now let's quickly finish the code. finish the code. But before making the court, you can check the time complexity, it can be made as per the formula for making whatever is possible, because there are so many notes, so after visiting each note, making it. Okay, if you read more to make more notes, making it. Okay, if you read more to make more notes, then n g. then n g. then n g. complexity is ours, it is okay, if you do not remember this in the interview, then date briefly, fine, you can tell me, if I change the number of murder number to M, then it is okay, then do Two Two Two number of catalog number would be the number of number of number of catalog number would be the number of number of binary search, multiply it by N. binary search, multiply it by N. What is N? What is N? power of N/N is 1.5. Okay, 0.5 doesn't mean there is no root turn. Their power is 1.5. Then what will happen here is the power of four. The power of N/N is 1.5. Okay, this is the value. Slide: There was a mistake. Slide: There was a mistake. Slide: There was a mistake. Okay, now let's code like it was explained. We will do the formation of binary exactly where what is starting, what is one ending, what is n. Okay, from here we will return whatever result will come. Even after writing, I know what it is, okay, and if start, if start is my greater den, that means I have exhausted all the resources and I don't have any children, then I will tap return here, okay, and yes, we have to return in vector, okay, and yes, we have to return in vector, right? right? right? return it, show it by creating the vector like this, okay, I will also show you the Java code right now, okay if start is equal to you, what does it mean that there What we have to do is okay and if it is not so then I solution will be from start to I-1 and which ones on the right side will be from I+1 to and so I will do the retracement tomorrow, so from there I will do the retracement tomorrow, so from there I will get the result is fine and push back in the result. It is simple to return the result to this route, we will also memorize it and it will pass because the constant is very small. pass because the constant is very small. Yes they have this question with Yes they have this question with out memorization, it is very easy to memorize it, one this start and this another change is happening, one this start and this another change is happening, okay but on this this start n, whatever was the result of the vector for these, I will return from here If it is not so, If it is not so, If it is not so, then I will store it at every place before returning. then I will store it at every place before returning. Okay, I have stored it here, I have Okay, I have stored it here, I have stored it here. stored it here. Correct results are obtained after doing late memories or Correct results are obtained after doing late memories or not. Let's not. Let's see after submitting it to India. It should also see after submitting it to India. It should also pass the date. pass the date. pass the date. great, now let me show you the Java code, I have given the link in my description of Getup, you will also get the Java code below, but I will show you the Java code here, so look, this is the Java code, the We We We took this DP for memorization which took this DP for memorization which I had taken in C plus plus ok I had taken in C plus plus ok here also from start and ran till in but here also from start and ran till in but look ok | 2024-03-20 13:31:22 | 95 | Unique Binary Search Trees II | Similar Problem | Recursion | Memoization | Amazon | Leetcode-95 |
|
ybnr2661jX4 | hi all welcome back to cracking the fang welcome back to cracking the fang interviews today i'm going to be talking interviews today i'm going to be talking about lead code number 91 about lead code number 91 which is decode ways this is again a recursion or dynamic programming problem that is very popular in interviews it's been lately asked at google amazon microsoft salesforce and i've also so let's dive right in and try to so let's dive right in and try to understand the problem first of all understand the problem first of all so and here i have a snippet from lead so and here i have a snippet from lead code code so what we have been given is a so what we have been given is a dictionary which dictionary which maps every character from a to z maps every character from a to z to to a number so for starting from 1 to to to a number so for starting from 1 to 26. 26. so for example a character here so for example a character here and i'm just going to call it a variable and i'm just going to call it a variable x x could map to some value 10 could map to some value 10 and where x is a character and where x is a character and you can it's it's a deterministic and you can it's it's a deterministic value you can simply value you can simply just keep you know following along just keep you know following along so c will map to three d will map to so c will map to three d will map to four four and so on but just to simplify and so on but just to simplify the discussion today i'm gonna refer it the discussion today i'm gonna refer it by variable x by variable x uh to explain the problem better and uh to explain the problem better and what we've been given is what we've been given is another string which we are asked another string which we are asked to figure out how many ways it can be to figure out how many ways it can be decoded in decoded in so as an example if you're given the so as an example if you're given the string string 2 to 6 and we have 2 to 6 and we have characters which map from 1 to 26 characters which map from 1 to 26 by default the way 2 to 6 can be broken by default the way 2 to 6 can be broken down is down is 2 can represent b 2 can represent b or the other 2 and 6 can represent i'm guessing it's going to be some some character so i will call it variable x and the other way this can be broken down is 22 which would be i am going to call it variable y again where y is some character you which you can figure out but this is a valid way to decode just to emphasize on that so 22 and 6 and 6 would be again x right since we are assuming 6 is mapped to character x so there are two ways way one and b2 to to break down two to six and what we've been asked to do is uh figure out number of ways in which we can decode it and i i mentioned this in my previous video about whenever you are asked number of ways whenever you are asked number of ways um it should prompt you to think about um it should prompt you to think about breaking down the problem into breaking down the problem into individual sub problems so here breaking it this way sub problem number one breaking it this way so problem number two and these algorithms are and you can later optimize these the and you can later optimize these the runtime of recursive algorithm which is runtime of recursive algorithm which is usually usually exponential to with dynamic programming exponential to with dynamic programming by by saving solutions and convert this into saving solutions and convert this into a polynomial time and when i say polynomial what it means is as an example exponential runtime could look like o of 2 power n this is exponential polynomial could be o of n square as an example or even o fn anything which is ah which is a power of uh n wherein is the uh number of uh the size of the input given to us all right i hope the idea is clear what the problem is asking us to do we have been given a map we've been given a string we are asked to find the number of ways we can decode it so i'm going to emphasize on the concept and try to break this down the problems problem down into sub problems as i said and if you haven't already i recommend you check out the climbing stairs video before before we go any further link is in the description the climbing style problem is a good fundamental problem to figure out how recursion and dynamic programming works i have explained it in more detail there and i am sort of using the concepts from the other video so i will pause the video right here check out the climbing stairs problem all right so let's come back to the all right so let's come back to the problem problem uh so if i give you a character uh so if i give you a character if i give you a string three uh this if i give you a string three uh this maps to maps to how many ways can you decode this if i how many ways can you decode this if i if if i just give this to you as an if if i just give this to you as an input input how many ways you can decode this uh you how many ways you can decode this uh you can decode can decode three to c and again this is given to us three to c and again this is given to us in the dictionary in the dictionary therefore num ways a string 3 can be decoded is one you you can you cannot decode this right you you can you cannot decode this right so again this is another base case that so again this is another base case that we are going to use so an empty string can only be decoded in one way which is no way and this is very similar to the climbing stairs problem check it out i'm going to go to the next case so this is case number one this is case number two and let's look at case number three if i if i give you a string which is more like one how many ways can you decode this so if how many ways can you decode this so if you start from you start from the left you can either start the left you can either start by one as by itself or take one to by one as by itself or take one to write as a character so one could map to write as a character so one could map to [Music] [Music] a character and even one two has a valid a character and even one two has a valid mapping in the mapping in the in the map given to us so the number of in the map given to us so the number of ways you could decode that ways you could decode that would be num ways two three four five i'm assuming i am able to decode one plus number of you can decode 3 4 5 where i'm assuming you can decode 3 4 5 where i'm assuming we can decode 12 we can decode 12 so the constraint given to us is any so the constraint given to us is any number number which is between 1 and 26 which is between 1 and 26 can be decoded so one can be decoded 12 can be decoded so one can be decoded 12 can be decoded but can be decoded but as an example 34 cannot be decoded as an example 34 cannot be decoded uh which is here which which could be uh which is here which which could be the next step of the recursion i'm just the next step of the recursion i'm just putting it out what putting it out what what the constraint of the problem is and to to sort of solidify this idea further let's take this string and solve it further ah again i'm gonna say num ways 2 3 4 5 can be decoded as b which is 2 and plus numbers three four five all right so uh let me let me make a all right so uh let me let me make a quick correction here quick correction here i'm making up a new example just to add i'm making up a new example just to add clarity so if clarity so if the number is 2 4 2 7 4 the number is 2 4 2 7 4 5 the way you would decode that is 5 the way you would decode that is b plus 7 3 4 5 b plus 7 3 4 5 and the reason i did that is you can if and the reason i did that is you can if if you start here if your pointer is if you start here if your pointer is at the beginning of the string you can at the beginning of the string you can decode 2 which is b decode 2 which is b but you cannot decode 27 as it's not but you cannot decode 27 as it's not going to be in range going to be in range this is a better example to understand this is a better example to understand so you're forced to take 7 3 4 so you're forced to take 7 3 4 5 as your preceding string you won't 5 as your preceding string you won't exercise the other case like we did here exercise the other case like we did here where we took one two so you cannot take where we took one two so you cannot take 27 because it does not fall in range 27 because it does not fall in range so that's the important concept i want so that's the important concept i want you to understand similarly if you break you to understand similarly if you break this down further this down further you'd have to break this up as seven you'd have to break this up as seven plus three 5 plus three 5 you cannot break it down as 73 you cannot break it down as 73 and 45 because this is out of range all right so now let's start by looking at the code for this problem i'm gonna directly talk about the dynamic programming code and you can the recursive code is going to look ah very similar to this expression if you want to start there and the runtime for the recursive code if i were to start with the recursive implementation will be o of 2 power n since you can add max take 2 branches while decoding and this is very similar to the climb stairs video again i highly encourage you to check that out before we look at the dynamic programming solution so now jumping into the dynamic programming solution the first thing we do is convert the string into a list so what that does for us is it um at each uh each number at a time so 2 um at each uh each number at a time so 2 3 4 and so on 3 4 and so on so we've been given a string 234 so we've been given a string 234 we break it down into a list of we break it down into a list of strings or characters let's call it that strings or characters let's call it that then you figure out the length length of then you figure out the length length of this and you create a memoization table which essentially stores your solutions one thing i'm doing here and i really want to emphasize whenever you write a dynamic programming solution always think about storing your base case and for that you will need one extra element in your in your dynamic programming array which is the solution to the base case and where the base case is coming from is this if you have an empty string you the number of ways you can decode that in is one i want to make sure i highlight this so this is the base case you care about the other base case is if you have a single character sorry a single digit the number of ways in which you can solve it is one so these are the two so what i mean is if you have this so what i mean is if you have this number 2 number 2 four and you're storing solutions four and you're storing solutions at the cliff of this uh if i give you at the cliff of this uh if i give you this empty string this empty string the number of ways you can you'll be the number of ways you can you'll be able to solve this is one able to solve this is one this is the base case essentially and this is the base case essentially and yeah you know we will go backwards from yeah you know we will go backwards from here so this is the extra element here so this is the extra element uh we've added with with plus one here uh we've added with with plus one here and the value for this is one we set the and the value for this is one we set the base case base case um what we do is we we we discussed um what we do is we we we discussed there's another base case where you're there's another base case where you're just given one just given one um character one uh one number to play um character one uh one number to play with with which is four in this case you can which is four in this case you can if any time you're given one number you if any time you're given one number you there's only one way to decode it so there's only one way to decode it so you set this here as well and what you you set this here as well and what you do is you do is you trade from here so length minus 2 so trade from here so length minus 2 so this is length this is length uh length so this is length uh length so this is length this is length minus one this is length this is length minus one this is length minus two the reason this is length is minus two the reason this is length is uh we we create uh uh we we create uh length plus one uh as the size length plus one uh as the size of the array and we are indexing from of the array and we are indexing from zero zero so uh the index for the this last so uh the index for the this last position is position is l length so we start from here l length so we start from here uh in the for loop uh and if we hit zero uh in the for loop uh and if we hit zero um so if we had two zero and four um so if we had two zero and four uh uh we let's see how it solve it so uh uh we let's see how it solve it so the number of ways you'd be able to the number of ways you'd be able to decode four is one uh the number of ways decode four is one uh the number of ways you'd be able to decode you'd be able to decode an empty uh string is 1 an empty uh string is 1 but 0 by itself is not in our valid but 0 by itself is not in our valid range which is which range which is which which is x is between 1 and 26 which is x is between 1 and 26 so anytime you hit zero you you simply so anytime you hit zero you you simply keep the answer zero keep the answer zero again we are initializing our again we are initializing our memoization array to zero memoization array to zero and if that's not the case we check if and if that's not the case we check if we can form we can form ah a number which is between this range ah a number which is between this range of 1 to 26 the ascii characters of 1 to 26 the ascii characters if we can do that we decode this number if we can do that we decode this number as itself meaning just looking at the as itself meaning just looking at the previous previous uh solution sub problem solution and the uh solution sub problem solution and the solution right after solution right after so in this example uh uh so in this example uh uh 3 4 can is not something you can 3 4 can is not something you can uh sort of decode because it's not in uh sort of decode because it's not in range range so you'll just look at one level behind so you'll just look at one level behind and mark it and mark it as one this is the step but as one this is the step but in the case of two three you are able to in the case of two three you are able to break it down into break it down into two and two three two and two three two and two three two and two three so the number of ways you'd be able to so the number of ways you'd be able to decode that would be decode that would be looking at the previous solution at 3 looking at the previous solution at 3 meaning you're decoding as 3 but looking meaning you're decoding as 3 but looking at a solution for 3 4 at a solution for 3 4 and also decoding it has 2 3 and looking and also decoding it has 2 3 and looking at the solution for 4 at the solution for 4 so that would be 1 plus 1 2. so that would be 1 plus 1 2. so the final solution is going to be at so the final solution is going to be at index 0 and we return that index 0 and we return that i hope the idea was clear and this is i hope the idea was clear and this is going to be a linear going to be a linear time algorithm as you know we are sort time algorithm as you know we are sort of iterating through of iterating through uh this once and the time complexity uh this once and the time complexity for this will be often the space for this will be often the space complexity complexity is essentially this uh memoized array is essentially this uh memoized array that you've put together the space that you've put together the space complexity is also going to be linear complexity is also going to be linear it's it's of the size of the given input awesome i of the size of the given input awesome i hope this made sense and hope this made sense and please feel free to send in your please feel free to send in your questions in the comment sections questions in the comment sections uh if you like the video please like uh if you like the video please like like it like it share and subscribe to our channel we'll share and subscribe to our channel we'll be um be um sharing a lot of exclusive interview sharing a lot of exclusive interview questions questions asked | 2024-03-20 13:01:38 | 91 | [Leetcode 91] Decode Ways [Recursion][Dynamic Programming] |
|
HXotfwDdU8A | So hello friends, welcome to the new video of Ticket, today is our 70th day, today is our 70th day, we are going to finish it soon, Pacific we are going to finish it soon, Pacific Atlantic Water Flow, okay, this is a medium type Atlantic Water Flow, okay, this is a medium type of question and what is the question trying to say, of question and what is the question trying to say, you can read the statement. you can read the statement. you can read the statement. link to both the question and the answer. I will give it in the description. For now, let me explain what the question is. Okay, so if the numbers are written here, it is like this, here is five, That That That water goes from highest to lowest, so if water goes from highest to lowest, so if water can go to both Pacific Ocean and Atlantic Ocean, then include it in the output. A list of lists of outputs include it in the output. A list of lists of outputs will be made. For example, if it is will be made. For example, if it is five, then it means that five, then it means that five, then it means that columns, then five can go up, down, right, left. If you do not take it diagnally, then neither can you go up and down. Now tell me one thing that there are two conditions for the flow here. First, there should be a small address in front, only It will be able to flow by going and the second one in It will be able to flow by going and the second one in It will be able to flow by going and the second one in front should be equal, then it can flow from five to van, it is front should be equal, then it can flow from five to van, it is small, then it small, then it can also flow from van to van, if it is equal, then it can also flow from van to van, if it is equal, then it means it can go to the Atlantic Ocean. means it can go to the Atlantic Ocean. After van, it is straight. After van, it is straight. After van, it is straight. talking about hair, it will be able to go from three to one punch to three because it is small, it will be able to go from three to one, it is small, then Atlantic Ocean has become, can the Pacific also go, then from three to two punch, then the question of money i.e. Well, whatever row column this one is, it will be added to our output answer. There is one thing here, if we do brute force technicality, then we can see each particular that this one will Isn't it all these, even the Isn't it all these, even the Isn't it all these, even the money can be spent, there is no problem in the question, money can be spent, there is no problem in the question, if there will be repeated if there will be repeated work here, that is, if I saw for the punch, work here, that is, if I saw for the punch, then I will also see for three separately, so then I will also see for three separately, so what will happen in the root four technique? what will happen in the root four technique? All the rows and columns of it will be All the rows and columns of it will be cleared because cleared because tell me the time complexity because now we are doing repeated work tell me the time complexity because now we are doing repeated work here, so what is the here, so what is the way to avoid it, one way is that we know that way to avoid it, one way is that we know that Pacific Ocean here means topic and left Pacific Ocean here means topic and left side. side. side. money will go to every corner. Talking about hair, right and bottom go to the Atlantic Ocean. Okay, so one thing we can do is to do it with DFS. You can also do this, You can also do this, You can also do this, for now I am telling you the method of DFS for now I am telling you the method of DFS so that we can also look at the question once again so that we can also look at the question once again that if we go from top to bottom, will we be able to reach the Atlantic? Talking about hair, if we go above the Atlantic, it means that we should we be able to reach the Atlantic? Talking about hair, if we go above the Atlantic, it means that we should not do this to people like three punches. not do this to people like three punches. not do this to people like three punches. go to one and go to Atlantic, we have to move backwards, how to move backwards? Look, if the one in front is bigger, it means it will be bigger or then can we go to three, because then can we go to three, because three is bigger than one, so we are taking the opposite case. three is bigger than one, so we are taking the opposite case. three is bigger than one, so we are taking the opposite case. is, we will not go out from inside, we will come in from outside, then if our water can flow inside and can flow at any place, it will mean that the money in question will also go to some other column If water also If water also If water also flows on the same row column then flows on the same row column then it will become our common and we will it will become our common and we will take that common in our answer. Okay, so we will keep in mind take that common in our answer. Okay, so we will keep in mind that give greater and equal tu that give greater and equal tu case will work i.e. N one will not work if we go case will work i.e. N one will not work if we go outside. outside. outside. we will do once is that we will hold the first floor and look at all these columns, come down from the Pacific Ocean and do the same in the bottom one and then Okay, so this Okay, so this Okay, so this was our question and you must have understood, let's was our question and you must have understood, let's come to the answer, so this answer is basically accepted and I have also submitted it, okay just do it now, so I thought it is visible, okay, the submission If we tell you that If we tell you that If we tell you that in this question I mean in this question I mean easy, then it would seem that Han Bhai, it is easy, so we have taken easy, then it would seem that Han Bhai, it is easy, so we have taken more columns for each day, the length of the front more columns for each day, the length of the front is the length of height, I will look at it in the description only, is the length of height, I will look at it in the description only, it must be visible in the figure. it must be visible in the figure. it must be visible in the figure. initial height will be whatever its length will be and what will be the height for the column, we will take the height of zero, I have already told you this many times, how If If If there is a punch, then we will there is a punch, then we will take two sets. take two sets. Okay, keep this thing in mind because we Okay, keep this thing in mind because we know that it should not be repeated again and again, so if there is know that it should not be repeated again and again, so if there is already value inside the set, then it already value inside the set, then it is okay and finally, which will be the output which will be our answer. is okay and finally, which will be the output which will be our answer. Let's take it as empty, Let's take it as empty, then we will end the app in it, later we are then we will end the app in it, later we are defining the DFS, okay, defining the DFS, okay, it has four parameters, first row column is it has four parameters, first row column is from office, third is visit set, I have done this many times, from office, third is visit set, I have done this many times, previous problems. previous problems. I take the visit set to see if the I take the visit set to see if the visitors we have already visited are visitors we have already visited are not reaching that place before and each previous not reaching that place before and each previous site means this was necessary, why was it necessary site means this was necessary, why was it necessary because we know that the previous one matters that if the that if the that if the only then water will flow from the next one, same thing here, this one condition will return nothing, why see, if our row problem is already present in the visit, Look Look Look brother, our row columns are less than zero, brother, our row columns are less than zero, this is our equal tu equal tu, when it goes this is our equal tu equal tu, when it goes out of bounds, if equal tu out of bounds, if equal tu give greater then we will let it reach, equal give greater then we will let it reach, equal tu itself got caught in row and column, if equal tu itself got caught in row and column, if equal tu is there i.e. tu is there i.e. tu is there i.e. seen, it is one less than zero, then if it is behind or ahead of zero, it means there is a problem or there is another case that if our height has been taken, it is okay, then do It is written that it is flowing below or see it like this, it is happening above the floor, wherever the flow is happening, just see that the height of the raw column should not be small, it should be It will be possible to come It will be possible to come It will be possible to come inside, it is okay and if it is our case, that is, all these cases are false cases, then return nothing, we will not do anything for them, if it is not so then Our row and column will be added to the visit set and Our row and column will be added to the visit set and we will run this operation on that row and column, we will run this operation on that row and column, do DFS four times, okay, you do DFS four times, okay, you can do it by taking a loop, but there is can do it by taking a loop, but there is no problem in doing it like this, up, down, right, left, no problem in doing it like this, up, down, right, left, okay, then you okay, then you okay, then you did the same thing one by one and add all the parameters initial, we will add the same row and column to this one because it was there, right, now we ran this loop, first for C For whom did we first For whom did we first For whom did we first run 'C' in the range column, run 'C' in the range column, we took it as zero, 'Row' we took it as 'zero' we took it as zero, 'Row' we took it as 'zero' i.e. which row is ours, which is the first row, this i.e. which row is ours, which is the first row, this money was also questioned, 'Who is the first row?', we money was also questioned, 'Who is the first row?', we took this row and the column will keep changing. took this row and the column will keep changing. That is, we are going to reduce the different columns to these five columns. We are going to That is, we are going to reduce the different columns to these five columns. We are going to start from the first of start from the first of all and from the side of the row too, we will all and from the side of the row too, we will enter from the bottom, right? Which enter from the bottom, right? Which will be the last row, row minus one, so here punch one, all these will be the last row, row minus one, so here punch one, all these columns. columns. columns. go up, first of all, we know that money also comes from above, so we have taken it, and whatever will be the height of zero, this also has to be written here. this also has to be written here. No, this also has to be written here, it No, this also has to be written here, it is okay because our Roman Reigns van will is okay because our Roman Reigns van will remain the same, the column will keep changing, remain the same, the column will keep changing, if we look at it from the Atlantic question, the rest if we look at it from the Atlantic question, the rest is the same, only what is below here is the Atlantic Ocean, is the same, only what is below here is the Atlantic Ocean, P means money is also a question, P means money is also a question, we have the column in Talking about RAW. we have the column in Talking about RAW. we have the column in Talking about RAW. that is, we talk about the first column and if we talk about the last column, then the column will remain fixed in it, so the initial first column was zero, the last column column will become minus one, the cases were above from and the first one was Okay, this headline is fine, Okay, this headline is fine, Okay, this headline is fine, so we have divided these two, so we have divided these two, we have checked which we have checked which one will go in the Pacific, which one will go in the Atlantic, one will go in the Pacific, which one will go in the Atlantic, now what to do is that the final look which is ours is now what to do is that the final look which is ours is actually its time complexity, you of M * actually its time complexity, you of M * actually its time complexity, you of M * and it is also present in Atlantic. If you and it is also present in Atlantic. If you want then adopt it in the answer. If you had want then adopt it in the answer. If you had taken the answer from our first then it would have made a list of taken the answer from our first then it would have made a list of lists. This was our small lists. This was our small code, now I must have understood it and I will also give its link in the description and I will also give its link in the description and we are very close, I have we are very close, I have given it in the play list to solve it | 2024-03-22 11:00:15 | 417 | Leetcode 417. Pacific Atlantic Water Flow. Python (Dfs Graph) |
|
480vrbuUmes | okay cool 942 di strain match given a string s that only contains I or D that string s that only contains I or D that n is to go the length of the string we n is to go the length of the string we turn any permutation a of just some way turn any permutation a of just some way such that for or I guess suffice you can such that for or I guess suffice you can add and well yeah a survival item it 10 add and well yeah a survival item it 10 the next car gets bigger if not then if the next car gets bigger if not then if it's teeth and it's smaller okay and it's teeth and it's smaller okay and they all have to be between 0 and n and they all have to be between 0 and n and 10,000 okay and I suspect it's some sort 10,000 okay and I suspect it's some sort of query haven't we had a deal at the of query haven't we had a deal at the end for example ITV then this asked such end for example ITV then this asked such as for and it career maybe okay nothing it's just greedy wait you just you have numbers from the top and the bottom or over them or fun and the end and I just kind of keep adding them Topanga we gonna die with D that's my guess and then playing out of it we took a hit who i mr. tenets matter what number I guess Hawaii man mr. Lipscombe no that's fine I think that should be called to say you finally learned how to use this tip you finally learned how to use this tip thing you just click on it I actually thing you just click on it I actually did another know that for a couple did another know that for a couple months so you made laughs I'm laughing months so you made laughs I'm laughing so that's right oh cool let's go for it cool uh okay well I don't think I'd take you late my thoughts on this one very well to be honest I just kind of went for a couple of things but I guess most of it most of what I thought was just that and some of that is kind of matter to be honest which is a little unfortunate in that like if your day with this is medium maybe I would have thought a little bit harder about how greedy could be wrong maybe yeah so I don't know if I kind of have like better cheated that way that makes sense I think some of that was like because it's easy that's one and then you look at the constrained and is your ten thousand so you know it's come here Fabio and maybe I'll n log n but like just doesn't seem like an N log n type form but maybe some kind of longest increasing subsequence I think then again not again but again it's easy so so I figured probably oh it's over bent and it's kind of weird that so much of this is kind of a little bit matter e but so what that is greedy I just figured like well I don't know how I came upon it to be honest I just thought well it's greedy there may be on every decreasing then you know that you want the three years big as possible because then it doesn't matter what the sequence is like because if it's increasing you take the smallest number then you could essentially ignore it from the rest of sequence where like almost like almost like a recursive e thing type thing where you chop like just sub the sub sequence will be also good so I think that's you start why the greedy works and I'm kind of proving it fish probably now but uh for example you'll get the same answer offset by one number if we take the substring which is just tid and so forth I think that's how I kind of have an intuition for it and I mean if I wasn't into me life I would try to explain that a little bit better why would it be very slow in an interview because I think I wouldn't have excuse me cuz I I also knew that this would take like I don't know I'm minted to write so that I could kind of test my hypothesis really quickly I was just like trying to prove everything for which I'm an interview you know I wanted to do that and have to be confident about you and it's until like you really surprised him when you're like yeah actually yeah I mean I've I had a rant about in greedy solutions on interview qualms before and this is kind of I don't think this is an exception I mean some that is that what the code is pretty sure it's a you know it's not in enough like and it helps disproportionate what people have seen how I describe it but it's like a real how I describe it but it's like a real like maybe like curve and that's you're like maybe like curve and that's you're really confident we're like the puke oh really confident we're like the puke oh very good and already erasing this very good and already erasing this problem they would get weight quickly problem they would get weight quickly and the people cooler maybe not as and the people cooler maybe not as strong but doesn't know anything strong but doesn't know anything you know like they only believe in you know like they only believe in greedy or like you know they believe in greedy or like you know they believe in greedy so they just some way the greedy greedy so they just some way the greedy solution and hope that's why we're oh solution and hope that's why we're oh yeah I need to read up what that means yeah I need to read up what that means but I feel like for me like for me and but I feel like for me like for me and maybe other people where my skill level maybe other people where my skill level which is a lot I think the thing is that which is a lot I think the thing is that like I feel like every time I do I like I feel like every time I do I assume something is greedy I get burned assume something is greedy I get burned like I'm like oh actually now it's like I'm like oh actually now it's dynamic programming in so and so dynamic programming in so and so therefore like every time I I see therefore like every time I I see something that I think it's greed I'm something that I think it's greed I'm like very suspicious and then it like very suspicious and then it actually takes me longer than someone actually takes me longer than someone who might not you know think it's who might not you know think it's dynamic programming so I don't know that dynamic programming so I don't know that makes sense that's my logic anyway makes sense that's my logic anyway oh yeah yeah I mean I think yeah you oh yeah yeah I mean I think yeah you just have to prove to was it called just just have to prove to was it called just you know fair I feel like I am NOT maybe you know fair I feel like I am NOT maybe that's just one of my weakness maybe I that's just one of my weakness maybe I should practice that should practice that but but that's harder to practice but but that's harder to practice sometimes because like I look at a list sometimes because like I look at a list of greedy solutions then I just know of greedy solutions then I just know it's greedy like greedy prompt that no it's greedy like greedy prompt that no is greedy so then it's hard to contest is greedy so then it's hard to contest with that we're like dynamic program for with that we're like dynamic program for example I could still practice it example I could still practice it because knowing something is a dynamic because knowing something is a dynamic programming solution it's not good programming solution it's not good enough you still have to figure how to enough you still have to figure how to you know how to draw the dependencies you know how to draw the dependencies right for example and how to program it right for example and how to program it if you will in the right order if you will in the right order which is also like not the same family which is also like not the same family problem problem oh yeah I don't have your viruses in oh yeah I don't have your viruses in your impression I think I hope that uh your impression I think I hope that uh uh I eventually get about get disease in uh I eventually get about get disease in question did I feel like this is also question did I feel like this is also one of those farms where like yeah ok one of those farms where like yeah ok you saw me and I did in a couple of you saw me and I did in a couple of minutes per like you give me another day minutes per like you give me another day where I don't know maybe I ate is over where I don't know maybe I ate is over too much for lunch and maybe a little too much for lunch and maybe a little bit you know less optimal for and maybe bit you know less optimal for and maybe I just don't get it and that's something I just don't get it and that's something that I'm aware of of myself which is a that I'm aware of of myself which is a little unfortunate but but um yeah but little unfortunate but but um yeah but they're still using a lot of people like they're still using a lot of people like it so maybe there's a easy discussion it so maybe there's a easy discussion greedy thing yeah good all right cool I greedy thing yeah good all right cool I think that I'm gonna say about that one think that I'm gonna say about that one so you know well and like it's like five so you know well and like it's like five lines of code so there's really not much lines of code so there's really not much to clean up the code and also I forgot to clean up the code and also I forgot to talk about complexity which is to talk about complexity which is clearly off and and uh and in terms of clearly off and and uh and in terms of return space because that's outfit return space because that's outfit sensitive so you have to be on event so sensitive so you have to be on event so you can do better than that but all one you can do better than that but all one extra space on top of the output extra space on top of the output sensitive complexity | 2024-03-25 11:59:04 | 942 | 942. DI String Match (Leetcode Easy) |
|
R6RddNeX3ug | Hello friends, welcome to the new video, question number 22 Let's generate code for question number 22 Let's generate code for parents, this is a medium level question, this is a parents, this is a medium level question, this is a question about backtracking, you question about backtracking, you people will find this question on the internet, it has been people will find this question on the internet, it has been asked in Facebook and Microsoft, let's start with the asked in Facebook and Microsoft, let's start with the right function to generate all right function to generate all combinations. combinations. combinations. places, what does it mean? You would have got 12345. Anything can happen. According to that, you have to generate all the combinations of value formed parents. Let us understand this question in detail. Let's see the example. N. Anything can happen. 12345 N. If there is one, you can use an open racket, you can If there is one, you can use an open racket, you can If there is one, you can use an open racket, you can use a project and create value from use a project and create value from different places, your different places, your two is two, you can use open rapid or you two is two, you can use open rapid or you can use it for employment and can use it for employment and create value from parents, MP3 is so. create value from parents, MP3 is so. can also reduce Jatin and in all the can also reduce Jatin and in all the ways value is created from paralysis, if you have ways value is created from paralysis, if you have made it pure, then keep one of yours open, made it pure, then keep one of yours open, use a glass of it and you have use a glass of it and you have made welcome friends, if it is Pattu, made welcome friends, if it is Pattu, then yours. then yours. then yours. brackets and you have seen two ways value can be created from parents, you have given three, use three open rackets, use three close back ends and you have seen five ways value can be created from princess. So some observations will have to be made in this, the first observation is that if you have an entry then use your three open rackets, use three close ends, then the length of the string which is ours will be six. Okay, one more observation will have to be made in this, as many parents as these are important. All those who are starting are generating, they are starting with open racket. Okay, so let's take an example. Let's take two of them and after generating, we will see how the parents will be generated. Okay, so there are some rules in this. Vansh, all these are just different, Vansh, all these are just different, Vansh, all these are just different, it is starting with open racket, it is it is starting with open racket, it is okay but now you neither have a decision, you have okay but now you neither have a decision, you have two choices, now you can use open racket also, you two choices, now you can use open racket also, you can also use it, just first of all you have to can also use it, just first of all you have to start with open. start with open. start with open. now you can play open rapid and you can also play close racket, okay but for how long you have to play open racket, there will be some limit, somewhere we will stop, if we take some examples then for If N If N If N is our two then we can hit two open rackets and is our two then we can hit two open rackets and cannot hit more than that, then one more cannot hit more than that, then one more condition is coming that as long as your open racket is condition is coming that as long as your open racket is less than the van, keep hitting it as it will be less than the van, keep hitting it as it will be equal to inches, there we will stop. equal to inches, there we will stop. Because we are Because we are Guru, after opening it, we will get two, so we will Guru, after opening it, we will get two, so we will stop till it is less, let's put it, okay, stop till it is less, let's put it, okay, so we are going to do it, we are going to keep it open on the left side and put the employees back on the right side and so that the sequence is put the employees back on the right side and so that the sequence is maintained. maintained. maintained. left side will be kept open and the class will be held on the right side, so let's start so you have put the open racket on the left side, okay, you have put your closed back on the right side, okay now we will explore the left branch, The choice is the The choice is the The choice is the decision. Open racket will be placed on the left side. If you decision. Open racket will be placed on the left side. If you look at the right side, look at the right side, can an open racket be placed? Already, if you have already can an open racket be placed? Already, if you have already placed two apane rakhegi, then the open racket placed two apane rakhegi, then the open racket cannot be placed on the top. This branch has cannot be placed on the top. This branch has crossed ours and we are ahead of this one. crossed ours and we are ahead of this one. crossed ours and we are ahead of this one. now we have to put a clothes rack on the right side, so can it take time to close or can it take rolls because right now the close rack is less than our open rack, keep it open, we had two, so we So right now it is not such a big issue, So right now it is not such a big issue, So right now it is not such a big issue, but we have to see one more condition but we have to see one more condition that if we have more closed rackets then it is that if we have more closed rackets then it is okay for us not to put extras, then okay for us not to put extras, then we should always have less closed rackets than open rackets, till then we should always have less closed rackets than open rackets, till then you keep putting more like you keep putting more like open rackets and open rackets and open rackets and then you stop, okay then let's add one more role that the project will run continuously till the time it is less than the open racket and as the close and open become equal then we will understand that now we are not planning the project. Okay, now let's do more exploration and we will see that the left side is crossed and there are two stars in the right branch. Okay, and the left side has to be fitted with an open racket, the right side is closed racket, so an open racket cannot be fitted. You have already Yes, Yes, Yes, okay, let's cross here okay, let's cross here and on the right side we will put a close bracket, so and on the right side we will put a close bracket, so can we put a close racket, now we have a can we put a close racket, now we have a closed back side, we have one and open rackets, we have closed back side, we have one and open rackets, we have two, so close, but we also have less, so we two, so close, but we also have less, so we can put a close begum. can put a close begum. can put a close begum. equal but at that time we could have estimated that our projects were less. Okay, now let's do Explorer again and from this point also we have Arpan 201. Okay, what are we going to do on the left, it will take us 15 minutes Secondly, if you want to bowl then first Secondly, if you want to bowl then first Secondly, if you want to bowl then first try open rapid. You cannot bowl with open batting. Can try open rapid. You cannot bowl with open batting. Can you bowl daily while sitting? you bowl daily while sitting? If you bowl after seeing you, then the If you bowl after seeing you, then the close rackets will be extra for you. If close rackets will be extra for you. If our condition is fulfilled, then close Beckham our condition is fulfilled, then close Beckham cannot bowl. cannot bowl. cannot bowl. cannot explain further, so we will go back and then we will explore that now we will ignore from this point, the decision is on this point, we can apply it by opening the left side and you can go and apply it on the right side. So you will see that the open racket is still in use, so we have installed the open racket, there is no issue and if you have installed the closed back, then you will see that the clothes rack will be our extra. Okay, the closed back door is the open racket. There was a close, There was a close, There was a close, so now if you put a close rack in the right branch, so now if you put a close rack in the right branch, then the clothes rack will then the clothes rack will become your extra, so we cannot put a close back here. become your extra, so we cannot put a close back here. Okay, what are you going to do, Okay, what are you going to do, now the right branch has crossed now the right branch has crossed and follow the left branch. and follow the left branch. and follow the left branch. too there is 244 on the left side, what do you have to do if you want to put an open racket, then you will see that there are already two open rackets, so you cannot put an open racket, well, a closed racket can be put in this, everyday our racket may seem that If it is then we If it is then we If it is then we will put it close madam will put it close madam and you will become equal to us every day. Okay, and you will become equal to us every day. Okay, now you will see that we now you will see that we cannot do the explorer from the left branch, we have got the juice, we can ignore it from the right branch, so cannot do the explorer from the left branch, we have got the juice, we can ignore it from the right branch, so if you if you put the open racket then you will see that we will keep it open already. put the open racket then you will see that we will keep it open already. put the open racket then you will see that we will keep it open already. two then you cannot put open rack and you will see that if you put close desktop then you will become extra in close rapid action. If there are two open rackets then they will become mud and if you cannot put even close wicket then you will see that you will not have any branch. So we have generated it, So we have generated it, So we have generated it, we have to pay attention to some roles, we have to pay attention to some roles, these are our basic rules, these are our basic rules, we can generate them by following them, okay, so let's we can generate them by following them, okay, so let's come to the code and let's see how we will code it. All the come to the code and let's see how we will code it. All the parents that are going to be generated are the ones that parents that are going to be generated are the ones that we have. we have. we have. then we create a list, we name that list as is ok is ok and finally we return this list, it and finally we return this list, it is ok in the end, so will is ok in the end, so will you write a recursive function and all the you write a recursive function and all the you write a recursive function and all the generate benefit parents then we keep giving some name to this function, find all name is Dev and what all you will pass in it, we had discussed about this, I have to start with open racket and what will happen to me if I don't What has to be done is how many opens have been placed, how many What has to be done is how many opens have been placed, how many What has to be done is how many opens have been placed, how many closes are there, so I say one closes are there, so I say one open has been placed and one close will not be placed, okay open has been placed and one close will not be placed, okay and we have to pass this list also because we will save it and we have to pass this list also because we will save it in it, okay and we in it, okay and we will pass this MB because we know. will pass this MB because we know. will pass this MB because we know. that how many open rackets are to be kept and how many closes are to be put. Okay, so now let's write the recursive function once. In this, you will first pass your spring. Let's name it current. Okay, A. Open racket, how many is his account, close is Baikuntha, how many is his We will have to pass this list of ours, We will have to pass this list of ours, We will have to pass this list of ours, okay and okay and how many open and how many closes we will be in it, and the information given to us how many open and how many closes we will be in it, and the information given to us in the pen is also passed. Okay, the in the pen is also passed. Okay, the code for this is simple. As you have seen, code for this is simple. As you have seen, those conditions will be there, the first condition was gone. those conditions will be there, the first condition was gone. How many open rackets do you have to put after opening? How many open rackets do you have to put after opening? If you have given us our dough then If you have given us our dough then you cannot put more than two open rackets. Okay, if you you cannot put more than two open rackets. Okay, if you sit open and put them, then how to do this in the village, let's sit open and put them, then how to do this in the village, let's make a call. Record nipple, then you will make a call. Record nipple, then you will add open rackets. add open rackets. add open rackets. you will make your bread in whatever skin is given to you, okay, and you will say that the account of open has increased, you will not increase the account of clause, and there is nothing to be The The The closed bracket that we have done should be less than our open racket, till then closed bracket that we have done should be less than our open racket, till then you sit and keep playing every day you sit and keep playing every day and as soon as it becomes equal and stop, we had also and as soon as it becomes equal and stop, we had also discussed this, so here if you play closed racket, then discussed this, so here if you play closed racket, then now one of the Clauses Act. now one of the Clauses Act. now one of the Clauses Act. increase the account then we will keep knowing how many projects have been started by us, so this is the doubt code, you will see that all will be generated but we have not saved it anywhere, how will we save it? Well, if I say generate, then if my end is two, then generate is only one. Bed also and half come, then it was being generated like this, then some of it was also being generated, if it was generated in different ways, then finally our length of and of was also being generated, which was finally our length If it was, do If it was, do If it was, do you have to save these small ones as well you have to save these small ones as well or you must have kept only the but only one of yours, if or you must have kept only the but only one of yours, if you have to save only the land for, then we do you have to save only the land for, then we do n't have to save all the small ones, n't have to save all the small ones, what will we do with this, we keep adding to our string. what will we do with this, we keep adding to our string. what will we do with this, we keep adding to our string. much as our string is going to be created in the recursive function, then we will say that when its length becomes ours, I will end it with 'to', this means if I have given 'to', then I will say basically, its length will be ' Only then would you like to save me or if it Only then would you like to save me or if it Only then would you like to save me or if it was my house then I would say was my house then I would say Strickland, if it gets stuck, set the Strickland, if it gets stuck, set the phone only then will you ever save it and what will you phone only then will you ever save it and what will you do, you will add it to the list of results, okay, okay, add it to it. add it to it. add it to it. anything else, then our job is done. Lastly, here you can do one thing, if you want that we do not want to explore further, then you can stop here now because we have already got the length and time, further length will be So you will go to the automatic So you will go to the automatic So you will go to the automatic route, you can also return it yourself, route, you can also return it yourself, okay, then you should run it once and see, okay, then you should run it once and see, I accept and I accept and submit, okay, you will see this successfully submitted, there You can access my channel by You can access my channel by You can access my channel by going to the About section of this Google Sheet, going to the About section of this Google Sheet, in this you can directly see in this you can directly see which interview questions' which interview questions' videos I have made, which list videos I have made, which list questions' videos I have made, you questions' videos I have made, you can see them category wise and can see them category wise and can directly reach the questions. can directly reach the questions. can directly reach the questions. you can see whether you have a date, what is the next video coming, thank you very much for watching this video and do it [Music] | 2024-03-19 17:18:23 | 22 | Generate Parentheses (Leetcode 22) - Medium |
|
msPHbO9qx3E | hey what's up guys this is chung here again again so so this time let's take a look at today's daily challenge problem number 902 numbers at most any given digit set so this is a very interesting hard problem because this is more like it's related to the digits and it also asks you to use the dp concept to solve it with dj for for the digits so with dj for for the digits so that's kind of unusual all right so you're given like you're given into an array of of digits and you can use you can use any digits as many times as you want and you can write though you can write them in any sequence the only cons the only constraint is that you need to find the mean the numbers you write has to be equal or smaller than the target than this integer n here and it it asks you to return the number of positive integers that can be generated right the total the total number of positive integers that can be generated given this digits array here right who which whose value is equal or smaller than the n here and there are some examples here so the first one like the example the 20 here right we have sorry we have a 100 equal is a target and we have four digits here and then we uh we have 20 total possible numbers whose value is smaller than 100 okay and here we have yeah i mean this one is pretty big that's why i mean similar but we have a much bigger output here right so on so forth yeah and here are some constraints here all right so given these two parameters how can we approach this problem right so i mean to solve this problem we have to think it in the in we have to split this problem into us into several small some some different scenarios so the first scenario is what the first scenario is that you know as long as the total numbers as you guys can see so the numbers could be from from one let's say the uh no let me change this one to big end here okay and then we have a since we're going to uh i'm going to have a string equals to a string dot n right and then i'm going to have n equals the length length of the so let's assume let's say we have a the so let's assume let's say we have a the total target total target digit is and the length is n so digit is and the length is n so from 1 to n minus one from 1 to n minus one right oh by the way and the uh the digits is from one to nine so which means that we don't need to worry about the leading zeros okay so anything anything should be a valid digits okay so okay back to here so assuming so let's say the total length of this target is so which means that from 1 to n minus 1 we can use any number for each for each of the digits let's say the n is equal to four so which means that so the length from length one to from for length one two and three we can use any digits on each of the digits right so which means that what so let's say the the digit is this four is this fourth so with all the length equals to one so with all the length equals to one right what right what how many options how many digits options how many options how many digits options we have we have we have four here right right because we have four here right right because we can put either of any of these we can put either of any of these numbers numbers at this one digit that's why we we have at this one digit that's why we we have four four how about the two here so let's say we how about the two here so let's say we have we have two digits have we have two digits and when we can use any freely use any and when we can use any freely use any of the digits that's why we have a of the digits that's why we have a 2 to the power sorry 4 to the power of 2 to the power sorry 4 to the power of two two so because on each digits we have four so because on each digits we have four options and since we have two total options and since we have two total two digits that's why we have four times two digits that's why we have four times four four same thing for three four to the power same thing for three four to the power of three of three okay so that's the uh that's the uh the the easy case where uh whose length is smaller than than the than the n right and so i'm going to write that real quick here so since i will just talk about that you know so for that you know what we have we have a let's say we have an answer equal to zero and then we have four i in range of i'll just remove this this part here so in range to what one to n right so this is from one to n minus one basically you know and the answer is what the answer is like the uh the the digits right so let's define the the the digits right so let's define the length of digits length of digits digits i i'll just call the digits in digits i i'll just call the digits in here here so it's going to be the length of digits so here we have the length of digits that's the length smaller that's the length smaller than than n right cool so that's that that's the easy case and the more difficult part is the when that when the for that we have to consider the for that we have to consider the answers digit by digit so what what do i answers digit by digit so what what do i what what does it mean it means that what what does it mean it means that let's say let's say the target assuming the n is like the target assuming the n is like 2 4 6 2 4 6 7 8. so this is the end 7 8. so this is the end right and so what i mean by consider the digits uh one by one which means i'm so for this one i'm going we need to define like a dp here so the dpi means that you know from from ice digits to from ice digits to end digits from ice digits to end to end digits from ice digits to end to end digits like what is the like what is the what is the total total positive numbers what is the total total positive numbers integers by given these digits whose value is smaller than this part let's say we have a this is i let's say this is i and the dp means that from from the current i's location to the end what is the total what is the total [Music] count for the for the positive integers whose value is less okay and to calculate that okay and to calculate that we have to there are like two cases we have to there are like two cases actually there are three actually there are three three cases so the first case is like three cases so the first case is like this this i mean basically we will try each of the i mean basically we will try each of the digits here right so digits here right so at this location this is n right so this at this location this is n right so this is is and so we're basically we're going to and so we're basically we're going to try each of the digits try each of the digits so when we compare with the current the so when we compare with the current the current digits of this end here current digits of this end here and basically there are three three and basically there are three three cases right scenarios cases right scenarios either the current digit is greater than either the current digit is greater than is smaller than is smaller than than this one or equal than this one or than this one or equal than this one or greater than this one so whenever let's say the digits let's say the current digits is is smaller smaller than six let's say the current digit is two right so what does it mean it means that assuming the current digit is it is two it means that we can freely put any digits on on these two right so which means that we can right so which means that we can like use the uh we can just use like use the uh we can just use use this formula to calculate this case use this formula to calculate this case which is going to be the uh which is going to be the uh the length of the digits to the power of the length of the digits to the power of in this case is two yeah but we're gonna in this case is two yeah but we're gonna have like the uh have like the uh uh so it's gonna be a n minus uh so it's gonna be a n minus i plus 1 something like that so that's i plus 1 something like that so that's the first scenario where the the first scenario where the the current digit is smaller than the the current digit is smaller than the six six right because since this one is smaller right because since this one is smaller than this so we it doesn't really matter than this so we it doesn't really matter what we have what we have here so that's the first case right so here so that's the first case right so that's the and the second case that's the and the second case is equal it's 6 is equal to this one is equal it's 6 is equal to this one so whenever the dj is the same as this so whenever the dj is the same as this one one so what do we have we have so what do we have we have basically we we cannot basically we we cannot freely put anything we can we can freely put anything we can we can we cannot freely put any numbers here we cannot freely put any numbers here but it happens to be that you know but it happens to be that you know since this one the same so it happens to since this one the same so it happens to be the dpi be the dpi so the dpi will becomes what will become so the dpi will becomes what will become the dp the dp i plus one right because the dpi plus one is the the total valid count starting from here which is exactly the the equal case for us because then what because whatever we have in dpi minus one it will be the same in this dpi here right because the c because the current digits is the same so we we're are on the uh on the on on the dpi plus one to tell us how many valid numbers we we have and the third scenario is like it's it's eight let's say for example is eight so when that when it's 8 of course it's a this is an invalid case because this it's already this 8 is already greater than the 6 7 8 is greater than 6 which means that there's no there's no more digits right that can start start with eight that can satisfy our condition here and yeah i know we just keep going backwards as you guys can see here because the so the the difference for this dp is that we have to going from from from going backwards from the end to the start because the uh from the current digits we have to rely on the uh on the on our digits on the right side and in the end when we're at zero we will have and when we have it at 0 the dp 0 will give us the total the total count right for the for the length who's for the for the numbers whose length is equal to the are the same as this length here and then we just need to accumulate that summarize that with this answer cool so and cool so and all right so let me try to code this all right so let me try to code this part so now part so now handle the handle the length equal length equal to n right so like i said we need to to n right so like i said we need to have like a dp here you know have like a dp here you know at the beginning the dp they're all at the beginning the dp they're all zero because we're storing the uh zero because we're storing the uh the valid the valid count right starting the valid the valid count right starting from here to this is from i to n and for i in range of the n minus one and for i in range of the n minus one minus one minus one right like i said minus one minus one right like i said we need to start from the end and we try we need to start from the end and we try each of the digits each of the digits right because we have we have to try it right because we have we have to try it because for each digit we have a because for each digit we have a different different scenarios here for each digit in digits scenarios here for each digit in digits so the first case is if the digits is so the first case is if the digits is smaller than the uh smaller than the uh then the n string then the n string [Music] [Music] dot i right so if dot i right so if if the current one is smaller we can if the current one is smaller we can just just accumulate we have to use digits accumulate we have to use digits and to the power of up this one similar and to the power of up this one similar like this one but we have to like this one but we have to calculate what's the remaining digits calculate what's the remaining digits right right so the remaining digits is n minus i so the remaining digits is n minus i minus one okay because the the n is the minus one okay because the the n is the length and the i is the the index length and the i is the the index that's why we have to also do a minus that's why we have to also do a minus one to get the one to get the the remaining number of digits okay the remaining number of digits okay and so for the remaining digits we can and so for the remaining digits we can freely use any of the freely use any of the digits right all right that's that so digits right all right that's that so else if right i'll see if the else if right i'll see if the digit is equal to the and digit is equal to the and string i so in this case like i said string i so in this case like i said the uh the the value will be the same as the dp i plus one okay because the the current one is the same and we have to just use whatever we have from dpi plus one and then in the end we can simply return the dp0 right and then plus the answer because the dp 0 will stores the total total result for the length that's equal and actually here there's like small and actually here there's like small corner case edge cases we need to corner case edge cases we need to be careful because we're starting from n be careful because we're starting from n minus one and we uh minus one and we uh some we will do a dpi plus one you know some we will do a dpi plus one you know so if the i is equal to n minus 1 and if so if the i is equal to n minus 1 and if we do an we do an i plus 1 it will be out of the i plus 1 it will be out of the boundaries so that's why boundaries so that's why we can just simply do a check if the i we can just simply do a check if the i we we only do a dpi my i plus 1 if the i we we only do a dpi my i plus 1 if the i is smaller than n minus one right is smaller than n minus one right else else is just one the the dj is the same as the the the dj is the same as the two four six seven eight where the uh two four six seven eight where the uh this is the this is the digits the first it is and the current digits the first it is and the current dj is eight which is the same as this dj is eight which is the same as this one one which means that it will be plus one which means that it will be plus one right that's the right that's the that's one that's one count yeah or we can just do a padding here you know instead of initialize it to n here we can do a n plus one and then we set the last element okay so i think that's it let's try to okay so i think that's it let's try to run the code here run the code here okay accept it submit all right cool so it passed yeah so the time complexity right so the yeah so the time complexity right so the time time complexity is the uh so the digit size is n and this one is so the digit size is n and this one is 10 to the power of nine but we're 10 to the power of nine but we're getting so actually the getting so actually the the time complex is only the length of the time complex is only the length of the length of this n which is the uh the length of this n which is the uh what i think the length is a lot it's what i think the length is a lot it's log n right so that's the length log n right so that's the length the length of the this end here and we the length of the this end here and we have a have a we have a for loop of the length here we have a for loop of the length here and another for loop of this one and another for loop of this one so the and the digits here is yeah so so the and the digits here is yeah so this it's only a constant right so it's this it's only a constant right so it's bounded so bounded so here we have up to nine that's why the here we have up to nine that's why the uh uh the total time complex is still the the total time complex is still the length of this length of this which is which is the uh the log n yeah and the space complex says same thing because we have a dp here that's why the uh the space complex is also o of all right so just to recap right i mean so for this kind of like digits related problem you know the uh it's always i think it almost always will relate to uh to comparing the current digits because the uh especially when you need to compare if the digits is smaller than target or greater than the target so based on the current digits the you you will have different options like what we have here so in our case i mean we we calculate the easiest scenario first which is the uh the length which is smaller than the target than the n here which means that we can freely use any of the digits on each on any of uh any of the numbers on any of the digits that's why we have this total numbers and then we'll use like a dp to help us accumulate the case where the length is the same as the n here so for this case we have to use we have to we have to loop through each of the digits because based on the based on who is bigger and who is smaller with the current digits we will have a different accumula we have a different accumulated account here right for the so for the dj which is smaller than the uh then the current then the card numbers right we can just freely put anything on the next few numbers and the reason we're using the dp here is only for the for this case for the case when the djs when the digit is the same as the uh as the as a current as a current number in this case we have to use the the count that we stored in the in the previous dp which is the dpi plus one and of course for the for the last case which we can simply ignore that and then in the end we simply uh just add two values together and that will be our final yeah i think this is a very interesting yeah i think this is a very interesting tp it's not like a traditional dp tp it's not like a traditional dp or this is just like a dp with the or this is just like a dp with the digits i hope you guys digits i hope you guys enjoy watching this video and i'll just enjoy watching this video and i'll just stop here stop here okay thank you so much for you guys to okay thank you so much for you guys to watch it and watch it and stay tuned see you guys soon stay tuned see you guys soon bye | 2024-03-25 10:20:07 | 902 | LeetCode 902. Numbers At Most N Given Digit Set |
|
fyW59LQFknc | hi my name is david today we're going to do number 1408 do number 1408 string matching in array this is an easy string matching in array this is an easy level problem on lead code and we're level problem on lead code and we're going to solve it in javascript going to solve it in javascript so the prop is we're giving an so the prop is we're giving an array of string an array of strings here array of string an array of strings here and we want to return all the strings in and we want to return all the strings in words this input which is a substring words this input which is a substring of any other word in any order so for of any other word in any order so for this one this one we have this array of words and we can we have this array of words and we can see see s is in mass so we would return as hero s is in mass so we would return as hero is within superheroes to return hero and is within superheroes to return hero and none of us is within anything else none of us is within anything else so that's all we return so so that's all we return so what we need to do first since it's what we need to do first since it's asking us to return an array we asking us to return an array we create a new variable for this so create a new variable for this so first thing create output array and that's going to hold the output we need next one so we're going to have to loop through this but we know that the order matters so we don't want to repeat like mass can't be an ass but as can be a mass so we want to sort it from ascending length so sort words to ascending length so now we got that we can loop through words and inside this we have to create a nested loop so so we compare this word to other words okay and inside of this nested loop we will check create condition if the current word is in in the nested word so we know that so be in order for the small words will be in the bigger word and if it is we will have to current word to current word to output and then output and then we don't want to get any repeat of it so we don't want to get any repeat of it so we can break we can break and then after that we return and then after that we return output okay so let's get started that output okay so let's get started that output equals empty array and now we output equals empty array and now we sort their words sort their words so words dot sort so words dot sort a and b from length a and b from length a dot length minus b dot length okay so we got this word sorted out now we do the loop no or let i equal zero i or let i equal zero i is less than words dot length is less than words dot length i plus plus and now inside that we i plus plus and now inside that we do the second loop for let j equals do the second loop for let j equals i plus one j i plus one j is less than words dot length is less than words dot length j plus plus and now we have to check if j plus plus and now we have to check if it's inside of each other it's inside of each other so if the second word the nestor word words dot j words index i words index i we know we have to push it output we know we have to push it output dot push words dot push words index i and we don't want any repeats so index i and we don't want any repeats so we break we break now at the end of this we return output now at the end of this we return output great now let's check yeah so we got it so the complexities since we're doing a nested loop we have to do o and the space complexity we know that we are creating an output array that is going to be big as the words and that is how you solve this problem and that is how you solve this problem thank you | 2024-03-21 01:13:09 | 1,408 | How to Solve "1408 String Matching in an Array" on LeetCode? - Javascript |
|
EbF3TJsobD0 | Guys Welcome To Dad Sales Today's Question Is When To Remove At Intervals In This Question Which Will Stop Intervals Where To Remove All Intervals Baithak Covered Boy In The Interval Hindi List Interval A Copy Squad And Interval Scene nickel to have and beat them nickel to have and beat them nickel to have and beat them equality of doing so better equality of doing so better returns in number of revenue intervals so let's understand this question example see in this list 2001 14821 and form a which vacancy date 144 entry ko monthly share and not getting kabaddi head to comedy Intervals And 361 And Se Interval Between Intervals And 361 And Se Interval Between Intervals And 361 And Se Interval Between No That In The Interval 2.3 Thomas No That In The Interval 2.3 Thomas Equal To President Should Seek Cover In Trouble Equal To President Should Seek Cover In Trouble Due To Remove This Possible Because It's Already Present Hindi Enter Enter The Stock Market Will Remove The Terrible And Stock Market Will Remove The Terrible And Will Determine The Original Avoid A That Are Yaar please forgive the monkey and * Kamat in sea vacancy Bittu ko mat is already been recovered in this son of Sudhir son of two Gomti Chakra interval Supreme Lord to remove the two Gomti swimming interview will be given for evil returns one and discuss in Eleventh Eleventh Eleventh Vacancy Back Cover Interviews For Comment Vacancy Back Cover Interviews For Comment Because In The World And For Whom The Also Exists As Because In The World And For Whom The Also Exists As President Internal President Internal Video Me Enter To Remove This Is Ki Video Me Enter To Remove This Is Ki Beti Mumbai Central And Eastern The Beti Mumbai Central And Eastern The Evening Answer Sudesh The Question Not Look At Evening Answer Sudesh The Question Not Look At You Approach Now This Question See The Question You Approach Now This Question See The Question Is Very Simple But Powerful But You To The Is Very Simple But Powerful But You To The First Governor General Lord Vishnu With This First Governor General Lord Vishnu With This Time The Will Not Listen That Time The Will Not Listen That Ascending Order Basis Of This Time Ascending Order Basis Of This Time Swift Filmy One Comes For Due To Come Again Welcome A Ko Bhi To Achhi To At All Don't Forget Shri Comedy Been Converted Into Comedy Been Converted Into Comedy Been Converted Into Prominence Software Update Vihar Metro Prominence Software Update Vihar Metro City Code For Selected As The Best Cadet City Code For Selected As The Best Cadet But Will Do If If Vector Interwar 2004 But Will Do If If Vector Interwar 2004 Interwar Se Z Not The Least Not And Up Interwar Se Z Not The Least Not And Up Resident Evil Returns Roti Interval Dot Resident Evil Returns Roti Interval Dot Size Size 100 200 300 Now They Are In This Case your program will reach willow dip condition your program will reach willow dip condition daily date are you dare devil at least consist of only once interval difficult ishwar interval once interval difficult ishwar interval dominar account will be one delhi switch possible between dominar account will be one delhi switch possible between sudhir will take into account sudhir will take into account equal to one will celebrate with one because equal to one will celebrate with one because no data is no data is no data is interested in this is not equal to be road will be at least one big brother will be at least one interval which will be novel and covering all the intervals sir counter affidavit start noida delhi yesterday to start the doctor in twitter hindi Descending Time Slot Will Do Descending Time Slot Will Do Descending Time Slot Will Do War Custom Pattern Discuss The Co Mute The Custom Batter Let's First Ride The Custom Batter A Ki Dot And Lag Cinema Custom Address Computer Only A Ki Doctor It's Right Custom Computer CC Bullet Return Max Batter Hai This Function This Function This Function And Arguments Every Passing RJ Devi And Arguments Every Passing RJ Devi Digambar Jain Bittu Intervals Interval And This Digambar Jain Bittu Intervals Interval And This Interval Correction 11015 Home Twitter To A Interval Correction 11015 Home Twitter To A Hint Hint That We President And 1 And Similarly Vectors Secretary Also In Temples And Being's Name Mirch A Budhi Person Handed Sa time Sa time Sa time it is very starting from scene in the it is very starting from scene in the world who will choose backed music values world who will choose backed music values and intimate scene after 10 minutes with oo started and intimate scene after 10 minutes with oo started consuming it means in this study consuming it means in this study shot the short intervals basic course in shot the short intervals basic course in descending order of the pending time and descending order of the pending time and acid notification 90 Student Video Member Custom Meeting 90 Student Video Member Custom Meeting Buddhi Typing Same Will Soften Desi Beat Buddhi Typing Same Will Soften Desi Beat And In Time And Descending Order And Will And In Time And Descending Order And Will Start From Not Sample Spontaneous And Wore This Start From Not Sample Spontaneous And Wore This Time He Zerre Zerre Customer Time He Zerre Zerre Customer Nobody Does Not The Length Of Nobody Does Not The Length Of Withdrawal Not The Least Point And Updated On Ki Point And Updated On Ki Intervals 108 Sisters Of Indies Equal Intervals 108 Sisters Of Indies Equal To One And Will Be Equal To A Ki To One And Will Be Equal To A Ki Intervals 201 Schedule Bad Intervar 09 Values In This Thought And Daddy Ki If Parameters For Comparing Date Bhi And And And Fourth Inter Intervals Not Recovered So Start And Fourth Inter Intervals Not Recovered So Start And Don't Topic-Special Starting And Don't Don't Topic-Special Starting And Don't Refer 2011 To Forgive And Beautiful Look At Some Thing If Refer 2011 To Forgive And Beautiful Look At Some Thing If One Dos Sexual Internet One Dos Sexual Internet Sites That I Plus Plus That Boat Also Chilly One See When No One Will Caused By Caused By Caused By The Interval This Is The World And Beat It For The Interval This Is The World And Beat It For Intervals Of House Intervals Of House 90 Is Greater Than Or Equal To Start And 90 Is Greater Than Or Equal To Start And Intervals Are Now High Command Is Less Nikalti And Bismil Thc Basic Double A Particular And Intellect Which Were Standing Right Now Is Subha Will Do Nothing Else Subha Will Do Nothing Else Subha Will Do Nothing Else Continue Select Features Example Suppose Continue Select Features Example Suppose Beneficial In The Form Of Karo Beneficial In The Form Of Karo Ko Support Other Initial E Ko Support Other Initial E On Karo Ko Support His Father And Sleep With Only Two Intervals Vinod Idea Music Jasmine Ko Batukamma And Some Interesting And Starting Start Value Start Value zero-valued is zero-valued is possible Withdrawal Is Cover Inner Being Converted Into This Withdrawal Is Cover Inner Being Converted Into This World Will Continue Till And Vitamin World Will Continue Till And Vitamin C E O Tomorrow Morning Minute Sorted Vikram One News Main Nachu Aaj 12th Class Which One Oo A Time In Charges One And Will Be Influenced By 4 Wickets Starting And Will represent the starting point of time and in order for the interval 9 loop start from this induced into middle travel frilly and they are not hidden video start intervals of the position of video start intervals of the position of kar underworld don this is not kar underworld don this is not kar underworld don this is not Naav Badodiya Statement Will Update U End Will Updater End Value Will Update First Vikram Minimum of Current 100 Interval Ki Ko Ma 0 Under End Will Earthquake Ki Intervals I Ko Ma One I Ki Intervals I Ko Ma One I Anil V Account Plus This Anil V Account Plus This Anil V Account Plus This Now It's One And Internal From His Position Not Valid This Is Not Valid Notes Will Start At The Starting Of Wave 2K's A And B Coming Maximum Thicker Maximum A And B Coming Maximum Thicker Maximum More Current Current End And Depending Valley Of More Current Current End And Depending Valley Of Depending Value Of The Depending Value Of The Current Current Current maximum is 800 vidmate no stop this one end edit sukhbir wa veervar ko subscribe intervals not only for oo hua hai aur yash infaday buddhist 69000 note khabar sunao notification hai front swasth that has been updated and has been nominated for justice One and short and jaipur plus veervansh hai necklaces done so far account current account is to 9 international bluetooth next election 2013 ko masik again for this condition researcher at intervals of asbestos setting bull icon interval this great and start getting s301 disciple condition and position of this Current Interval So If End This Year subscribe this Video plz subscribe Shravan Underwear Continues at Doing All This Step Will Be Found Accordant Travel and Will Return Account Government Delhi Has To Do So Will Return To Only In This Case Fast Track Court Of This Question Demonetization Code Number One Thing To Note Here That Even In Another Class 10th Class Admit Due To Be Used A Way That To Record Your Help Won's And A Way That To Record Your Help Won's And Accepted Aayog Ne Jo Lagi To Video Thank Accepted Aayog Ne Jo Lagi To Video Thank You | 2024-03-20 10:37:54 | 1,288 | Remove Covered Intervals Leetcode | Leetcode 1288 | Leetcode october challenge |
|
aZuQXkO0-XA | That fans festival, the question above has been asked by taking minimum squares, you will get your number, you have to question above has been asked by taking minimum squares, you will get your number, you have to tell in how many minimum tell in how many minimum number of squares you number of squares you can represent it, what does this mean, can represent it, what does this mean, like if there is a note, then one like if there is a note, then one can get pregnant by smelling only one number. can get pregnant by smelling only one number. can get pregnant by smelling only one number. answer will be like disgusting two because I can appoint as both how many numbers can I subscribe and what is the minimum number I can subscribe like it is war the difference for 17 is 4 like this subscribe So while talking on four numbers, So while talking on four numbers, So while talking on four numbers, subscribe and then subscribe and then subscribe, if not at all, then subscribe, if not at all, then tell me, I am 10 and 506 tell me, I am 10 and 506 and signing the meaning on an index, I and signing the meaning on an index, I give you, I have set it, so according to me, I How many of my phone numbers How many of my phone numbers How many of my phone numbers can be made clean? You can start there can be made clean? You can start there but this is a completely different and opposite way. Let's but this is a completely different and opposite way. Let's try a new way to source. Zero on robbers cannot be specified for any number, meaning no other number will be included in it. One number is deposited from the campaign of one, this number can be presented as 108. Now I will do one age option above but on behalf of this Vada village, it can be said that from here, from here and from here, how many will you get? Day, you could have said minimum from there, from here we see this here, inside I have seven square, you have number 11, from number 11 and you keep it aside, now here we have put the value 251 more and there is If there is more, then If there is more, then If there is more, then remove it here, see if subscribe remove it here, see if subscribe and the remaining 22 numbers are one plus one, I feel and the remaining 22 numbers are one plus one, I feel that I have some problem here, that I have some problem here, look at this, now from inside the phone, I have an option, but let me Do Do Do tell me, it is free, that three becomes that pressure, tell me, it is free, that three becomes that pressure, okay, then 30 to 14, one option, four numbers will okay, then 30 to 14, one option, four numbers will be taken, Sanskrit decisions on 1000 saved in 24, be taken, Sanskrit decisions on 1000 saved in 24, what is the second option, what is the second option, this is MS Word, sure that you have a cartoon on it, this is MS Word, sure that you have a cartoon on it, each other's total is 40. each other's total is 40. each other's total is 40. number, this happened in real life, so we were in the past vs. Braun, the answer to the previous birth came to us, we will start off here that my mom will be made from this tree of one numbers, this time of any one, now half of it 1015 Special Thermal Officer, I am getting four numbers here. It seems that number 212 can also be check-in. I got a little late here too, it does not seem different. The stuff should have been a little clear on this number. Wherever the If I take out the name 'Open Squash' If I take out the name 'Open Squash' If I take out the name 'Open Squash' then I went with the thoughts, take out one named 'Three or then I went with the thoughts, take out one named 'Three or Two Speed', 'Neech Zero', you know the Two Speed', 'Neech Zero', you know the definition, it takes 3 from here, definition, it takes 3 from here, see this in this way, Subscribe 1510, see this in this way, Subscribe 1510, nothing takes place, from here, from here, from here, nothing takes place, from here, from here, from here, 3000. 3000. 3000. here I also agree that there can be problems. Now see, one of the pipe pipes is that if you take it then put it once, beyond that it is fine, one is all done. 10 to 12 stances from the shop. Seven Seven Seven in 25, at what time does a pig's tooth in 25, at what time does a pig's tooth stop breaking, four by four, so friends, stop breaking, four by four, so friends, come now to the next time, come now to the next time, Hello viewers, welcome to two square Hello viewers, welcome to two square cartoon, so I have reached here, it cartoon, so I have reached here, it goes further, one plus one, this is only one thing, I goes further, one plus one, this is only one thing, I don't understand it. don't understand it. don't understand it. man, you play supervisor, you have an ideological child, now this four one reaches zero in one step, it is a broken puja shop, it is written and there is a chapter on 100, it is the champion square root, so Till it's all both have Till it's all both have Till it's all both have one it's also present don't go on the other one it's also present don't go on the other one sir it's all in opposition to forest Shiva one sir it's all in opposition to forest Shiva and delicious ok so 102 in that you have and delicious ok so 102 in that you have purse from two and 2017 way does from 12 purse from two and 2017 way does from 12 someone like is the same thing someone like is the same thing someone like is the same thing say that we did darkness and the other one went, shut the other's tail, okay, 12 is a matter of understanding, as if only one understands, now let's move on to teaching interest, plus 2 If it If it If it happens then either take it out on it, okay now happens then either take it out on it, okay now see, I take it out, so come friends, we can see, I take it out, so come friends, we can use the enemy, we can use two, then ours will be able to come, use the enemy, we can use two, then ours will be able to come, how much is the tubeless minister, how much is the tubeless minister, an important one for 12 2012, two an important one for 12 2012, two can be subscribed, so either subscribe to subscribe as if he hates subscribe to subscribe as if he hates subscribe to subscribe to I have set one thing and got the place. I have set one thing and got the place. Okay, now let's do it together, look carefully. If it is a Okay, now let's do it together, look carefully. If it is a marital relationship, then this one marital relationship, then this one is cheaper than doing it. Either put it behind this is cheaper than doing it. Either put it behind this or this one. Meaning if there is war then Meaning if there is war then I can do 101 or do I have importance I can do 101 or do I have importance here there is a clear winner subscribe toe Abe if I here there is a clear winner subscribe toe Abe if I talk about name then vansh and to sarkar has talk about name then vansh and to sarkar has reached here this trees near cartoon reached here this trees near cartoon so I will reach here so I will reach here E want to were with high school in this way so E want to were with high school in this way so that three are theirs, from here they feel scared, from that three are theirs, from here they feel scared, from here they seem to be Hindu, if we had made it if we did here they seem to be Hindu, if we had made it if we did not pay attention then 1222 from here, they seem to be friends, not pay attention then 1222 from here, they seem to be friends, from here there could be another candidate, from here there could be another candidate, so minimum this so minimum this so minimum this and here Dot Cervi is the smallest leaf thing to get a job. Okay, tankers use water, so make sure to put a cross here in the lineage, I will use this, so I am there Minimum Minimum Minimum one on 1341, which became OnePlus one two, still in the one on 1341, which became OnePlus one two, still in the last 10 minutes with spoon turmeric, we last 10 minutes with spoon turmeric, we subscribe the channel, subscribe the channel, subscribe the channel, subscribe the channel, ok, we would have complained 101 from here too, ok, we would have complained 101 from here too, half the body is a woman till the time she subscribes, half the body is a woman till the time she subscribes, but do all this. but do all this. that I have made a horror movie comedy new that I have made a horror movie comedy new cent and plus one [ cent and plus one [ music] music] 1000 hoti aur dp of wave hoti 1000 hoti aur dp of wave hoti ki ab point is quiet ushe oil dainik ki ab point is quiet ushe oil dainik urdu and sculptural aaoonga urdu and sculptural aaoonga hai and beech mein chalega look dega gas stove hai and beech mein chalega look dega gas stove From the band and how far did it come that J*Jain has got this From the band and how far did it come that J*Jain has got this letter published letter published in which both of them are running like Sochle Khol I in which both of them are running like Sochle Khol I No Clue in Haryana, it is 1052 400 and it will run in such a way that whichever you keep it smaller, run in such a way that whichever you keep it smaller, it will keep increasing or it will increase. it will keep increasing or it will increase. it will keep increasing or it will increase. that we can go to this post by subscribing and finding the minimum. Int mean equal to two will be included. Put in it the daughter value meaning of how much is the remaining. Come - Jeetu ji. Okay, if you are a great leader, then by combining one and removing the other, you will remove the other The job has reached the morning place, there is The job has reached the morning place, there is The job has reached the morning place, there is only deep only deep meaning in this list, if you subscribe, then in the next two days, make it plus one medium and next two days, make it plus one medium and my dear friend, enemy, why will it take hard work, my dear friend, enemy, why will it take hard work, everything is yours and you have everything is yours and you have taken one but Ujjain. taken one but Ujjain. taken one but Ujjain. we will return, BP will see them from here, submit this chapter and write submit this chapter and write that it is done, the said leaders will understand, let's that it is done, the said leaders will understand, let's meet in the question, thank you. | 2024-03-22 14:00:04 | 279 | Perfect Squares Dynamic Programming | Leetcode 279 Solution in JAVA |
|
Bxgq2ILCsfQ | Hello friends, welcome to Day 8 of 990 Days SC Prep. This is the first question of Lead Code 75. This is the first question of Lead Code 75. Lead Code 1768 Merge Strings. Lead Code 1768 Merge Strings. Alternatively, I have made such an idea that Alternatively, I have made such an idea that I will make separate videos for each question and on I will make separate videos for each question and on Sunday I will do a live one for which Sunday I will do a live one for which Sunday I will do a live one for which can talk to me and if you have any doubt then they can be resolved. Okay then lead code is 1768 Merge Strings Alternatively I will show you the question, this is the question, you have been given two words, it is an easy Easy Easy Easy question I think lead code has also tagged it as easy. Two strings have been given to you and you have to create a long string by merging both of them alternately. Ok, create a long string by merging both of them alternately. Ok, very easy question. It is very easy. very easy question. It is very easy. Pick up the character, then pick up that, then Pick up the character, then pick up that, then pick up that, then pick up that, this is how we have to pick up that, then pick up that, this is how we have to pick up the characters, if one string ends then we have to append the pick up the characters, if one string ends then we have to append the other one, so other one, so like I discuss in some examples, let us have like I discuss in some examples, let us have a string, I have a. a string, I have a. a string, I have a. C and the second string is D FG H I. So how to make the answer we have to make? Picked A from the first string and put it in the answer. Then we have to pick D, then pick D, then pick b, then pick e, then Then F has to be raised and now there is nothing Then F has to be raised and now there is nothing Then F has to be raised and now there is nothing left at the top, so G A I has to be raised from the bottom, then left at the top, so G A I has to be raised from the bottom, then look at look at A then D then B then E then C then F A B A then D then B then E then C then F A B AD B CA Okay and then in the last when A is AD B CA Okay and then in the last when A is finished. finished. finished. for this I told you what I did, I used my merge to sorted sort trick. If you look carefully, I used the same trick. So let us say As Se D B G H I K M Okay, so I put a pointer here, I put a pointer here, okay and created a string builder, I will append from the string builder and placed a flag which will keep on being true false true false so in the beginning that flag If that flag is true then if it If that flag is true then if it If that flag is true then if it is true then I will pick the character from word one. is true then I will pick the character from word one. If it is false then I will pick the character from word two. If it is false then I will pick the character from word two. So I picked the first character from here, picked a, then appended a in the string builder then appended a in the string builder and increased it from where it was picked by a. and increased it from where it was picked by a. and increased it from where it was picked by a. index, I moved it forward, index ok and flag falls, this flag falls, now the flag falls, so I will pick it up from word two, I pick it up from word two, so I picked up D, consumed it here Made true, Made true, Made true, see flag is equal to not, flag is true see flag is equal to not, flag is true then it will be false, if false then it will then it will be false, if false then it will be true, now flag because if it is true, then be true, now flag because if it is true, then I I will go to word one. If flag is true, then I will go to word one. From word one, I will will go to word one. If flag is true, then I will go to word one. From word one, I will pick B. pick B. pick B. increased the index and toggled the flag. Now the bag is false, so I will go to word two, so I have G here, wherever it is at this time, like it is standing on B, so B has been consumed. B has been consumed. Next. Increased the index and toggled the flag. Now if the flag is true then C is consumed from word one. Increased the index and toggled the flag. Now if the flag is false then G is consumed from the word below. Increased the index and If the flag If the flag If the flag is true then I consume D from the top word is true then I consume D from the top word and increase the index and and increase the index and toggle it. If the flag is false then I consume it from below. toggle it. If the flag is false then I consume it from below. I consume A and I consume A and increase the index and make the flag true. By making the increase the index and make the flag true. By making the flag true when I flag true when I flag true when I know that the upper string is finished, then I just put the lower loop and consumed I, K and A, so as long as I will keep I will keep I will keep consuming it. If one string is consuming it. If one string is finished, I will finished, I will completely consume the other string. So bring me its code. I will completely consume the other string. So bring me its code. I will write it in front of you. So it is simple. write it in front of you. So it is simple. I have I have made a string builder. Why do I have to make a string builder? If you made a string builder. Why do I have to make a string builder? If you add it to the string then it will be ok. add it to the string then it will be ok. add it to the string then it will be ok. in the loop. Look in the loop. An addition is made of O in the string. If you add it in the loop, then O will become square. In the string builder, the one that is appended is of Ov, so Kept Kept Kept which will rotate on Word Two as long as both are which will rotate on Word Two as long as both are within their limits, Aa has not gone out of Word One within their limits, Aa has not gone out of Word One and H has not gone out of Word Two. and H has not gone out of Word Two. Okay, so S is true, this could have been done through questions and other Okay, so S is true, this could have been done through questions and other methods also, methods also, why did I do it like this because why did I do it like this because Just like this, I thought of this Just like this, I thought of this strategy, everyone knows the story of merge to merge array, strategy, everyone knows the story of merge to merge array, okay, so I thought of it, so I okay, so I thought of it, so I used it, I kept one used it, I kept one flag equal to true, which I will keep toggling every time, flag equal to true, which I will keep toggling every time, flag equal to not. Flag So now if I think carefully if the flag is true then I have to consume from word one else I have to consume from word two how will it be consumed String builder d append wave ka aa and the one Let's increase it Let's increase it Let's increase it otherwise if the flag falls then otherwise if the flag falls then I will consume from word two. From word I will consume from word two. From word two we consume with the help of J two we consume with the help of J and increase J only. Okay so sometimes aa is increasing, sometimes and increase J only. Okay so sometimes aa is increasing, sometimes j is increasing and sometimes i is j is increasing and sometimes i is increasing. increasing. increasing. come when one of these two will end? Our heat will continue only as long as both are there, one will end, one will end, so what will I do? I will put such a loop, Do you know whether I is over Do you know whether I is over Do you know whether I is over or J is over? Okay, so I will or J is over? Okay, so I will put a loop of both. Look, I don't know put a loop of both. Look, I don't know whether I is over or J is over. The whether I is over or J is over. The loop above Let Us is over because I loop above Let Us is over because I was over. was over. was over. If they If they come out of this loop, then I have written the loops of both below. If the come out of this loop, then I have written the loops of both below. If the upper loop is finished due to aa, upper loop is finished due to aa, then the loop above aa will not go down. then the loop above aa will not go down. still left, the one still left, the one below will work, the one below will work, if the one will below will work, the one below will work, if the one will not work, then there is nothing to be done in it, not work, then there is nothing to be done in it, now there is no question of flag, now now there is no question of flag, now we just have to consume without any decision, so we we just have to consume without any decision, so we just consumed it from I and inside it just consumed it from I and inside it Only word two was consumed with the help of J, l was Only word two was consumed with the help of J, l was written and returned in the last. If you written and returned in the last. If you think about the complexity, then see that the length of the complex think about the complexity, then see that the length of the complex one is one is o n and the length of word two is m, so the total time o n and the length of word two is m, so the total time complexity is n + m n + m. complexity is n + m n + m. complexity is n + m n + m. you think of the crosses of all three weil loops, if we think of the crosses of all three weil loops, then this string has also been completed and this string has also been completed, so the weil loops are coming one after the other, so the j has moved, it has j has moved, it has j has moved, it has moved across the length of both the strings, moved across the length of both the strings, time complex T is n + m, time complex T is n + m, if there is any doubt on this then you can ask me live, if there is any doubt on this then you can ask me live, I think there will be no doubt on this, I think there will be no doubt on this, ok before going I mean ok before going I mean put two important links in the description. You can use both of them. One put two important links in the description. You can use both of them. One link is for you to journal your progress with me. link is for you to journal your progress with me. I have put its link and the I have put its link and the other one is Sklar School of Technology. other one is Sklar School of Technology. If you have any younger brother or sister, then If you have any younger brother or sister, then I am using this link. I am using this link. I am using this link. Time Sna Scale School of Technology. Why is the child so amazing? Look, we are studying in a college. We have to find time for ourselves away from that college. Is it possible for anyone to study computer science in youtube4, now what is there in SST? What is good about SST is that in the curriculum, within the curriculum of your college, there was 50% CS, 50% was non-CS, there is 100% CS in its curriculum, the Bangalore, the instructors you had in the Bangalore, the instructors you had in the Bangalore, the instructors you had in the college were those PhD people, do you college were those PhD people, do you know who are the instructors here micronavdisha.com No infact the session has just started, the first year students went and played in ACM IPC, while the rest were When the When the When the first year team from SST is going to first year team from SST is going to play regionals, the culture has play regionals, the culture has become a culture of code chef, hacker, rank etc. from day one, it is full of become a culture of code chef, hacker, rank etc. from day one, it is full of hacker attitude and finally the very hacker attitude and finally the very amazing thing is that the promoters amazing thing is that the promoters are there. are there. are there. and Sequoia and Tiger are Global, there are 110 unicorns in the country, out of 110 110 they have invested money in 60 of them, so when they have founder retreats etc., then all the founders of the unicorns meet among themselves, If we meet, she is soaking in all the news till here, If we meet, she is soaking in all the news till here, If we meet, she is soaking in all the news till here, so I think that is why this is so I think that is why this is one of the best places to be. one of the best places to be. I will put the link in the description. I will put the link in the description. If you have a younger brother or sister, then If you have a younger brother or sister, then you can apply through that link. you can apply through that link. you can apply through that link. you can also message me if you want to apply you can message me I have a coupon code so the application fee will also be reduced so you let me know all right let's meet in the next video thank you so much | 2024-03-22 12:47:52 | 1,768 | Leetcode 1768 | Merge Strings Alternately | 1st out of LC 75 | Prepare for SE Role in 90 days |
|
rt5C1eoFnqg | what happened here was that there was a complete area of our own and inside it there were two problems, if you understand it as yours, then one was that you have to make everyone else's, it is okay to make Find it, it's okay, both of them were our own problems if you consider them as probability, but now it can be a small integer or reduce it by one, leave this entire year, No, this is No, this is No, this is all of four sizes, we have converted it into 2 sizes, it all of four sizes, we have converted it into 2 sizes, it is okay, we have converted till now, now think is okay, we have converted till now, now think what can be in the size, give your answer okay, what can be in the size, give your answer okay, further you and I think, now further you and I think, now a common thing will come out here, what if. a common thing will come out here, what if. This element of yours is fine, if it is A This element of yours is fine, if it is A in both of these, that if in both of these, that if A is present in both of them, then it is always being formed. Now think about it, this is a small element, Now think about it, this is a small element, because of this. because of this. because of this. game is changing, so now what happened here is that if you clear your mind, first of all, you have to leave in the morning and first of all, take minimum leave from it, look at the specific minimum of your priority and If you try then it will become yours. If you try then it will become yours. If you try then it will become yours. Okay, okay, those who do Okay, okay, those who do not understand the problem, there is not understand the problem, there is no need to take tension. First of all, you are going to no need to take tension. First of all, you are going to understand very easily understand very easily what is trying to be said by this question, after that we will what is trying to be said by this question, after that we will make an appointment and end. make an appointment and end. make an appointment and end. Implementation is ok so look here let's understand well what happened here that there is some error in it, ok there is some competition in that area and the final result is This is This is okay, now this three and one cheat foot okay, now this three and one cheat foot is also our sabar, now tell me, what is the minimum in it, turn remove all these, and after that too, there is minimum and and after that too, there is minimum and and after that too, there is minimum and go out, you will have to travel in it, otherwise no, now growth is not coming to your mind right away, nothing is coming to your mind right away, right away, nothing is coming to your mind right away, DP graph please DP graph please back tracking, there is nothing, okay said, what question do you have and You have to go out, turn it upside down, it is leave it, okay, whatever leave it, okay, whatever different logic is trying to come into your mind, you are different logic is trying to come into your mind, you are looking at them as to looking at them as to how they can be yours, okay, how they can be yours, okay, tell me one thing, it is Have you understood? Han, Have you understood? Han, Have you understood? Han, okay, tell me one thing, from where to here, from here to here, there was nothing in this too, first take a single, after that was nothing in this too, first take a single, after that you will definitely get involved, you will definitely get involved, okay, but when I come from here, what will happen, so [Music] Ki agar three van tu four hai, it is okay and in this whole thing, if you are considering your van, it is okay, if you are considering your van, then which one will you take as a minimum, only one van will you take, it is okay, If you want to take the body, then what are you thinking of can eat it yourself, right, it is okay, there is such a small presunt of the left hand, it will always be such a small presunt of the left hand, it will always be made. clear that Yeh Jo Tu Hai will come first on the left side. absolutely correct. Well, what absolutely correct. Well, what is the one on the left? If the one on the left is small, will four come again? Is the is the one on the left? If the one on the left is small, will four come again? Is the matter clear? Do you understand what you did? If it is added to the group, then how many can be made and if the one on the right is added If it happens then how much can be added, If it happens then how much can be added, If it happens then how much can be added, if the rider is not your own, if you if the rider is not your own, if you make the light ones, then tell me 4, make the light ones, then tell me 4, how many in the rate, if there is not even one in the right of four, how many in the rate, if there is not even one in the right of four, then just take this man of yours, only one then just take this man of yours, only one can make his own group, can make his own group, right. can he come in the first group, come, then there is no problem in all, come, then there is no problem in all, but make the minimum element [Music] how much will he okay, how much will you come in this? okay, how much will you come in this? How many times is the bullet about you going to come, let's look at the bullet How many times is the bullet about you going to come, let's look at the bullet once, it is clear, I have understood it, there is no problem, I have understood it, I clear, I have understood it, there is no problem, I have understood it, I just understood this approach, this approach immediately just understood this approach, this approach immediately came to our mind, see it, it came to our mind, see it, it needs a lot of practice. needs a lot of practice. needs a lot of practice. is okay there, it will take a lot of practice when you start getting clear on your own, then it is left of it, there is a bigger present than this, there is a left of it, there is a bigger present than this, there is a smaller present, it is good for you, okay, this is the four. okay, this is the four. okay, this is the four. smaller than the same, smaller than the same, then it is not the same. Similarity is elements will be done, then it is fine for van. You have to complete the number which is on its left. Look, where does a smaller number than this exist on its left? now what you have to do first is to now what you have to do first is to write to them first, it if you try to code yourself, it if you try to code yourself, it is not too difficult, just try once. is not too difficult, just try once. is not too difficult, just try once. you do this then you will forget it, then if there is any problem later, then your own people are now what happened that your own people are the first to now what happened that your own people are the first to come in the size of the error, so again and again Android and how small are they. how small are they. how small are they. can it come and how long can it come once on the right, okay now what have you done at the time of initialization, you have initialized everything in the left, All are small All are small All are small on the left and all are big on the right. on the left and all are big on the right. Normally, what did you do that you gave it a sun base case because it is not possible that it will be a mines van because one of its own will definitely now there are Have you always had sex? Have you always had sex? Have you always had sex? Okay, so try to call whatever little knowledge you have. Okay, so try to call whatever little knowledge you have. Okay, Okay, definite answer. Okay, now it's three. definite answer. Okay, now it's three. What did you say when you left three? So What did you say when you left three? So what have you taken till now? Youngest Sansad again. what have you taken till now? Youngest Sansad again. what have you taken till now? Youngest Sansad again. smaller than that and the van till is the smallest one, okay, which one is the smallest one till now, the which one is the smallest one till now, the latest one, latest one, tell me, calculate it, then you will know that there are calculate it, then you will know that there are four smaller ones in between. four smaller ones in between. four smaller ones in between. like four, where are our three, that is smaller than this, what did Han say, become, that is smaller than three, okay then it is smaller than 13, so remove the three, okay There was no one else and any leader There was no one else and any leader There was no one else and any leader is fine, only this one is existing, so is fine, only this one is existing, so till now what did you understand that if this one till now what did you understand that if this one exists, then even give him whatever size he is, exists, then even give him whatever size he is, he will remain the smallest among all, that is he will remain the smallest among all, that is correct. correct. tell me three and what is its index, no problem because your no problem because your answer is in it, you had made a factor named left in the left, similarly, the whole question of yours is on the right. similarly, the whole question of yours is on the right. similarly, the whole question of yours is on the right. gone, you do looking like multiply and keep adding six to it, looking like multiply and keep adding six to it, no problem, please open and return, okay then your look is gone, I have made the total, okay, what did you do in that, Got it done, okay, Got it done, okay, Got it done, okay, now what is this percentage module? Percentage is the now what is this percentage module? Percentage is the pearl that this answer is, it could have been quite big, pearl that this answer is, it could have been quite big, so the question of mine, I had said earlier so the question of mine, I had said earlier that we have to give it by reminding, with whom are we, that we have to give it by reminding, with whom are we, with this Modi, is with this Modi, is it okay? it okay? it okay? should not be any problem, after that, you have multiplied it, then what did you say after multiplying, now it has been multiplied, left and right, look here, left is right, is okay. add on done inside it, is the multiply add on done inside it, is the multiply product done, three is ok, then now when it is calculated, will six come, then that six will be equal, no problem, finally got the whole thing returned to the calculator, I hope you understand it well. Still if there is any doubt then submit the comment box, you have run, it was yours, submit is done, run, it was yours, submit is done, ok thank you. | 2024-03-25 10:34:53 | 907 | 907 || Sum of Subarray Minimums || Leetcode Daily Challenge |
|
PBcnF4jpRTA | three foreign three four so the sensor one is [Music] is is this means | 2024-03-22 18:00:04 | 1,826 | 1826 Faulty Sensor #leecode |
|
ZG2ZYd7U03s | question and it is really easy but generally in phone interview or in online assessment sometimes an easy question is asked then one of them is ok straight line here it has not been asked by amazon Let's look at it, it is very simple, Let's look at it, it is very simple, Let's look at it, it is very simple, you must have given the coordinates, you you must have given the coordinates, you must have given us the coordinates, you must have given must have given us the coordinates, you must have given two things in each, X A two things in each, X A coordinate, okay, so you have to tell coordinate, okay, so you have to tell that these points make a straight line in that these points make a straight line in D X, all the points which D X, all the points which D X, all the points which If there are If there are two points then find out its slope. What will be its code net? Let's take So far it is clear, a very simple property of mathematics, what will we do with it that when there is any straight line, then pick up any two points in the straight line, pick up any two points, I picked up this, then Whichever slope will be there, let's take Whichever slope will be there, let's take Whichever slope will be there, let's take it and pick up another one and then extract it from it. it and pick up another one and then extract it from it. Okay, so what do we do here Let me Let me pick three points, first of all, okay, fix it, what will I do first, mother, take everyone's slope, I will take it from this, okay, everyone's slope will be taken from the first point, that is, the We have taken out three We have taken out three We have taken out three comma four, one comma tu's stop, comma four, one comma tu's stop, if it is from slope, then it means we will if it is from slope, then it means we will be in a straight line. If everyone is ok, then be in a straight line. If everyone is ok, then first let's take out 3 - 2. You see, we are first let's take out 3 - 2. You see, we are taking out taking out x2 - x1 from this. Is this? correct, see, both are equal also 3 - 2 correct, see, both are equal also 3 - 2 1 will become 2 - 1 will become Will this one go This one will go 1 will become 2 - 1 will become Will this one go This one will go My one This one will go my one Look here 4 - 2 / Both the cuts will be Both the cuts will be Both the cuts will be 1/1. Both are equal. Okay, 1/1. Both are equal. Okay, now it is clear. Just pay attention to one small thing. now it is clear. Just pay attention to one small thing. We We generally tell you to stress on this thing in the interview generally tell you to stress on this thing in the interview that you should that you should show yourself how to find the corner. Now think for yourself. show yourself how to find the corner. Now think for yourself. Here we take a zero in the denominator, so now your code will get denominator, so now your code will get fat, division by zero is fat, division by zero is okay, for that you can make it simple like this too. okay, for that you can make it simple like this too. okay, for that you can make it simple like this too. 3 - 2 * 3 - 1 cross multiply, take this there, take this so see, what I will do is just simple, so see, what I will do is just simple, first two, I am going by the mother of all, first two, I am going by the mother of all, I will come out of this, okay all. I will come out of this, okay all. I will come out of this, okay all. these two. Okay, remember, see what will happen. We will take out x2 - what will happen. We will take out x2 - Sir, 3 - 2 will become 1. Sir, 3 - 2 will become 1. What will happen is x2 - Okay, so what is this brother, what is its delta delta Delta A Delta A multiplied by this one, isn't it, you are great, you are equal, It is from this point that the It is from this point that the It is from this point that the slope that is being created by meeting this point is slope that is being created by meeting this point is not equal. Okay, so at this time we will not equal. Okay, so at this time we will say that brother, by meeting all these points, it is say that brother, by meeting all these points, it is definitely not making a straight line. Okay, it definitely not making a straight line. Okay, it was a very simple question. was a very simple question. was a very simple question. very simple way, we are just putting the same thing, first of all, here I have calculated what is its size, let's go with that, okay, our example is fine, so first of all, You comma 3 You comma 3 You comma 3 to 1 2, what will be the A of A, let's write it like this, okay look which are the coordinates brother, the one with index y2 - y1 is okay, what is the A of this brother, this one is not three, so here it will be 1, okay y2 - y1 This is done y2 and its y2 - y1 This is done y2 and its y2 - y1 This is done y2 and its first one is first one is clear till now my clear till now my y2 - y1 music] start with and start with and everyone's slope will come out with this zero index. Okay, I's everyone's slope will come out with this zero index. Okay, I's Both of them should be okay, that is, Both of them should be okay, that is, [Music] [Music] Cross multiply, what will happen [ Cross multiply, what will happen [ Music] If this is not done here, then we will checked by multiplication, OK, so checked by multiplication, OK, so you have to pay attention to these things, you will not know anyone in the interview. you have to pay attention to these things, you will not know anyone in the interview. you have to pay attention to these things, you will not know anyone in the interview. also doubt please in D common | 2024-03-19 11:56:45 | 1,232 | Check If It Is a Straight Line | AMAZON | Leetcode-1232 | Explanation ➕ Live Coding |
|
dg0tCWF2ta8 | Ki 510 Welcome To My Channel And They Are Also Living Very Important And Famous Interview Living Very Important And Famous Interview Problem MyCalendar Vansh Sidhi Like Share And Problem MyCalendar Vansh Sidhi Like Share And Like Share And Subscribe Attempting Like Share And Subscribe Attempting Interview Tips Interview Sharing This Interview Tips Interview Sharing This Problem Thursday Till Pen Drive And Subscribe Subscribe Subscribe Quit Successfully and Returns Through It's Not Free Dangi Will Return Forms and subscribe The Channel and subscribe the subscribe The Channel and subscribe the Channel and subscribe the Truly Channel and subscribe the Truly Representative Meeting from Shyam Subscribe Representative Meeting from Shyam Subscribe Button Meeting with Subscribe Shyam Shyam Kunwar Life in the First Kunwar Life in the First Kunwar Life in the First Meeting Hai Like Its Vishuddha Meeting Can Also Be Accepted And Evil Returns Through That Is This Is Totally Problem Solved Viruddh Solution Like And Subscribe Will Keep 1000 Start End Time To Be Successful 1000 Start End Time To Be Successful Meeting And Meeting And Meeting And method for withdrawing subscribe with the meeting will you spend time in 2G successful walking and great and through effect collida and everyone will return forms its so what are the subscribe meeting from visiting card subscribe meeting from visiting card definitely subscribe in the previous meeting definitely subscribe in the previous meeting definitely subscribe in the previous meeting festivals start subscribe like this is the chief of staff meeting between 2 student of the year to my channel like this meeting is completely ignored due meeting is completely overlap devices pacific meeting cordiality start again as they can find fault with the stars like this Meaning of bje meeting Meaning of bje meeting Meaning of bje meeting completely overlapping subscribe can live completely overlapping subscribe can live with to one with to one that nda second 151 k sonth raw 1955 will that nda second 151 k sonth raw 1955 will check bhi new start so staff banu meeting which we need to check bhi new start so staff banu meeting which we need to check if it is great then and check if it is great then and subscribe meeting which will not listen and subscribe meeting which will not listen and ladders in the ladders in the ladders in the Channel Subscribe Channel Subscribe Videos Not To Subscribe 9 Videos Not To Subscribe 9 Arvind Hardly Takes Two Minutes So Like Share Will Take This Arvind Hardly Takes Two Minutes So Like Share Will Take This Point From College Meetings Point From College Meetings And He Will Release It's First Meeting With And He Will Release It's First Meeting With You You You Check The First Indian To And Start Is Loot Dash Lene To Subscribe And According To This Video Meeting New Year Ago Quick Start And Has Been Stopped And Have Time Time Time Of The Time Increase The Time Total Total Time Of The Time Increase The Time Total Total Time Times In Every Life For The Last One Will Come Times In Every Life For The Last One Will Come Into Times For This Time Complexity Of Into Times For This Time Complexity Of And subscribe The Amazing Something And subscribe The Amazing Something Different Types Of The Day Different Types Of The Day Is So What We Can Do You Will Tried To Is So What We Can Do You Will Tried To That Sort That Sort That Sort structures so in java with adopted kids will help of which commonly used factory map and in c plus plus one is the mean that will win this time start time alone with absolute value and time so in this The New The New The New New Interviewer Is The New Interviewer Is The Success Fully Not To Worship In Any Of The Already Obscene Success Fully Not To Worship In Any Of The Already Obscene Selected Meeting So What Will You Try To Find Selected Meeting So What Will You Try To Find Out 20 Home Made This Out 20 Home Made This Meeting Life So These Three Members Have Meeting Life So These Three Members Have Very Important To Make The Life And In This Very Important To Make The Life And In This Floor Floor Floor Number Channel Subscribe And You Will See subscribe and subscirbe 21 subscribe and subscirbe 21 Ki Hina Bar Retreat Map Ki Hina Bar Retreat Map Ki No Veer Wedding Minute Par Meeting 1520 500 Ki No Veer Wedding Minute Par Meeting 1520 500 For Date Of Birth Using Start Will Tree To Find Out Who For Date Of Birth Using Start Will Tree To Find Out Who Had Had Had floor of this is stand and such gender of this channel is unique wishes software predicate ceiling key suite with me to take no no no need to check the volume to the floor that is grated stop start start 1000 and interview with David 210 The sun for 5th floor key will be null wild ceiling key will be time not mean that to apply the same condition show for this is the condition Neetu check is the key and turn of our new meeting is lesson value of this is pain and sorrow this It is better than salinity in ceiling, it is better than salinity, misbehavior, overlap, edifice of buffalo beach, stem and a list of some, already subscribe, meeting calendar and decisions, like overlapping, subscribe our channel, if you have not subscribed, then Our Video Represents Your Data Structure In Record Board Flash Light Will Use A Trap For Treatment Of Enter Enter Key And Attracts Call Map Itself And Share Bellini Slice This Was That No Water Into And Justice Cut This Channel Of Of Of interior Udayveer and is like sin dot floor interior Udayveer and is like sin dot floor ki problem ki office jaana hai ki similari e will guide seal of starts from map.com ceiling ki ya sauce will be map.com ceiling ki ya sauce will be stopped ceiling office start vvi good will stopped ceiling office start vvi good will Check also condition of this floor that is not tap that hand som Check also condition of this floor that is not tap that hand som you direct floor is you direct floor is a great dane and equal to start who is this also neatu like talash which is not interested in this will return forms a & b value in end a & b value in end a & b value in end adi and this great dane seal efficacious The case so let's check the year problem or effigy value its do not included to be used in this case and new start this ki included for this and is not Saurabh Yadav this recommendation was written for Software Otherwise Village Map Hotspot Start From And That And He Will Return Proof Vihar Double Duplex Tried To Compile Record Festival Creative Thursday 112 And 50 Minutes Backward Gift Second And Third Third Sample A Tried To Give Some Id Hua Hai Record Accept What Is The Record Accept What Is The Record Accept What Is The Complexity of Dissolution Soul Space Complexities Festival Call Receive Breaking News and Times in the Floor and Take Off the Time Complexity Subscribe 2012 | 2024-03-21 11:38:21 | 729 | My Calendar I | Leetcode 729 | TreeMap Range | Google Facebook |
|
zdk_9kDV2Bg | hi everyone it's albert today let's solve the contest median today let's solve the contest median question closest dessert cost question closest dessert cost and before we start don't forget to and before we start don't forget to subscribe to my channel subscribe to my channel i'll be constantly solving good and i'll be constantly solving good and classic clinical question classic clinical question with clear explanation animation and with clear explanation animation and visualization visualization now let's look at a question in this now let's look at a question in this question question we would like to make a dessert and are we would like to make a dessert and are preparing to buy preparing to buy the ingredients we have n ice cream the ingredients we have n ice cream based flavors based flavors and m types of toppings to choose from and m types of toppings to choose from and we have to follow this rule when and we have to follow this rule when making the dessert making the dessert the first rule is there must be exactly the first rule is there must be exactly one one ice cream base and we can add one ice cream base and we can add one or more types of toppings or have no or more types of toppings or have no topics at all topics at all but there can be at most two of each but there can be at most two of each type of toppings type of toppings we are given three inputs base cost we are given three inputs base cost array array is an integer array of then n where each is an integer array of then n where each item item represents the price of the ice cream represents the price of the ice cream base flavor and topping cost array base flavor and topping cost array each item represents the price of one of each item represents the price of one of the the i topping and target is an integer i topping and target is an integer represents the target price of our represents the target price of our dessert dessert and we want to make a dessert with a and we want to make a dessert with a total cost as close to total cost as close to target as possible so we have to return target as possible so we have to return the closest possible cost of the desert the closest possible cost of the desert to target to target and if there are multiple ones we have and if there are multiple ones we have to return to return the lower one in example one the base the lower one in example one the base cost array cost array is one seven and topping cost is three is one seven and topping cost is three four four and target is ten so the and target is ten so the optimal cost we can get is uh choose optimal cost we can get is uh choose base one which will cost seven and then base one which will cost seven and then take one of typing zero take one of typing zero and it will cost three we won't take top and it will cost three we won't take top one at all one at all so the total cost will be seven plus so the total cost will be seven plus three plus zero three plus zero which is ten which is exactly target which is ten which is exactly target any example 2 with a given base cost any example 2 with a given base cost and topping cost target we can consider and topping cost target we can consider the following combination we can choose the following combination we can choose base 1 base 1 which will cause 3 and then take one of which will cause 3 and then take one of typing zero typing zero two of topping one and the total two of topping one and the total optimal cost will be 17 which is the optimal cost will be 17 which is the closest closest cost we can get to target cost we can get to target for example three and 4 the optimal for example three and 4 the optimal total cost we can get is 8 and 10. total cost we can get is 8 and 10. and the data constraint of this question and the data constraint of this question is actually a big hint that is actually a big hint that the size of base cost and topping cost the size of base cost and topping cost won't be bigger than 10. so for such a won't be bigger than 10. so for such a small dial size small dial size we can just use a brute force dfs we can just use a brute force dfs recursion to solve this question which recursion to solve this question which is the same algorithm that we use is the same algorithm that we use in solving last week's problem in solving last week's problem and the main idea is to try every and the main idea is to try every possible combinations possible combinations of base and topping and then we will of base and topping and then we will update update the total cost closest to target the total cost closest to target now let's look at the code okay now let's look at the code okay and first we'll create a class variable and first we'll create a class variable res res and it can be initialized to positive and it can be initialized to positive infinity infinity and then for every cost in the base cost and then for every cost in the base cost array will run array will run a dfs function and a dfs function a dfs function and a dfs function won't return anything and the phase won't return anything and the phase condition condition for the dfs function is when the for the dfs function is when the absolute difference between target and absolute difference between target and the current sum the current sum total is more than the difference total is more than the difference between between rest and target then we will update rest and target then we will update total total to rest and if total is bigger than to rest and if total is bigger than target target we will just return from the recursive we will just return from the recursive function function and next is the dfs sub problem we'll go and next is the dfs sub problem we'll go through through every cost in the topping cost array and every cost in the topping cost array and then then try every possible combinations of the try every possible combinations of the topping topping and then return rest at the end now and then return rest at the end now let's see the coding action okay and here we'll be looking at example 2. the base cost array is 2 and 3 and topping cost is 4 5 and 100. so starting from the first cost in the base cost array we can try don't pick topping 0 at all and then a dfs sub problem would be the remaining subarray in topping cost which is subarray 5 and 100 but we also have different options that we can choose one of typing 0. or choose 2. and when trying these different combinations rest and next we can try the other base and and next we can try the other base and again again try zero one or two of topping zero try zero one or two of topping zero and then recurse into the dfs sub and then recurse into the dfs sub problem problem so following this idea this process so following this idea this process the optimal solution will be choosing the optimal solution will be choosing base one and then one of topping zero base one and then one of topping zero two of topping one and the optimal cost two of topping one and the optimal cost we can get we can get closest to target 18 is 17 closest to target 18 is 17 and this will conclude the algorithm finally let's review because of a small data size of the input array of this question we are able to use a brute force dfs to solve it and the main intuition is to try every possible combinations of base and topping cost array and then update the total cost closest to target and the time complexity of this approach is big of m times three to the power of n and three is because we have three options of choosing toppings and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the you | 2024-03-22 14:29:33 | 1,774 | LeetCode 1774. Closest Dessert Cost | Visualization | Python |
|
fTBM3qOLGYw | hey hey everybody this is Larry this is day day 13 of the lead code daily challenge 13 of the lead code daily challenge hit the like button hit the Subscribe hit the like button hit the Subscribe and join me on Discord let me know what and join me on Discord let me know what you think about today's form you think about today's form uh 15 23 count our numbers in an uh 15 23 count our numbers in an interval range interval range um yeah let me know what you think I um yeah let me know what you think I just watched the Super Bowl uh so I just watched the Super Bowl uh so I don't know let me know don't know let me know which team you were rooting for and which team you were rooting for and whether they won if you watched it if whether they won if you watched it if not also like what about that mid uh uh not also like what about that mid uh uh that halftime show that halftime show um I actually forgot how many uh hit um I actually forgot how many uh hit singles Rihanna has been singles Rihanna has been it's been a long and it's been a long and good career okay so let's take a look at good career okay so let's take a look at this prom I'd uh I mean this is easy this prom I'd uh I mean this is easy though I should know it faster though I should know it faster um I I one thing is that obviously uh um I I one thing is that obviously uh uh you should definitely still look at uh you should definitely still look at the constraint even though it's easy and the constraint even though it's easy and given that this is 10 to the nine a four given that this is 10 to the nine a four Loop would be a little bit too slow uh Loop would be a little bit too slow uh in most cases in most cases um there are really two ways you can um there are really two ways you can think about it um you can maybe do some think about it um you can maybe do some maths about you know uh the the Delta maths about you know uh the the Delta and then like do some whatever and then like do some whatever um um like uh uh on the parody and I think like uh uh on the parody and I think that should probably be good too uh the that should probably be good too uh the way that I like to think about it is way that I like to think about it is is is um um for these kind of problems maybe not for these kind of problems maybe not this one is a little bit over this one is a little bit over complicated but but if you're checking complicated but but if you're checking this video out uh maybe this will be this video out uh maybe this will be something that you can learn as well something that you can learn as well right right um which is um this idea of prefix sum um which is um this idea of prefix sum maybe uh or I mean it's not quite prefix maybe uh or I mean it's not quite prefix some because this is way easier than some because this is way easier than that but basically the idea of that but basically the idea of um you know counting the odds of um you know counting the odds of between between if we want to count the odds between uh if we want to count the odds between uh low and high that is just the same as low and high that is just the same as counting the number of odds which counting the number of odds which um between zero and high minus uh it's um between zero and high minus uh it's between zero and uh low minus one right between zero and uh low minus one right uh low minus one because if low is odd uh low minus one because if low is odd then uh then low would be inside this then uh then low would be inside this range so this is where I I kind of you range so this is where I I kind of you know um know um uh uh this is where the prefix sum idea uh uh this is where the prefix sum idea comes from or like the analogy you know comes from or like the analogy you know before exam is definitely a more before exam is definitely a more advanced topic but if you're watching advanced topic but if you're watching this video hopefully it helps but yeah this video hopefully it helps but yeah basically the idea is that okay let's basically the idea is that okay let's say we have some number line right say we have some number line right I'm asking very hard I'm asking very hard uh let's see about some number line uh let's see about some number line right and then we have let's say lowest right and then we have let's say lowest here and high is here right the idea is here and high is here right the idea is really simple is that we want to get the really simple is that we want to get the number of odd numbers in this range number of odd numbers in this range um which is just it goes to the number um which is just it goes to the number of odd numbers in this range minus the of odd numbers in this range minus the number of odd numbers in this range number of odd numbers in this range right exclusive of the lower bound and right exclusive of the lower bound and you can kind of see that if we subtract you can kind of see that if we subtract this from this from this you get this this from this from this you get this um so this is a tool that you obviously um so this is a tool that you obviously like I said you don't really need it for like I said you don't really need it for this particular problem but this particular problem but but it is a problem it is a tool that um but it is a problem it is a tool that um it is a technique that does come into it is a technique that does come into play from time to time and if you and play from time to time and if you and you may see it in other problems harder you may see it in other problems harder problems and this would be kind of the problems and this would be kind of the idea behind it so yeah so that's idea behind it so yeah so that's basically the idea and then okay so then basically the idea and then okay so then now we can say return F of Pi minus F of now we can say return F of Pi minus F of low minus one low minus one have to be a little bit have to be a little bit be careful because uh because low can be be careful because uh because low can be zero and then negative one you may do zero and then negative one you may do something funky something funky um but yeah and then of course now we um but yeah and then of course now we Implement F which is uh let's just say x Implement F which is uh let's just say x um maybe if x is let's just take care of um maybe if x is let's just take care of their Edge case it is a little bit weird their Edge case it is a little bit weird but that's fine right but that's fine right um um and then now uh this is easier right and then now uh this is easier right because basically if if x is odd then because basically if if x is odd then you could kind of do the cases right if you could kind of do the cases right if x is odd what does that mean right so x is odd what does that mean right so for example if it's seven then for example if it's seven then and and this is what I like to do is and and this is what I like to do is that I play around with small numbers to that I play around with small numbers to kind of make sure that I get the smaller kind of make sure that I get the smaller numbers right and and then you know numbers right and and then you know because it's easy to get off by one because it's easy to get off by one otherwise right so the number seven we otherwise right so the number seven we want to return four so I'm just guessing want to return four so I'm just guessing that is going to be that is going to be um you know X plus one over two right um you know X plus one over two right and of course it is also the same if you and of course it is also the same if you do uh integer division for for even do uh integer division for for even number as well so then Auto thingies are number as well so then Auto thingies are kind of so you don't even need this kind of so you don't even need this because if this is an even number this because if this is an even number this would round down anyway so okay would round down anyway so okay so let's give it a run it looks okay so let's give it a run it looks okay maybe you test a little bit more because maybe you test a little bit more because I worry about this zero in one case I worry about this zero in one case maybe so uh zero one maybe so uh zero one uh maybe one one and then something like uh maybe one one and then something like that right uh so it looks good let's that right uh so it looks good let's give it a submit give it a submit did I click on submit or did I click on did I click on submit or did I click on whatever whatever nope let's click on submit sorry what's nope let's click on submit sorry what's in there it looks good 10 49 day streak in there it looks good 10 49 day streak not that I mean it's fast enough it's not that I mean it's fast enough it's just fluctuation at this point just fluctuation at this point um yeah and this is obviously just over um yeah and this is obviously just over one right this is of one this is our uh one right this is of one this is our uh well this is odd one and then we do it well this is odd one and then we do it twice so yeah uh and you probably don't twice so yeah uh and you probably don't even you know whatever just to kind of even you know whatever just to kind of be clear be clear um cool um cool um yeah that's what I have for this one um yeah that's what I have for this one let me know what you think let me know let me know what you think let me know how you did it let me know your really how you did it let me know your really quick and short Solutions quick and short Solutions um so yeah um so yeah anyway uh the week is coming up the long anyway uh the week is coming up the long week uh I don't know it's just a regular week uh I don't know it's just a regular week but uh so yeah so have a great week week but uh so yeah so have a great week stay good stay healthy to good mental stay good stay healthy to good mental health I'll see y'all later and take health I'll see y'all later and take care bye bye | 2024-03-21 11:29:01 | 1,523 | 1523. Count Odd Numbers in an Interval Range - Day 13/28 Leetcode February Challenge |
|
BjN-UJ4oVZQ | hey welcome back and today we're going to continue our journey to minimax and to continue our journey to minimax and we're going to talk about this we're going to talk about this super hard problem cat and mouse and super hard problem cat and mouse and we're going to go ahead and read the we're going to go ahead and read the question question a game is played by a cat a mouse named a game is played by a cat a mouse named a catamount a catamount and the environment is represented by and the environment is represented by the grid we have the rows and the grid we have the rows and columns and where each element columns and where each element is a wall floor and we have two players is a wall floor and we have two players catamounts catamounts or the food and the players are or the food and the players are represented by different characters represented by different characters we have c stands for cat m stands for we have c stands for cat m stands for mouse mouse and we have the dot period stands for and we have the dot period stands for the empty spaces we can walk on the empty spaces we can walk on and we also have the hashtag are the and we also have the hashtag are the walls that blocking walls that blocking cat and mouse are from moving so we cat and mouse are from moving so we cannot the the cat and mouse cannot cannot the the cat and mouse cannot across the wall across the wall and we have the f stands for the food so and we have the f stands for the food so we have cat and mouse and food and we have cat and mouse and food and in the grid the empty spaces we can walk in the grid the empty spaces we can walk on on and the hashtag stands for the wall that and the hashtag stands for the wall that there are like blockers the mouse and there are like blockers the mouse and the the cat can play accordingly to the to the cat can play accordingly to the to the following rules following rules so what are the rules we have the mouse so what are the rules we have the mouse can move can move first and then they take turns to move first and then they take turns to move so mouse goes first and then cat and so mouse goes first and then cat and then mouse then mouse and during each turn the cat and mouse and during each turn the cat and mouse can jump into one of the four directions can jump into one of the four directions left right up and down left right up and down they cannot jump over the wall nor the they cannot jump over the wall nor the outside of the grid can jump cat jump mouse jump are the maximum length that the cat and mouse can jump at a time respectively and cat and mouse can jump less than the maximum length that we defined within the cat jump mouse jump staying in the same position is allowed so we can jump zero step all the way to cat jump or the mouse jump that we defined in the parameter and mouse can jump over the cat they cannot jump over the walls but the mouse can jump over that the the cat for example the the cat is right here and the mouse can jump over the the cat as long as the maximum jump is allowed how will the game ends so we got four different ways the first way is when the cat occupies the same position as the mouse so cat wins so cat catch the mouse cat wins or the cat can go ahead and directly waiting for the mouse at this spot so that means the cat is smart and cat will directly go into the foot spot and just waiting for them the mouse to come over where the mouse will reach the foot first and then that's when mouse wins or we have the last tricky condition so this is actually a trick so after like a thousand turns if the mouse cannot reach the foot then catch wins but sometimes we have less empty spaces but sometimes that they are running in the loop so that's why we are on account the empty spaces so i'm gonna show you guys within the code so let's go ahead and write the code and we're going to learn this from okay so we can go ahead and start doing okay so we can go ahead and start doing some coding we're going to define the boundaries m and n so we have the grid was being given so we're gonna go ahead and write rows and columns and we're gonna have a vetted it stands for how many empty spaces we have how many empty spaces we can walk on so we're gonna loop through every single grid to calculate it and we're gonna also find the cat mls and also the food where are they and grid i nj stands for each grid and as long as it's not equal to the hashtag that means we have a valid place to go and then we're gonna loop this four times we're gonna find our cat and we find a position you know what perfect so we have our cat perfect so we have our cat so we need to find the males as well so we need to find the males as well mouse will be mouse and the foot mouse will be mouse and the foot will be the food now we have all the will be the food now we have all the parameters are parameters are ready so let's go ahead and write our ready so let's go ahead and write our hopper function which is our dfs hopper function which is our dfs so the reason we made everything to so the reason we made everything to tuple is because when i cache the value tuple is because when i cache the value so let's put the cache first so let's put the cache first bunk tools that are lru cache so you can go ahead and write your your manual cache so we have been talked about this for a long time so this is the python trick to to catch the values or you can use the hashmap to catch it so we're gonna have the mouse we're gonna have the cat we also have the turn so turn means like which uh which round which animal should go ahead and play the game so the mouse starts first so that's what we give in the game and let's write the terminated terminal condition so when's the base case wins the game will end so we actually given right here let's just copy this over so if the if the cat occupies the same position as the mouse so if the cat equal to the mouse or if the cat go into the spot where is the foot is then we return false so we are acting as uh the player as mouse so if the cat catches the mouse or if the cat going to the foot spot then the mouse loose and this warmer condition we have to be really careful so turn wheel tracking like how many runs we have been given and if the turn is greater or equal to divided times two the value stands for how many empty spaces we can go so if the turn go over twice as the empty spaces we have that means we are running in the loop then so the question is asking if the cat is running over 1000 so right here if if the mouse cannot get the 30 within 1000 turns cats win but 1000 is not the constraint actually it's not a strict stricter constraint the stricter constraint is the valid spaces so if i keep running in the loop then we are eventually going to lose the game as well because we are running in the is equal to the foot that means the is equal to the foot that means the mouse will win mouse will win so that's why we're going to return to so that's why we're going to return to so first round is going to be the mouse so first round is going to be the mouse turn turn mouse goes first so if the turn mouse goes first so if the turn mod 2 equal to zero that means we are in the even we're in the even number so the mouse turn so for n stanford stands for next so next mouse in the next position we put mouse in we put the turn in so we're going to write a separate function next position to calculate where on the spot where the positions that the mouse can go so based on the turn we can determine if it's cut turn or the the mouse turn and based on that we can calculate because we are given the maximum length that the animal can jump and based on that we also given the position so we can calculate what are the next positions we can calculate so we can we're going to write the helper function and same thing so we're going to write the minimax function so then we put next mouse in and put the next cat in and we put turn plus one because each round we uh plus one so if one of the run that the the mouse can win we just return true because we are the mouse so we can we can win so otherwise we just return files so else so this is going to be the cat and based on that so we're going to and based on that so we're going to calculate all the positions that calculate all the positions that our cat can go so we're going to put the our cat can go so we're going to put the next next position and we're going to put the cat position and we're going to put the cat that we're going to put the term that we're going to put the term and we're going to calculate all the and we're going to calculate all the positions that where the cat can go positions that where the cat can go and we're going to put the dfs as well and we're going to put the dfs as well now we're going to pass in the now we're going to pass in the mouse we're going to have the next cat mouse we're going to have the next cat and turn plus one as well so the and turn plus one as well so the the up the opponents also play optimally the up the opponents also play optimally so that's why when we return false so that's why when we return false from the opponents so we just return from the opponents so we just return false because we are playing optimally false because we are playing optimally and otherwise we just return true and otherwise we just return true perfect so perfect so now we are finishing the uh the function now we are finishing the uh the function so we can go ahead write the helper so we can go ahead write the helper function next position the next position so we're gonna have the next position and we're gonna put the position in okay so given the position so how many okay so given the position so how many jumps we can go so let's define the list jumps we can go so let's define the list and we're gonna return the list as well and we're gonna return the list as well so the jump will be equal to um so if turn that means we have mouse jump that means we have mouse jump mouse goes even else we have mouse goes even else we have the cat jump now we have the jump number the cat jump now we have the jump number and then we can go ahead and looping and then we can go ahead and looping through all the neighbors right through all the neighbors right all the four positions one zero one zero negative one zero negative one zero one perfect so we're gonna loop through one perfect so we're gonna loop through like like exploring all the neighbors and then exploring all the neighbors and then we're gonna find out how many steps we we're gonna find out how many steps we can find can find oh we can jump so we're gonna so we can oh we can jump so we're gonna so we can stay in the same spot stay in the same spot so that's why we're gonna go from zero so that's why we're gonna go from zero all the way to jump all the way to jump so we have done plus one because python so we have done plus one because python only allowed only allowed uh the the exclusive we we don't include uh the the exclusive we we don't include the the last number and then we're gonna the the last number and then we're gonna calculate the next calculate the next coordinate so that's gonna be a position coordinate so that's gonna be a position zero plus the step zero plus the step times the the dx and same thing with the times the the dx and same thing with the y y will be position of one plus the step will be position of one plus the step times d y so we're exploring this times d y so we're exploring this so as long as we are within then we can go and just one more thing then we can go and just one more thing actually actually it's supposed to be end so as long as it's supposed to be end so as long as we're within the coordinates we're within the coordinates so we can go ahead and rolling we can so we can go ahead and rolling we can start like start like uh crowding but one more thing uh crowding but one more thing we cannot move we cannot move if it's not empty spaces so we need to if it's not empty spaces so we need to check check make sure this is not a wall so we make sure this is not a wall so we cannot across the wall so that's why cannot across the wall so that's why when as long as it's not a wall so we when as long as it's not a wall so we can move can move otherwise otherwise we break otherwise otherwise we break so we're going to continue we'll break so we're going to continue we'll break why because for example why because for example if the the cat the mouse can jump like if the the cat the mouse can jump like three three spot right so for example on three three spot right so for example on the left the left is a wall so the cat cannot jump over is a wall so the cat cannot jump over so that's why we're gonna break instead so that's why we're gonna break instead of continue so of continue so we're gonna we're gonna break from this we're gonna we're gonna break from this direction direction while looping through this direction we while looping through this direction we are checking one step two step three are checking one step two step three step step so as long as we cannot jump that far so so as long as we cannot jump that far so we break we break perfect i think we are finished so let's perfect i think we are finished so let's go ahead and call in the function go ahead and call in the function we put the mouse in and we put cat in we put the mouse in and we put cat in which we calculated which we calculated on the very top and see if that works oh i'm actually writing the inner oh i'm actually writing the inner function so function so i shouldn't need this off okay okay minor minor okay it passed all right so let's do a okay it passed all right so let's do a little bit recap little bit recap so what we're doing right here is that so what we're doing right here is that so we are calculating the valid so we are calculating the valid so how many empty spaces we can walk on so how many empty spaces we can walk on and we have and we have the three coordinates we need to cache the three coordinates we need to cache and and we're gonna have oh so we're gonna catch we're gonna have oh so we're gonna catch the vet otherwise it's gonna be the vet otherwise it's gonna be uh tle and we're gonna have mouse we're uh tle and we're gonna have mouse we're gonna have cat and we have the turn gonna have cat and we have the turn so all the conditions we calculated so so all the conditions we calculated so this is actually given right this is actually given right all the conditions are given given all the conditions are given given except this part so instead of like 1000 except this part so instead of like 1000 we put we put divided times two that means how many divided times two that means how many empty spaces we can walk on empty spaces we can walk on and as long as we we are passing uh all and as long as we we are passing uh all the empty spaces twice that means like the empty spaces twice that means like we are going over a loop so we are going over a loop so as long as we are in the loop then we as long as we are in the loop then we return false that means the cat cannot return false that means the cat cannot win win because we already go over that we're because we already go over that we're gonna go into the infinite gonna go into the infinite loop so if the mouse reached the foot loop so if the mouse reached the foot and then we are and then we are returned to because we the the demands returned to because we the the demands already win already win and the mouse can go and the cat can go and the mouse can go and the cat can go each player played each player played will play with optimal solution will play with optimal solution and we are done so all we does right and we are done so all we does right here is the here is the uh the find the next position so it's uh the find the next position so it's more like a bfs more like a bfs standard okay sounds looks great okay standard okay sounds looks great okay i'll see you guys in the next video | 2024-03-20 17:42:00 | 1,728 | Leetcode 1728. Cat and Mouse II |
|
WKlbdfKiZn4 | That Welcome Back Price Today Will Be Seen The Maximum Number of Return Apples Problem This Problem Maximum Number of Return Apples Problem This Problem Appeared in the Weekly Contest Appeared in the Weekly Contest of List Ko Dr. Ko Cut Song From A of List Ko Dr. Ko Cut Song From A Explicit Flex Reader Problem Dare Explicit Flex Reader Problem Dare This Special Kind of People Tree Traffic Date This Special Kind of People Tree Traffic Date for Entries Contra Voucher for Entries Contra Voucher for Entries Contra Voucher Producer Apple Cider Free State Will Support After Their Descendants After 25th July 2014 People Will Feel Choked And They Can't Better Than This Temple Is Not Valid Points And Which It Onto Episode 520 Entries Profile Dhoop See Suicide Into The The The Doctor Away E Do Not Want You Can Keep Doctor Away E Do Not Want You Can Keep Eating After First And As Given Twenty Eating After First And As Given Twenty Years At Temples In The Maximum Number Of Years At Temples In The Maximum Number Of Couples' Facility Problems Is The Given Two Couples' Facility Problems Is The Given Two Years Apple Cider And Its People Rather Years Apple Cider And Its People Rather Plain By Apple Tree Plain By Apple Tree Turn On The Amazing Notes The Turn On The Amazing Notes The Turn On The Amazing Notes The Twitter aspect for witch noose straight yellow pink and basically what we have to do is to so if we see its example then the so if we see its example then the example is given like one to example is given like one to three 52 Apple has been released and three to one three 52 Apple has been released and three to one 4280 Sudhir and condition in spite of that is present as is 4280 Sudhir and condition in spite of that is present as is - closed If - closed If an apple is produced on Municipal Commissioner's Day then you try an apple is produced on Municipal Commissioner's Day then you try plus 1005 - We can fit the apple only till one who kid, plus 1005 - We can fit the apple only till one who kid, after that we after that we cannot produce it. cannot produce it. cannot produce it. i till after this stage of i - Band only they claim to solve this example so it's right one plus three left side let's not reliable 2012 201 ewant hai tu MP3 Zero plus Zero plus Zero plus minus one on the road So this one on Apple 103 Test minus one on the road So this one on Apple 103 Test Pooja This is the guide 0120 So we Pooja This is the guide 0120 So we can feed it here also can feed it here also You can also bring it here You can also bring it So You can also bring it here You can also bring it So for now we will press it here for now we will press it here for now we will press it here again and it is affected that two one plus two minus one is easy-to-read two is Punjabi in today's till will be then we * You press it here and how two plus one minus one suited Stuart Because here this Because here this Because here this tubeless one - from the middle of 1864 ours tubeless one - from the middle of 1864 ours and we have already said that here and we have already said that here we cannot use all these apps, we have used all these, we cannot use all these apps, we have used all these, we have used all these we have used all these but we but we but we okay, so now we go to the third, a young man phone, third, what to do when three plus form - one is 60, which on fiber, it will come up to 6 inches, so we change them till six, 1234, so if we But here bana is But here bana is But here bana is left and after this we left and after this we cannot use par forever. Now four plus two minus one cannot use par forever. Now four plus two minus one request is 6 - 151. request is 6 - 151. Now we could not do this so Now we could not do this so basically we discovered all so basically we discovered all so now we can use all the now we can use all the now we can use all the all the dough no problem skin tight with this money 12345 670 Answers for this stop now su look at this problem as an example once we have understood what we have to do then basically now So So So first of all the solution to Jack problem first of all the solution to Jack problem strikes us, he does this one that strikes us, he does this one that we both put that and in that we beat the we both put that and in that we beat the birthday check that at this airport birthday check that at this airport as many as when label and that is our I plus as many as when label and that is our I plus days of I days of I days of I that Dravid is the staple on Saturday, so if we can net, then place him and like this, we will move ahead in this IPL-5 - Mamta has less quantity people but others have How is the color approach, How is the color approach, How is the color approach, I explain its solution with lucky examples. I explain its solution with lucky examples. We need apples that We need apples that this will be and one is this bird this will be and one is this bird Saudi Arabia, Saudi Arabia, so if we go with this approach, then we will get so if we go with this approach, then we will get this 0123 floor and 10060, what will we this 0123 floor and 10060, what will we do or plus and minus. do or plus and minus. do or plus and minus. pulse that we can eat 19th, but we are starting to shoot the starting scene, so here we will do square feet, here we will cut and these two ended with each other, zero's that But if our object is Apple, then But if our object is Apple, then But if our object is Apple, then one plus one - one on this bill that the one plus one - one on this bill that the distributor, so we will fit it here, distributor, so we will fit it here, you and three have made the payment by being curved, you and three have made the payment by being curved, now we have this two plus years and now we have this two plus years and what is our day second year two plus what is our day second year two plus Six - If we do T-20 at this time, then we will do one and Six - If we do T-20 at this time, then we will do one and two here, we will cut this, this is also two here, we will cut this, this is also forced, now whoever goes to Apple, this is forced, now whoever goes to Apple, this is third day career, this is three plus possible third day career, this is three plus possible minus one, this umbrella, this is till six later. minus one, this umbrella, this is till six later. minus one, this umbrella, this is till six later. can only eat one of these so we put it here so this ₹ 1 and zero 1234 so four plus two minus one apps 16 - 152 These apps will not be valid If we If we If we organize them, then basically organize them, then basically we can use this method to get weapons, but now what is the we can use this method to get weapons, but now what is the correct answer to this, correct answer to this, how is the camp internship that we have just how is the camp internship that we have just taken in the fall of 2012, the taken in the fall of 2012, the zero fee typing that we had done in starting it? zero fee typing that we had done in starting it? zero fee typing that we had done in starting it? him lying on the bed, so we can fit him in that school, here I can ask him like this, we are the has him, we can break him here, like this we can this we can this we can then by folding them like this, we can do the entire avery field and according to that, if we want an earthquake, then 30 Chobdar that monkey juice, we have proposed the club solution, the basic question that is We will have to We will have to We will have to think of some such fear father-in-law who will think of some such fear father-in-law who will always give us the blood slide minimum deadline always give us the blood slide minimum deadline and with the minimum deadline, we can check and with the minimum deadline, we can check that if this divider line is valid on this country that if this divider line is valid on this country and and how many apples are left corresponding back to this blind, then we how many apples are left corresponding back to this blind, then we that you all have always maintained a deep minimum approach, there is a that you all have always maintained a deep minimum approach, there is a threat of a deadline, there is a threat of a deadline, there is a deadline and the number of points is 100, we have to click on the account and the tagline in it is to we have to click on the account and the tagline in it is to convert it into minimum approach. convert it into minimum approach. convert it into minimum approach. flour can add the most, get back, see why we can use it on medium, loot project, so we will use minimum amount of flour in it, that you will use that in it, days, how long that apple is valid, We will put this in it, we will take our date, we will do We will put this in it, we will take our date, we will do We will put this in it, we will take our date, we will do something inside that and something inside that and how many correspondents of that samples line are back, yes, I have how many correspondents of that samples line are back, yes, I have that, we will do something inside that, when that, we will do something inside that, when we called them flowers, cannons, we called them flowers, cannons, particular is left, what will we do, we will particular is left, what will we do, we will check brother. check brother. check brother. took out a tree, people took out a top first, crime vaccine, we will check in it whether we can do this particular apple on this oil and if Amit can do it, then in this experiment we will take out that apple and make it do If we can't use it If we can't use it If we can't use it then it means that it wo then it means that it wo n't be able to stop any of the upcoming candidates, so for this n't be able to stop any of the upcoming candidates, so for this reason, we will reason, we will give this apple a point of 100. It give this apple a point of 100. It has a basic presentation, so we will see the light turn after seeing its blood. has a basic presentation, so we will see the light turn after seeing its blood. If we have more If we have more clear all software then the problem is great clear all software then the problem is great school looteri community store like normal cup looteri community store like normal cup applicants will make priority to find that pair that hua that your 100 boat banyan tree broken reception that your 100 boat banyan tree broken reception poor point poor point bluetooth now we are from this na second one will boil people will royal look for wealth is letter and and priority q size do a suite no words which acts like this is This This This person who took condition that to specify person who took condition that to specify plus specific - but auspicious vacation equal to plus specific - but auspicious vacation equal to five states so how notification immediately five states so how notification immediately applicants applicants loot loot in this regard a glance footage of idols in this regard a glance footage of idols one comedy episode one comedy episode that nobody will do inch 11 applicant's all that nobody will do inch 11 applicant's all wicked all equal wicked all equal wicked all equal fifth day of specific it is nothing of but forum politics like this condition will handle 309 topic effigy element in the field of do a by-product top and few days should not do this ajay ko ajay ko on mp3 dot on mp3 dot on mp3 dot itni byachand same condition tip condition that was your bluetooth setting set same condition proposes hair soft hydroxide s minus one critically injured in the condition that particular apple that were mated and not increase the account yasmin quantity art Not Not Not I Will Again Put Into Practice Is The I Will Again Put Into Practice Is The Full Form Of B A Full Form Of B A Bhi Aap Swapna Dosh Hai Ka Anubhav Field Mother Cow But Harmonious E Is A Tantra Account Or Immediately Draw You WhatsApp Facebook Screen Compiler WhatsApp Facebook Screen Compiler Loot Lo Loot Lo Phone Kahan Hai Phone Kahan Hai Main Nidhaal Ajay Ko Hai Hai Sorry This Number Last 10 Test Radhe Show More Tomorrow Morning Difficult Time Limits For And Now She Will Win The Hearts Of Milk Plus Plus Ashwini Titu Polls Bank Westpac Gaur Tak Manner and Manner and Manner and Soft Cotton Shop Soft Cotton Shop Chat Organization That Sweet Has Been Accepted That Guys Like This Video in His Arrest Like Button Share the Video with Your Friends and Subscribe to The Channel Benefit Posting Regular Leader Limit Questions on This Channel Proper Nouns and Icon And Subscribe Our Icon And Subscribe Our Icon And Subscribe Our Channel Thank You For Watching Channel Thank You For Watching My Video | 2024-03-20 14:58:40 | 1,705 | Leetcode 1705. Maximum Number of Eaten Apples | Leetcode Weekly Contest 221 |
|
cW3fTKGT7rU | hello everyone welcome to another one of my lead code videos and this one we'll my lead code videos and this one we'll do lead code 367 valid perfect square so do lead code 367 valid perfect square so we're basically given a number and we we're basically given a number and we need to determine if it is a perfect need to determine if it is a perfect square so for example 16 is a perfect square so for example 16 is a perfect square because two integers when you square because two integers when you multiply four times four it'll give you multiply four times four it'll give you 16. 16. note that we're not allowed to use any note that we're not allowed to use any built-in functions such as square root built-in functions such as square root so what will be our approach for this so so what will be our approach for this so the you know the Brute Force approach the you know the Brute Force approach since we know that it's only two since we know that it's only two integers that you can multiply we can integers that you can multiply we can try every single integer so we can do try every single integer so we can do one times one two times two Etc until we one times one two times two Etc until we either get to num or if we exceed them either get to num or if we exceed them we know that okay then this is not a we know that okay then this is not a perfect square so for example if in this perfect square so for example if in this example num is 14 we'll do three times example num is 14 we'll do three times three we'll see it's nine we'll do four three we'll see it's nine we'll do four times four we'll see 16. so since 16 is times four we'll see 16. so since 16 is already past num which is 14 we know already past num which is 14 we know that this is not a perfect square and if that this is not a perfect square and if we got to 16 then we would just return we got to 16 then we would just return true true and this is a Brute Force solution so and this is a Brute Force solution so the time complexity will be o n because the time complexity will be o n because we'll try every integer from one we'll try every integer from one to the square root of n actually o of to the square root of n actually o of the square root of n right because we'll the square root of n right because we'll try every integer from 1 up to the try every integer from 1 up to the square root of n square root of n so the question is can we do better if so the question is can we do better if you think about this you know these you think about this you know these numbers are progressively increasing so numbers are progressively increasing so we don't actually have to do it one by we don't actually have to do it one by one we can actually apply the concept of one we can actually apply the concept of binary search to find which number it is binary search to find which number it is so in the binary search we usually need so in the binary search we usually need a minimum and a maximum so our minimum a minimum and a maximum so our minimum will be one because one is the smallest will be one because one is the smallest number number that it can have and since it goes up to that it can have and since it goes up to 2 to the 31 minus 1 2 to the 31 minus 1 you know our maximum will be square root you know our maximum will be square root of 2 to the 31 minus 1 and I computed of 2 to the 31 minus 1 and I computed this using a calculator and found that this using a calculator and found that this is equal to this is equal to 46340.95 and since we're only interested 46340.95 and since we're only interested in integers this is just fourth six in integers this is just fourth six three forty so we'll basically do a three forty so we'll basically do a binary search between 1 and 4 6 340 to binary search between 1 and 4 6 340 to find which number find which number when multiplied by itself either equals when multiplied by itself either equals to num or you know we can't find it to num or you know we can't find it so the time complexity of this will be o so the time complexity of this will be o of log of log 4 6 340 and that's basically better than 4 6 340 and that's basically better than this because this is O of 4 6 3 4 t this because this is O of 4 6 3 4 t right in the worst case and this is log right in the worst case and this is log of that so this is much better algorithm of that so this is much better algorithm so let's go ahead and code our binary so let's go ahead and code our binary search search so first we need to Define our minimum so first we need to Define our minimum and maximum variables as we have laid and maximum variables as we have laid out below next we'll just do a loop out below next we'll just do a loop which is standard binary search while which is standard binary search while Min less than equal to Mac Min less than equal to Mac so first we'll compute our mid which so first we'll compute our mid which will be Min plus Max over 2. will be Min plus Max over 2. and then this bit will be used as the and then this bit will be used as the potential square root right so we'll try potential square root right so we'll try to see we're using this mid what is the to see we're using this mid what is the product that we can get so here's our product that we can get so here's our product and then we'll compare this product and then we'll compare this product to num so if this product product to num so if this product is equal to num that means we found a is equal to num that means we found a perfect square perfect square root of this number and so we'll just root of this number and so we'll just return true return true and otherwise now if the product is less and otherwise now if the product is less than num than num that means the mid we got is too low and that means the mid we got is too low and we need a higher mid to get closer to we need a higher mid to get closer to num so what we'll do is increase our Min num so what we'll do is increase our Min to Mid plus one so that way we can get a to Mid plus one so that way we can get a higher mid next time and otherwise if higher mid next time and otherwise if it's not equal and it's not less than it's not equal and it's not less than that means here product is greater than that means here product is greater than num so we that means we need a smaller num so we that means we need a smaller product so what we'll do is Max equals product so what we'll do is Max equals mid minus one so that way we'll be mid minus one so that way we'll be searching from Min to Mid minus 1 for searching from Min to Mid minus 1 for our next round our next round and at the end if and at the end if we aren't able to find a valid mid what we aren't able to find a valid mid what will happen is these Min and Maxes will will happen is these Min and Maxes will just go past each other just go past each other right so if we never hit this case and right so if we never hit this case and this Loop terminates that means we this Loop terminates that means we haven't found a perfect haven't found a perfect square root of num and so what we'll do square root of num and so what we'll do in that case is just return false in that case is just return false so let's run that and see how that does so let's run that and see how that does accept it let's submit cool 100 runtime thank you so much for watching I'll see you in the next one | 2024-03-24 11:29:08 | 367 | Leetcode 367 Valid Perfect Square (Java) - BINARY SEARCH |
|
EKBPqhiv27M | welcome everyone to one more session in lead code solutions tutorial series in lead code solutions tutorial series in this particular session we are going to this particular session we are going to look at problem number one three eight look at problem number one three eight nine create the target array in the nine create the target array in the given order but before we begin with the given order but before we begin with the actual solution let me remind you of the actual solution let me remind you of the edinite ngo discord server this server edinite ngo discord server this server has been created for computer science has been created for computer science enthusiasts all people who want to excel enthusiasts all people who want to excel their career in the id field okay so their career in the id field okay so over here you can ask your doubts and over here you can ask your doubts and discuss topics related to id field discuss topics related to id field additionally sir will also post some additionally sir will also post some regular content some useful contents and regular content some useful contents and updates from the updates from the topics related to the same sectors so if topics related to the same sectors so if you are a computer science enthusiast or you are a computer science enthusiast or as i said earlier if you want to excel as i said earlier if you want to excel in the career in computer science or i.t in the career in computer science or i.t field then do join the server from the field then do join the server from the link given in the description below do link given in the description below do share this link with maximum of your share this link with maximum of your friends to ensure more and more friends to ensure more and more participation and yes this all the participation and yes this all the solutions all the solutions of the lead solutions all the solutions of the lead code problem as you can see over here code problem as you can see over here will be given over here okay so there will be given over here okay so there are several solutions okay there are are several solutions okay there are several uh solutions to several problems several uh solutions to several problems given on the same discord server so do given on the same discord server so do join the discord server from the link join the discord server from the link given in the description below given in the description below so now let us create an array okay so so now let us create an array okay so initially target array is empty let me initially target array is empty let me just move to whiteboard and over here just move to whiteboard and over here let us let us let us read the question okay so let us read the question okay so initially the target array we will initially the target array we will create a target array that is empty okay create a target array that is empty okay so let the target array be answer or ans so let the target array be answer or ans okay okay then we need to read okay we have given then we need to read okay we have given we have been given two arrays over here we have been given two arrays over here nums and index okay so we need to read nums and index okay so we need to read nums i and index i and then insert at nums i and index i and then insert at index i the value numps i in the target index i the value numps i in the target array okay so this problem is very much array okay so this problem is very much similar okay it is not exactly the same similar okay it is not exactly the same problem but very much similar to the problem but very much similar to the problem one of the problems that we have problem one of the problems that we have discussed earlier okay and now repeat discussed earlier okay and now repeat the previous steps okay we need to the previous steps okay we need to repeat the previous steps until there repeat the previous steps until there are no elements to be read in are no elements to be read in nums and index okay so as nums and index okay so as there is array there should be a there is array there should be a loop right loop right so so let us let us now move to an example let us let us now move to an example okay over here uh the nums array has 0 1 okay over here uh the nums array has 0 1 2 3 4 okay so 0 1 2 3 4 okay so 0 1 2 2 3 3 and 4 okay and the index array has 0 1 2 and 4 okay and the index array has 0 1 2 2 1 okay 2 1 okay so the index array has 0 so the index array has 0 then it has 1 then it has 2 then it has 1 then it has 2 2 and 1 okay initially the target array 2 and 1 okay initially the target array is empty okay initially the target array is empty okay initially the target array is empty so for what we can do is we can is empty so for what we can do is we can just create this array okay we can just create this array okay we can create this array within this is 0 1 create this array within this is 0 1 2 2 3 and 4 okay and then we can insert one 3 and 4 okay and then we can insert one elements one by one okay so first of all elements one by one okay so first of all zero is matched with zero actually uh as zero is matched with zero actually uh as the array is empty we need to insert at the array is empty we need to insert at this index itself okay so we will insert this index itself okay so we will insert zero over here zero over here now one will be at one okay so one will now one will be at one okay so one will be at one let me just erase this be at one let me just erase this and do this one will be at one so one and do this one will be at one so one then 2 will be at 2 okay 2 will be at 2 then 2 will be at 2 okay 2 will be at 2 and now 3 is at 2 okay and now 3 is at 2 okay 3 should be inserted at index 2 so what 3 should be inserted at index 2 so what about this this 2 will be shifted okay about this this 2 will be shifted okay it will obviously be shifted so let me it will obviously be shifted so let me shift this 2 over here okay 2 over here shift this 2 over here okay 2 over here and then insert and then insert 3 over here ok 3 over here ok now similarly i need to insert ok i now similarly i need to insert ok i need to do the same thing for four okay need to do the same thing for four okay four should be inserted at one four four should be inserted at one four should be inserted at one so over here should be inserted at one so over here over here we need to shift two three and over here we need to shift two three and 1 so over here we need to shift 2 okay 1 so over here we need to shift 2 okay we need to shift 2 we need to shift 2 then we need to shift 3 then we need to shift 3 okay then we need to shift 3 and then we okay then we need to shift 3 and then we need to shift need to shift 1 okay and in this place at index one at 1 okay and in this place at index one at index one we will insert index one we will insert four okay so this is our target array four okay so this is our target array zero four one three two okay this is our zero four one three two okay this is our target array and we need to return this target array and we need to return this particular array we need to return this particular array we need to return this particular array so how we are going to particular array so how we are going to do it okay do it okay over here we will use vectors as well as over here we will use vectors as well as we will use iterators in c plus plus we will use iterators in c plus plus okay okay so let us say that we have a for loop so let us say that we have a for loop okay i am writing i'm only writing the okay i am writing i'm only writing the pseudo code and not the actual c plus pseudo code and not the actual c plus plus board okay so let me just write a plus board okay so let me just write a for loop okay for loop that will run for loop okay for loop that will run okay for i equal to 0 okay for i equal to 0 to we can say nums dot size okay so let to we can say nums dot size okay so let me just write n over here i equal to 0 me just write n over here i equal to 0 to n okay it will run from i equal to 0 to n okay it will run from i equal to 0 to n okay now if uh answer is empty okay to n okay now if uh answer is empty okay if if answer is empty okay em pty if answer is answer is empty okay em pty if answer is empty then we need to push obviously we empty then we need to push obviously we need to push the nums of i into answer need to push the nums of i into answer so we will write answer so we will write answer push push nums of i okay nums of i okay nums of i okay so we need to push it and now else part okay if the answer is not empty if the answer is not empty if there's already one is one or more elements in the target array then we need to insert the elements in the index that is specified in index of i okay so else else part in else part first of all we need to create an iterator okay so we will initialize the iterator the way of initializing iterator over here i will just write i t okay we will look at the way of initializing iterator when we see the code that is in the later part of this lecture okay and over here we will insert into our answer okay so we will just write a n s we will write a n s dot i n s c r t insert okay a n s dot i n s e r t insert now what is to be inserted over here let us see what is to be inserted okay what is to be written inside the insert function okay so suppose we have a vector okay suppose we have a vector over here so this is the vector and this is a long vector okay so this here we have 0 then then you can see that we have 2 then we have 4 and so on okay so over here over here when we when i write iterator okay when i initialize the iterator iterator isn't pointing to anything okay it's not pointing to any element in the vector or to any vector or to any variable okay now i want to point my iterator to the beginning of of the vector okay so what i will do is i will just write i t equal to i t equal to over here the name of the vector is answer so i will just write a n s okay a n s dot begin a n s dot begin and now our iterator will point at the beginning at the beginning of at the beginning of our vector okay now what if i increase the value of iterator what if i do i t equal to i t i t plus 1 i d equal to i t plus 1 the arrow would be shifted over here okay when i do plus 1 the arrow will be shifted over here so let me just shift to the arrow the whole arrow over here okay now if i do i t plus 2 then it will be shifted over here okay it will be shifted at index number 2 okay now what if i want to insert at index number two i want to insert three okay so four will be shifted okay all the elements that are succeeding for four as well as all the elements that are succeeding for will be shifted okay one place afterwards and three will be inserted over here three will be inserted over here okay so this is uh the mechanism of insert method okay so what we need to do is what we need to do is we need to insert okay we need to first of all we will write iterator okay first of all we will initialize the iterator and then after initializing the iterator we will just write i t equal to i t equal to a n s dot begin okay i t equal to a n s dot begin i need to okay we need to actually initialize the iterator as well as as well as we need to initialize it okay we need to point it to the beginning every time we insert okay every time we make an insert operation why because what happens is whenever we insert an element into the array the array becomes larger right array becomes larger or the vector becomes larger so the vector that was in the original or older heap memory over there it will get erased and it will be shifted to another memory location okay to a larger memory location but iterator will still point okay iterator if it's not initialized okay re-initialized or or we can we can say that it is not updated then it will point the same heap memory location that has been freed and over there you will get the heap overflow error okay it will be a run time error so over here we will write answer dot insert or cancel dot insert and then we will write i t plus i t plus what we need to insert okay where we need to insert we need to insert that index of i index of index of i so if it is it's 0 then it will be inserted at beginning okay i t plus 0 is equal to i t i t plus 1 is a will shift one place from the beginning okay so i t plus index of i and what we need to insert over there over there we need to insert numbers of i over there we need to insert norms of i and then close it okay we need to close the else part okay so let me close the s part and over here let me just erase all these things so that you just don't get confused okay so i have erased all most of the things okay so else part we have close to the else loop okay and now let me close the for loop and after closing the for loop we will return answer okay so i will just write ret answer ret answer okay so this is the whole code okay first of all we need to run the for loop okay first of all we need to check if the answer is empty if it if it's empty then we need to push the first element and if it's not empty then we need to update the value of iterator first we need to point our iterator to the beginning of the vector and then we need to run okay we need to execute the insert operation after executing the insert operation for n number of times okay till the end we need to return the answer now let us move to lead code and code the same part okay so over here we will move to the lead code and then over here we will double solution okay so let me just write vector vector into okay vector in vector in n s so we have initialized a n s and now we will run a for loop i less than nums dot size nums dot size i less than nums dot size nums dot size size eddy size okay i plus plus i plus size eddy size okay i plus plus i plus plus plus so i plus plus and now we will write if so i plus plus and now we will write if num sorry arms okay a n s dot e m p t y num sorry arms okay a n s dot e m p t y if the answer if the answer array is empty or answer vector actually array is empty or answer vector actually is empty then a n s dot push underscore is empty then a n s dot push underscore back push underscore back push back back push underscore back push back numbers of i numbs off i okay numbers of numbers of i numbs off i okay numbers of i i else we will look at the else part so else we will look at the else part so let us look at the else part let us look at the else part else now this is the way of initializing else now this is the way of initializing an iterator okay so let me just an iterator okay so let me just move over here okay so std then we will move over here okay so std then we will write vector okay we will write vector write vector okay we will write vector and the vector is of integer type it it and the vector is of integer type it it will be it is of integer type so we need will be it is of integer type so we need to create an iterator that will point to create an iterator that will point over the elements of a vector that over the elements of a vector that contains integer values okay iterator contains integer values okay iterator iterator and the name of the iterator iterator and the name of the iterator will be ik okay now we will just write i will be ik okay now we will just write i t equal to i t equal to answer dot begin t equal to i t equal to answer dot begin answer dot answer dot okay so we will begin our uh iterator okay so we will begin our uh iterator and then then what we will do is we will and then then what we will do is we will we will just insert it so we will write we will just insert it so we will write and start insert insert we need to and start insert insert we need to insert at id plus index of index of i id insert at id plus index of index of i id plus index of i and we need to plus index of i and we need to over there we need to insert nums of i over there we need to insert nums of i okay we need to insert numbers of i okay we need to insert numbers of i now let us return now let us return the the answer vector okay return the answer answer vector okay return the answer vector so this is the whole code let us vector so this is the whole code let us run the code and see if we get any run the code and see if we get any errors or if it's a success okay so you errors or if it's a success okay so you see that it has been accepted the see that it has been accepted the solution has been accepted now let us solution has been accepted now let us submit the code okay submit the code okay and you see it's a it's a success okay and you see it's a it's a success okay so this was about this was about the so this was about this was about the solution of create target any in given solution of create target any in given order that's it for this particular order that's it for this particular session let's meet in the next session session let's meet in the next session thank you everyone | 2024-03-21 01:01:00 | 1,389 | Create Target Array in the Given Order | Leetcode DSA Solutions | Lecture 14 |
|
DOwX4DEQzv4 | Okay, so this is the clone graph, okay, its code is written and our test case is this code is written and our test case is this tooth 4 is connected, so we have to clone it, tooth 4 is connected, so we have to clone it, okay, so initially what we are okay, so initially what we are doing is we will check that the weather node is null doing is we will check that the weather node is null and not. and not. and not. we will simply move ahead, so what will we do, we will create a node after getting the result, okay look at this, so we are creating this, okay, what is this, our final answer will return the result, this is the final answer, so now we are initially in it. What are we doing? We are storing the head value in it. Okay, you can see this, so we are storing the head value here. Okay, so what will we do now? Here we have Now our value Now our value Now our value is one in this, okay this is our result deep is one in this, okay this is our result deep copy okay now let's move ahead we are copy okay now let's move ahead we are making a weighted array one, we will make a weighted array of size, making a weighted array one, we will make a weighted array of size, here in the constraint we gave 100 here in the constraint we gave 100 that the value of nuts can go up to 100 that the value of nuts can go up to 100 so we so we so we area will be ours, something like this 0 1 2 3 4 The size of the visitor is fine and seeing it here is not true and false, it is of note type, basically we will store the nut value in Visitec, we will know later. Why basically we are making Visitech of note type so that whenever that node is Visitech and we are cloning it, then in Visitech we put that value, yes, put its deep copy, otherwise Yes, we will have to keep a Yes, we will have to keep a Yes, we will have to keep a separate map, okay, we have filled the taps in it, it is not necessary to track it so much, now we start DFS, what are we doing in DFS? we doing in DFS? we doing in DFS? copy has been made of the head and it is passing through the wizard. Okay, its region will also be understood. Now the first node is initially which is noted in the question, meaning that one is yes, so now we have passed the initial one in it and have And if the visitor is And if the visitor is And if the visitor is passed then basically what will keep changing in DFS, the passed then basically what will keep changing in DFS, the value of the node will keep changing value of the node will keep changing and the result will keep getting updated, and the result will keep getting updated, our result will keep getting built up and the result will keep getting our result will keep getting built up and the result will keep getting built up and what we will pass in DFS will be built up and what we will pass in DFS will be known further now. known further now. known further now. now look, here we come DFS has started, what will we do now here visitor of this equals to okay visit of result dot value here we can also do note dot value because the value of both will remain the same what is result dot value Our one will be stored here, we need integer value, so the value of one is equal to this result, that is one, so what will come in the value, here now this one will be stored, this one, this one is not a number, it is a node, air node, R Storing in DI Yes OK Now let's R Storing in DI Yes OK Now let's R Storing in DI Yes OK Now let's go ahead with this Now what will we do, we will traverse the neighbors of the node that we have brought, right here, what are the neighbors of the forest, okay, so the first check we will see here is that okay, so the first check we will see here is that this this this Okay, if not then what will we do again? The same process which we have done here, we have created a new result and stored the values in it, so let Everyone will pay everyone, everyone will Everyone will pay everyone, everyone will Everyone will pay everyone, everyone will make a copy, so what did we do here, created a new note, created a new note, okay, stored the value in the new note, assign it okay, stored the value in the new note, assign it to OK and this is the neighbor of the result, so to OK and this is the neighbor of the result, so added neighbors to the new note, added neighbors to the new note, so what did we do here, its neighbor so what did we do here, its neighbor this OK related name result was just one this OK related name result was just one our result was just one so we added this ok ok ok now we will move ahead now what will be the DFS call move ahead now what will be the DFS call Next DFS call will be Next DFS call will be our our DFA with a key DFA with a key value two value two value two now what will happen here witted off say off this to equal tut y will be stored node ok now what will we do we will go so ca n't we store witted here Why are we storing it instead Why are we storing it instead Why are we storing it instead of? We know that we are making a deep copy of it. Well, we could have stored it in VITE. Yes, we can do it. There is no problem. There is no problem in that. But now think about the So, So, So, when will you get it done for zero, please do it above, when will you get it done for zero, please do it above, okay, you will have to okay, you will have to write the code in two places, this is a single line, write the code in two places, this is a single line, meaning it is on the string, okay, now it is done, what will we do now, or we have marked it as We will go to Neighbors. So, We will go to Neighbors. So, We will go to Neighbors. So, what is Neighbors? What are Neighbors? Okay, now we will go to Neighbors. Look, now we have come to one point. Okay, in this case, we checked if neither is active, then we will We will do it We will do it We will do it okay and what is the result here, you have to keep in mind what is the value of the result which here, you have to keep in mind what is the value of the result which is the current note after which this is our result. is the current note after which this is our result. Now in this case I have understood that yes yes Now in this case I have understood that yes yes because as a new note is passed. because as a new note is passed. Neither this is our result nor this, Neither this is our result nor this, you have passed this atli, so you have passed this atli, so we will add it in its neighbors, basically there it is being added we will add it in its neighbors, basically there it is being added to the list, here we have already to the list, here we have already made the diagram, this has been added, made the diagram, this has been added, now this is the case. now this is the case. now this is the case. three. Okay, now we come to three. Neighbor to th is not marked. Yes okay, so Okay, we put th in the new node. Then we will add th to Okay, we put th in the new node. Then we will add th to its neighbor. its neighbor. its neighbor. call will be made to the next neighbor of the invited now. What is the neighbor? Okay, now the same process will happen with the second one. If he is invited then he will be added We will We will We will create a new node because it is create a new node because it is not visited, okay and here we will create the first visited three, we have also marked this three as visited, here initially we have we have also marked this three as visited, here initially we have come to four, yes yes, we have come to four, now come to four, yes yes, we have come to four, now even four is not visited. even four is not visited. even four is not visited. add it to the neighbors, made it a new node of four, added the copy node to the neighbor, added it to the neighbor of three, added it to the neighbor, and then called DD, DFS started, four on four, and added four. Okay, okay then we will come to the neighbors of four, what is the neighbor of four and one? Now look, one is also marked, so four has been added to the neighbor of one and one has been I am already I am already I am already connected, so in this way our connected, so in this way our clone has been created, so when it returns, the return clone has been created, so when it returns, the return means finally the process is white type, means finally the process is white type, recording has been slowed down. | 2024-03-21 11:58:18 | 133 | Clone a graph | Leetcode 133 |
|
tx6F4ytNg0A | Welcome to my channel again today will discuss some problem to meet code 1298 sum to lip code 1298 sum to lip numbers for the problem statement saying from root will have to numbers for the problem statement saying from root will have to race to the list node from root race to the list node from root dalit note hair 605 lips note dalit note hair 605 lips note means have no children beans left and right means have no children beans left and right to to to Lip Notes 675 Soft 262 Ko Din 3962 Cross Frustration Se Number Chord 06 Air Water With Number 394 7 And Exit Is 315 Se Toll Free Number Sadar Swift Editor For The Native Is Is Is the result you want from this problem now you have cost given one the result you want from this problem now you have cost given one is the number notes in is the number notes in history history train which is 120 and what will oo will meet train which is 120 and what will oo will meet 102 not least they single digit and can 102 not least they single digit and can form number date of the tree will not exceed form number date of the tree will not exceed 100 three content 100 three content 100 three content is heard The question is that how I can solve this problem Sirf aloo cat hair the number three 96 Form notification The number it is 3210 Class ninth tenth plus 6 Replies check return 947 The breakdown Dutt * to 0.1 That That That note's share was same tree leaves note's share was same tree leaves multiplied from same time to same time multiplied from same time to same time cities multiplied by thousand same time with cities multiplied by thousand same time with tan white is Bigg Boss to maximum death tan white is Bigg Boss to maximum death for this loop notes are changing the billions for this loop notes are changing the billions 30 to level download way multiplying 30 to level download way multiplying 3100 exit is three layer gold and 3100 exit is three layer gold and 3100 exit is three layer gold and 3720 Just One Level Downloads Pay 210 SIM For No You Can Take Care No One Will Donate 0 But In This Case Not To Plu 1920 So Ifin Notice Here To Solve This Problem You To Things From Top Unmute To Go To The Button Buy Multiplying Buy Multiplying Buy Multiplying 10th 10th that Sapoch for Hair Oil to Multiplicative that Sapoch for Hair Oil to Multiplicative 10.29 Absolutely Spent Plus 9 War 30 10.29 Absolutely Spent Plus 9 War 30 Time Pred World Play List 10 and Sind Time Pred World Play List 10 and Sind Side Interview 39392 Benefits Elephant Side Interview 39392 Benefits Elephant Day This Gurjar Simply 892 This Aspect's 06 Day This Gurjar Simply 892 This Aspect's 06 2394 10 Round View To Multiply Diesel 2394 10 Round View To Multiply Diesel 2010 Network's 087 2010 Network's 087 2013 Entertain Any Thirty Plus 12331 Promise Solution Will Be From Top To Developer Now Will Go Through How We Will Do the Free Mode Traversal and Solve This Problem Solving This Problem Needs Someone You Will Want to Tell Someone Else Will Give the Sum of History Numbers What Formal Wear Is First Real Dob Total Workers Want to Tell Some Plus 30 Total Review Messages Variable 30 Total Review Messages Variable 30 Total Review Messages Variable Total Song Dushman Will Apply For Each Not Every Total Song Dushman Will Apply For Each Not Every Note Nandish Together Will Apply To Note Nandish Together Will Apply To Enrich To The Lip Note Sun First And Total 10 Enrich To The Lip Note Sun First And Total 10 Days Indian Old Varna Movie Days Indian Old Varna Movie 120000 Classroom Balaghat Is Three Layer Stree 120000 Classroom Balaghat Is Three Layer Stree Ya Upvas To Both Side Free MP3 Ya Upvas To Both Side Free MP3 Stay in Accept This Name Is In Father Stay in Accept This Name Is In Father Snowden Choli Member Third Quarter Se Snowden Choli Member Third Quarter Se Input From Next Not For No Fear To Input From Next Not For No Fear To Calculate The New Name Day 123 * 10:30 Calculate The New Name Day 123 * 10:30 Classroom Spent Sexual To Part To Both Sides Classroom Spent Sexual To Part To Both Sides Of Its Children 100 3902 Pass Of Its Children 100 3902 Pass Decide And that now has been quite reversal means left that now has been quite reversal means left side to leave them to keep from nowhere to go to the left side to leave them to keep from nowhere to go to the left parties 66 vacancy too parties 66 vacancy too left and right is channel date means that is a left and right is channel date means that is a lip note calculation of doom improved time both lip note calculation of doom improved time both of this of this of this thing is the name will get 1000 b-39 or fruit pahal net is 8396 396 them bread answer total time so total song.com edition hair soft 96 aaya 2nd year due to that nakul computing and go to right side And Health 28 Oil Facility Name Is Absolutely Near 12392 2398 Lad Follow Notice Forces Posts That And Obviously Right Side Nothing Is Late So Dainik Tourist 72 Laptop Distribution Odd And Exit Poll Apply Both The Islamic Katu Na Mintu Ten Plus Two Wealth Plus Total Swapn Dosh Nau Vid Swapn Dosh Nau Vid Swapn Dosh Nau Vid 394 * 10:30 3940 Plus Daru 12394 70 60 394 * 10:30 3940 Plus Daru 12394 70 60 For Add Vid Vid Total Sum Total Semi-solid 396 For Add Vid Vid Total Sum Total Semi-solid 396 Shyam To End Dar Free Shyam To End Dar Free Phone No Phone No 84 84 Ki End 7th Ki End 7th 126 Party Find A Control Your Hair And 126 Party Find A Control Your Hair And Will Go To The Right Side Will Go To The Right Side Will Go To The Right Side Three Layer Name Person * 10:30 Class Fruit Will Notice That Does One Is The Lymph Node Time This Bread Or Hotel 100% Whole Raw Discuss And You Will Be Our Total Saag Pushpi * Return Result Recording And Sample Function Newton Function Newton Function Newton Right Words When Will Pass Through Turn The Nam Right Words When Will Pass Through Turn The Nam Officer But Think You Can Simply Eternship Officer But Think You Can Simply Eternship Route Left and Right Vatan Lal Mirch Speed Route Left and Right Vatan Lal Mirch Speed Jali Apne Day Time Will Calculate Very Jali Apne Day Time Will Calculate Very Updating 19 Na Mintu Na Mintu Ten Plus Updating 19 Na Mintu Na Mintu Ten Plus Two Andher Nagari Total Semik Total Plus Nam Two Andher Nagari Total Semik Total Plus Nam It It It And Remove Right And This Traversal Show Business Loot Novel Pass Notice Name * Ten Plus To Hell And Forward To All U Something Na Mintu 10th Class Room Where And When Will The The The result century total Saumya can define result century total Saumya can define outside a global variable and you can keep updating find outside a global variable and you can keep updating find time complexity they need to time complexity they need to swim wear visiting below green node just once a come new-year coating brother milk according new-year coating brother milk according parts and total time now difference global parts and total time now difference global variable outside pimple variable outside pimple variable outside pimple calling is pre-order real family and friends and abiding total time third | 2024-03-21 11:39:14 | 129 | Leetcode 129 | Sum Root to Leaf Numbers |